<template>
  <div class="app-container">
    <!--头部选项-->
    <div class="head-container">
      <div>
        <el-input v-model="query.username" placeholder="用户名称" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.identificationNum" placeholder="身份证号码" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="crud.toQuery" />
        <el-date-picker v-model="startExpirationDateQuery" type="month" value-format="yyyy-MM" placeholder="选择有效日期终-开始" class="filter-item" @change="changeStartExpirationDateQuery" />
        <el-date-picker v-model="endExpirationDateQuery" type="month" value-format="yyyy-MM" placeholder="选择有效日期终-结束" class="filter-item" @change="changeEndExpirationDateQuery" />
        <query :crud="crud" />
      </div>
      <crud :permission="permission">
        <el-button slot="right" class="filter-item" icon="el-icon-download" type="warning" @click="dialogVisible = true">
          导出数据
        </el-button>
      </crud>
    </div>
    <!--表格内容-->
    <CustomTable ref="customTable" :col-configs="colConfigs" :columns="columns" :crud="crud" :row-class-name="getTableRowClassName">
      <el-table-column v-if="checkPermission(permission.edit)" slot="operation" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <Edit :permission="permission" :data="scope.row" :disabled-edit="false" />
        </template>
      </el-table-column>
    </CustomTable>
    <pagination />
    <el-dialog :title="crud.status.title" :visible.sync="crud.status.editor > 0" :before-close="crud.cancelCU">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="姓名：" prop="username">
          <el-input v-model="form.username" placeholder="填写姓名" type="text" />
        </el-form-item>
        <el-form-item label="身份证号码：" prop="identificationNum">
          <el-input v-model="form.identificationNum" placeholder="填写身份证号码" type="text" />
        </el-form-item>
        <el-form-item label="学历：" prop="education">
          <el-select v-model="form.education" placeholder="填写学历">
            <el-option v-for="item in educationDicList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业：" prop="major">
          <el-input v-model="form.major" placeholder="填写专业" type="text" />
        </el-form-item>
        <el-form-item label="职称：" prop="certificateName">
          <el-select v-model="form.certificateName" placeholder="填写职称">
            <el-option v-for="item in certificateNameDicList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="级别/项目/代号：" prop="levelList">
          <el-cascader v-model="levelList" :options="levelOptions" @change="changeLevel" />
        </el-form-item>
        <el-form-item label="证书编号：" prop="certificateNum">
          <el-input v-model="form.certificateNum" placeholder="填写证书编号" type="text" />
        </el-form-item>
        <el-form-item label="有效期：" prop="expirationDate">
          <el-date-picker v-model="expirationDate" type="monthrange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM" @change="changeExpirationDate" />
        </el-form-item>
        <el-form-item label="发换证日期：" prop="renewalDate">
          <el-date-picker v-model="form.renewalDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期" />
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-select v-model="form.remarks" placeholder="填写备注">
            <el-option v-for="item in remarksDicList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="crud.cancelCU">
          取 消
        </el-button>
        <el-button type="primary" @click="crud.submitCU">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog width="60%" :visible.sync="dialogVisible" title="自定义导出选项" @close="closeExportDialog">
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" style="margin: 5px" @change="handleCheckAllChange">
        全选
      </el-checkbox>
      <div style="margin: 15px 0;" />
      <el-checkbox-group v-model="checkedOptions" @change="handleCheckedChange">
        <el-checkbox v-for="options in exportOptionsData" :key="options.value" border :label="options.value" style="margin: 5px">
          {{ options.label }}
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="exportCertificate">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { form, header, presenter } from '@/components/Crud/crud'
import Crud from '@/components/Crud'
import Query from '@/components/Crud/Query'
import Edit from '@/components/Crud/Edit'
import CustomTable from '@/components/Crud/Table'
import Pagination from '@/components/Crud/Pagination'
import CrudCertificate, { exportExcel } from '@/api/certificate'
import { getTreeList } from '@/api/dic_muti_level_directory'
import { getLastDayByDate, parseTime, downloadFile } from '@/utils'
import { getDicDataListByTypeName } from '@/api/dic_data'
// crud交由presenter持有
const defaultCrud = presenter(CRUD({
  title: '证书',
  url: '/certificate/list',
  orderBy: ['id asc'],
  crudMethod: { ...CrudCertificate }
}))

// 设置初始form
const defaultForm = form({})

export default {
  name: 'CertificateList',
  components: { Pagination, Query, Crud, CustomTable, Edit },
  mixins: [defaultCrud, defaultForm, header()],
  data() {
    const validatorLevelList = (rule, value, callback) => {
      if (!this.levelList.length) {
        callback(new Error('请输入级别/项目/代号'))
      } else {
        callback()
      }
    }
    const validatorExpirationDate = (rule, value, callback) => {
      if (!this.expirationDate.length) {
        callback(new Error('请输入有效日期'))
      } else {
        callback()
      }
    }
    return {
      colConfigs: [
        { prop: 'username', label: '姓名', align: 'center', width: 50 },
        { prop: 'identificationNum', label: '身份证号码', align: 'center' },
        { prop: 'education', label: '学历', align: 'center', width: 50 },
        { prop: 'major', label: '专业', align: 'center' },
        { prop: 'certificateName', label: '职称', align: 'center', width: 60 },
        { prop: 'level', label: '级别', align: 'center', width: 50 },
        { prop: 'project', label: '项目', align: 'center' },
        { prop: 'code', label: '代号', align: 'center', width: 50 },
        { prop: 'certificateNum', label: '证书编号', align: 'center' },
        { prop: 'startExpirationDate', label: '有效日期', align: 'center',
          formatter: (row, column, cellValue) => {
            return (cellValue ? cellValue.substring(0, cellValue.length - 3) : '') + ' 至 ' + (row.endExpirationDate ? row.endExpirationDate.substring(0, row.endExpirationDate.length - 3) : '')
          }
        },
        { prop: 'renewalDate', label: '发换证日期', align: 'center', width: 50 },
        { prop: 'remarks', label: '备注', align: 'center', width: 60 },
        { slot: 'operation' }
      ],
      permission: {
        add: ['certificate:list:add'],
        edit: ['certificate:list:update'],
        del: ['certificate:list:delete']
      },
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        identificationNum: [{ required: true, message: '请输入身份证号码', trigger: 'blur' }],
        education: [{ required: true, message: '请输入学历', trigger: 'blur' }],
        major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
        certificateName: [{ required: true, message: '请输入职称', trigger: 'blur' }],
        levelList: [{ validator: validatorLevelList, required: true, trigger: 'blur' }],
        certificateNum: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
        expirationDate: [{ validator: validatorExpirationDate, required: true, trigger: 'blur' }],
        renewalDate: [{ required: true, message: '请输入发换证日期', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      levelList: [],
      levelOptions: [],
      expirationDate: [],
      educationDicList: [],
      certificateNameDicList: [],
      remarksDicList: [],
      expirationDateQuery: [],
      startExpirationDateQuery: '',
      endExpirationDateQuery: '',
      dialogVisible: false,
      checkAll: [],
      checkedOptions: [],
      isIndeterminate: false,
      exportOptionsData: [
        { label: '姓名', value: 'username' },
        { label: '身份证号码', value: 'identificationNum' },
        { label: '学历', value: 'education' },
        { label: '专业', value: 'major' },
        { label: '职称', value: 'certificateName' },
        { label: '级别', value: 'level' },
        { label: '项目', value: 'project' },
        { label: '代号', value: 'code' },
        { label: '证书编号', value: 'certificateNum' },
        { label: '有效日期开始', value: 'startExpirationDate' },
        { label: '有效日期终止', value: 'endExpirationDate' },
        { label: '发换证日期', value: 'renewalDate' },
        { label: '备注', value: 'remarks' }
      ]
    }
  },
  created() {
    this.crud.optionShow = {
      add: true,
      edit: false,
      del: true
    }
    getTreeList({ superParentLabel: 'certificate' }).then(data => {
      this.levelOptions = data
    })
    this.initDicDataList()
  },
  methods: {
    /**
     * 初始化字典相关列表
     */
    initDicDataList() {
      getDicDataListByTypeName({ typeCode: 'education' }).then(data => { this.educationDicList = data })
      getDicDataListByTypeName({ typeCode: 'certificate_name' }).then(data => { this.certificateNameDicList = data })
      getDicDataListByTypeName({ typeCode: 'certificate_remarks' }).then(data => { this.remarksDicList = data })
    },
    [CRUD.HOOK.afterToAdd]() {
      // 初始化数据
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
      this.levelList = []
      this.expirationDate = []
    },
    [CRUD.HOOK.beforeToEdit]() {
      // 初始化数据
      this.levelList = [this.form.level, this.form.project, this.form.code]
      this.expirationDate = this.form.startExpirationDate ? [this.form.startExpirationDate, this.form.endExpirationDate] : []
    },
    changeLevel(value) {
      this.form.level = value[0]
      this.form.project = value[1]
      this.form.code = value[2]
    },
    changeExpirationDate(value) {
      if (value) {
        this.form.startExpirationDate = value[0] + '-01'
        this.form.endExpirationDate = getLastDayByDate(value[1])
      } else {
        this.form.startExpirationDate = ''
        this.form.endExpirationDate = ''
      }
    },
    /**
     * 更改行颜色
     * @param row
     * @returns {string}
     */
    getTableRowClassName({ row }) {
      const endExpirationDate = new Date(row.endExpirationDate)
      const now = new Date()
      if (endExpirationDate.getFullYear() < now.getFullYear() || (endExpirationDate.getFullYear() === now.getFullYear() && endExpirationDate.getMonth() <= now.getMonth())) {
        return 'table-row-color-orange'
      }
      return ''
    },
    changeStartExpirationDateQuery(value) {
      if (value) {
        this.query.startExpirationDate = getLastDayByDate(value)
      } else {
        this.query.startExpirationDate = ''
      }
    },
    changeEndExpirationDateQuery(value) {
      if (value) {
        this.query.endExpirationDate = getLastDayByDate(value)
      } else {
        this.query.endExpirationDate = ''
      }
    },
    closeExportDialog() {
      this.checkAll = false
      this.isIndeterminate = false
      this.checkedOptions = []
    },
    handleCheckAllChange(val) {
      if (val) {
        this.exportOptionsData.forEach(options => {
          this.checkedOptions.push(options.value)
        })
      } else {
        this.checkedOptions = []
      }
      this.isIndeterminate = false
    },
    handleCheckedChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.exportOptionsData.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.exportOptionsData.length
    },
    exportCertificate() {
      if (this.checkedOptions.length === 0) {
        this.$message.error('请选择导出项')
        return false
      }
      const sortOptions = []
      this.exportOptionsData.forEach(exportOptions => {
        this.checkedOptions.forEach(checkedOptions => {
          if (exportOptions.value === checkedOptions) {
            sortOptions.push(checkedOptions)
          }
        })
      })
      exportExcel(sortOptions).then(data => {
        this.dialogVisible = false
        downloadFile(data, parseTime(new Date()) + '-' + this.crud.title + '数据', 'xlsx')
      })
    }
  }
}
</script>

<style scoped>

</style>
