<template>
  <div>
    <card-container>
      <vxe-toolbar>
        <template #buttons>
          <el-date-picker v-model="select.year"
            type="year" size="small" value-format="yyyy"
            placeholder="年份" format="yyyy">
          </el-date-picker>
          <el-select style="width:250px;margin-left:6px"  size="small" v-model="select.department_id" placeholder="请选择">
            <el-option v-for="item in departments" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button icon="el-icon-search" type="primary" plain size="small" style="margin-left: 6px;"
            @click="getList">搜索</el-button>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAdd = true">新增</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px;"
        :loading="loading"
        keep-source
        show-overflow
        :column-config="{ resizable: true }"
        :edit-rules="validRules"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
        :align="allAlign"
        :data="tableData"
      >
        <vxe-column type="seq" width="58" align="center" />
        <vxe-column field="year" width="170" title="年份" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" type="year" v-model="row.year" size="small" value-format="yyyy" />
          </template>
        </vxe-column>

        <vxe-column field="work_year" title="工作年限" width="120" :edit-render="{name: 'input', attrs: { type: 'number' }}" />

        <vxe-column field="should_holiday_days" width="140" title="应休假天数" :edit-render="{ name: 'input', attrs: { type: 'number' } }" />
       <vxe-column field="plan_start_time" width="170" title="计划安排开始时间" :edit-render="{}">
         <template #edit="{ row }">
           <el-date-picker style="width: 100%;" type="date" v-model="row.plan_start_time" size="small" value-format="yyyy-MM-dd" />
         </template>
       </vxe-column>
        <vxe-column field="plan_end_time" width="170" title="计划安排结束时间" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" type="date" v-model="row.plan_end_time" size="small" value-format="yyyy-MM-dd" />
          </template>
        </vxe-column>

        <vxe-column field="admin.name" width="170" title="创建人" :edit-render="{}">
        </vxe-column>

        <vxe-column field="operate" title="操作" min-width="220" fixed="right">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)">保存</el-button>
              <el-button size="small" type="primary" plain @click="cancelRowEvent(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="destroyRowEvent(row)">删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;"
        :current-page.sync="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size.sync="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="e => {
          select.page_size = e;
          select.page = 1;
          getList();
        }"
        @current-change="e => {
          select.page = e;
          getList();
        }"
      />
    </card-container>
    <addYearHoliday ref="addYearHoliday" :is-show.sync="isShowAdd" @refresh="getList" />
  </div>
</template>

<script>
import { index as departmentIndex } from '@/api/department'
import { deepCopy } from '@/utils'
import { index, save, destroy } from '@/api/yearHoliday'
import addYearHoliday from './components/addYearHoliday.vue'
import axios from "axios";
import {getToken} from "@/utils/auth";
export default {
  components: {
    addYearHoliday
  },
  data() {
    return {
      departments: [],
      isShowAdd: false,

      loading: false,
      select: {
        page: 1,
        page_size: 20,
        year:new Date().getFullYear()+'',
        department_id:''
      },
      total: 0,
      allAlign: null,
      tableData: [],
      validRules: {
        year: [
          { required: true, message: '请输入年份' }
        ],
        work_year: [
          { required: true, message: '请输入工作年限' }
        ],
        should_holiday_days: [
          { required: true, message: '请输入应休假天数' }
        ],
        plan_start_time: [
          { required: true, message: '请输入计划安排开始时间' }
        ],
        plan_end_time: [
          { required: true, message: '请输入计划安排结束时间' }
        ]
      },
      form: {
        id: '',
        year: '',
        work_year: '',
        should_holiday_days: '',
        plan_start_time: '',
        plan_end_time: '',
      }
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    }
  },
  created() {
    this.getDepartments()
    this.getList()
  },
  methods: {

    editRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },

    async getDepartments() {
      try {
        this.departments = await departmentIndex({
          page: 1,
          page_size: 9999
        })
        this.departments.unshift({
          id:'',
          name:'全部'
        })
      } catch (err) {
        console.error(err)
      }
    },
    async getList() {
      this.loading = true
      try {
        const res = await index({
          page:this.select.page,
          page_size:this.select.page_size,
          'filter[0][key]':'year',
          'filter[0][op]':'eq',
          'filter[0][value]':this.select.year?this.select.year:'',
          'filter[1][key]':'department_id',
          'filter[1][op]':'eq',
          'filter[1][value]':this.select.department_id?this.select.department_id:'',
        })
        this.tableData = res.data
        this.total = res.total
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },

    async saveRowEvent(row) {
      try {
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        const form = deepCopy(this.form)
        for (const key in form) {
          form[key] = row[key]
        }
        if (!form.password) {
          delete form.password
        }
        this.loading = true
        await save(form)
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        this.loading = true
        if (row.id) {
          await destroy({
            id: row.id
          })
          await this.getList()
        } else {
          console.log(row)
          this.tableData.splice(this.tableData.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY), 1)
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
