<template>
  <m-dialog ref="editDialog" :title="title" v-bind="$attrs" @sure="handleSaveEdit">
    <m-form ref="formRef" :items="items" v-model="query" v-loading="loading"></m-form>
  </m-dialog>
</template>

<script>
import { saveRoster } from '@/api/system'
import { mapGetters } from 'vuex'
import {
  getSalaryLevelDict
} from '@/api/salary'
import {
  getJobLevel,
  getPositionCategory,
  getPersonnelCategory,
  getPositionSequence,
  getJobName
} from '@/api/dictionary'

import DICT from '@/utils/dict'

export default {
  name: 'roster-edit',
  props: {
    title: {
      type: String,
      default: '新增'
    }
  },
  data () {
    return {
      query: {},
      isEdit: false,
      loading: false,
      dict: {},
      employeeStatus: []
    }
  },
  computed: {
    ...mapGetters(['organizationTree']),
    items () {
      return [
        {
          prop: 'parentOrganizationName',
          hidden: true
        },
        {
          prop: 'parentOrganizationNo',
          hidden: true
        },
        {
          prop: 'deptName',
          hidden: true
        },
        {
          label: '部门名称',
          prop: 'organizationNo',
          type: 'cascader',
          options: {
            ref: 'organizationNo',
            filterable: true,
            clearable: true,
            placeholder: '请选择部门',
            options: this.organizationTree,
            showAllLevels: false,
            props: {
              emitPath: false,
              value: 'organizationNo',
              label: 'organizationName',
              children: 'child'
            }
          },
          handles: {
            change: this.onChange
          }
        },
        {
          label: '通行证号',
          prop: 'passes',
          type: 'input',
          options: { disabled: this.isEdit, placeholder: '请输入通行证号' },
          rules: [{ required: true, message: '请输入通行证号', trigger: 'blur' }]
        },
        {
          label: '员工名称',
          prop: 'employeeName',
          type: 'input',
          options: { disabled: this.isEdit, placeholder: '请输入员工名称' },
          rules: { required: true, message: '请输入员工名称', trigger: 'blur' }
        },
        {
          label: '工行时间',
          prop: 'tradeUnionsTime',
          type: 'datePicker',
          options: { disabled: this.isEdit, placeholder: '请选择工行时间' },
          rules: [{ required: true, message: '请选择工行时间', trigger: 'blur' }]
        },
        {
          label: '员工状态',
          prop: 'employeeStatus',
          type: 'select',
          options: {
            placeholder: '请选择员工状态',
            filterable: true,
            items: this.employeeStatus.map(e => {
              return {
                ...e,
                value: +e.value
              }
            })
          },
          rules: { required: true, message: '请输入人员类别', trigger: 'change' }
        },
        {
          label: '人员类别',
          prop: 'personnelCategory',
          type: 'select',
          options: {
            disabled: this.isEdit,
            placeholder: '请输入人员类别',
            filterable: true,
            items: this.dict.personnelCategory
          },
          rules: { required: true, message: '请输入人员类别', trigger: 'change' }
        },
        {
          label: '岗位名称',
          prop: 'postName',
          type: 'select',
          options: {
            placeholder: '请输入岗位名称',
            filterable: true,
            items: this.dict.jobName
          },
          rules: { required: true, message: '请输入岗位名称', trigger: 'change' }
        },
        {
          label: '岗位序列',
          prop: 'positionSequence',
          type: 'select',
          options: {
            placeholder: '请输入岗位序列',
            filterable: true,
            items: this.dict.positionSequence
          },
          rules: [{ required: true, message: '请输入岗位序列', trigger: 'change' }]
        },
        {
          label: '岗位类别',
          prop: 'positionCategory',
          type: 'select',
          options: {
            placeholder: '请输入岗位类别',
            filterable: true,
            items: this.dict.positionCategory
          },
          rules: [{ required: true, message: '请输入岗位类别', trigger: 'change' }]
        },
        {
          label: '职务层级',
          prop: 'jobLevel',
          type: 'select',
          options: {
            placeholder: '请输入职务层级',
            filterable: true,
            items: this.dict.jobLevel
          },
          rules: [{ required: true, message: '请输入职务层级', trigger: 'change' }]
        },
        {
          label: '薪酬档次',
          prop: 'salaryCategory',
          type: 'select',
          options: {
            placeholder: '薪酬档次',
            items: this.dict.gradeDict
          },
          rules: [{ required: true, message: '请输入薪酬档次', trigger: 'blur' }]
        },
        {
          label: '薪酬级别',
          prop: 'salaryLevel',
          type: 'select',
          options: {
            placeholder: '薪酬级别',
            items: this.dict.levelDict
          },
          rules: [{ required: true, message: '请输入薪酬级别', trigger: 'blur' }]
        }
      ]
    }
  },
  methods: {
    async open (item) {
      this.$refs.editDialog.open()
      this.loading = true
      await this.getEmployeeStatus()
      this.query = this.items.reduce((res, item) => {
        res[item.prop] = null
        return res
      }, {})
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
      this.isEdit = Boolean(item)
      await this.getDict()
      await this.getOtherDict()
      if (item) {
        Object.keys(this.query).forEach(key => {
          this.query[key] = item[key]
        })
        this.query.personnelCode = item.personnelCode
      }
      this.loading = false
    },
    async getEmployeeStatus () {
      try {
        const data = await DICT.get('EMPLOYEE_STATUS')
        this.employeeStatus = data
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleSaveEdit () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { tradeUnionsTime, ...obj } = this.query
        const date = new Date(tradeUnionsTime)
        // 获取年、月、日
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
        const day = String(date.getDate()).padStart(2, '0')
        try {
          await saveRoster({
            ...obj,
            tradeUnionsTime: `${year}${month}${day}`
          })
          this.$message.success('保存成功')
          this.$refs.editDialog.close()
          this.$emit('refresh')
        } catch (error) {
          this.$message.error(error)
        }
      })
    },
    onChange () {
      const nodes = this.$refs.formRef.$refs.organizationNo.getCheckedNodes()
      const node = nodes[0].data
      const parent = nodes[0].parent.data
      Object.assign(this.query, {
        organizationNo: node.organizationNo,
        deptName: node.organizationName,
        parentOrganizationName: parent.organizationName,
        parentOrganizationNo: parent.organizationNo
      })
    },
    async getDict () {
      try {
        const { data } = await getSalaryLevelDict()
        const dict = { ...this.dict }
        Object.assign(dict, {
          gradeDict: data.gradeDict.map(e => {
            return {
              label: e,
              value: e
            }
          }),
          levelDict: data.levelDict.map(e => {
            return {
              label: e,
              value: e
            }
          })
        })
        this.dict = dict
      } catch (error) {
        this.$message.error(error)
      }
    },
    async getOtherDict () {
      const lists = [
        { key: 'jobLevel', fn: getJobLevel },
        { key: 'positionCategory', fn: getPositionCategory },
        { key: 'personnelCategory', fn: getPersonnelCategory },
        { key: 'positionSequence', fn: getPositionSequence },
        { key: 'jobName', fn: getJobName }
      ]
      try {
        const result = await Promise.all(lists.map(item => item.fn()))
        const dict = { ...this.dict }
        Object.assign(dict, lists.reduce((res, item, index) => {
          res[item.key] = result[index].data.map(e => ({ label: e, value: e }))
          return res
        }, {}))
        this.dict = dict
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
