<!--
/*
* @Author: zwq
* @Date: 2020-12-29 15:41:11
 * @LastEditTime: 2022-07-28 19:02:55
 * @LastEditors: gtz
* @Description: 拆分了搜索区和功能按钮区，增加了toptitle
*/
-->
<template>
  <div class="app-container">
    <head-form
      :form-config="headFormConfig"
      @headBtnClick="btnClick"
      @importFile="handleImportResult"
      @importFileError="handleImportResult"
    />
    <base-table
      :top-btn-config="topBtnConfig"
      :page="listQuery.current"
      :limit="listQuery.size"
      :table-config="tableProps"
      :table-data="list"
      :is-loading="listLoading"
      @clickTopBtn="clickTopBtn"
    >
      <method-btn slot="handleBtn" :width="calculateWidth" :method-list="tableBtn" @clickBtn="handleClick" />
    </base-table>

    <!-- footer part -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList()"
    />
    <staff-add v-if="addOrUpdateVisible" ref="addOrUpdate" :role-list="roleList" @refreshDataList="getList" />
  </div>
</template>

<script>
import i18n from '@/lang'
import { list, del, getRoleList } from '@/api/basicData/GroupModule/staff'
import staffAdd from './components/staff-add.vue'
import moment from 'moment'
import HeadForm from '@/components/basicData/HeadForm'
import BaseTable from '@/components/BaseTable'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import MethodBtn from '@/components/BaseTable/subcomponents/MethodBtn'
import basicData from '@/filters/basicData'
import { nonEmptyFilter, timeFormatter } from '@/filters'

// import DictFilter from '@/components/BaseTable/subcomponents/DataDictFilter'
// import { workerRoleList } from '@/api/dict'
/**
 * 表格表头配置项 TypeScript接口注释
 * tableConfig<ConfigItem> = []
 *
 * Interface ConfigItem = {
 *  prop: string,
 *  label: string,
 *  width: string,
 *  align: string,
 *  subcomponent: function,
 *  filter: function
 * }
 *
 *
 */

const topBtnConfig = [
  {
    type: 'add',
    btnName: 'btn.add'
  }
]

const tableBtn = [
  {
    type: 'detail',
    btnName: 'btn.detail'
  },
  {
    type: 'edit',
    btnName: 'btn.edit'
  },
  {
    type: 'delete',
    btnName: 'btn.delete'
  }
]
const tableProps = [
  {
    prop: 'createTime',
    label: i18n.t('module.basicData.staff.CreateTime'),
    filter: timeFormatter
  },
  {
    prop: 'name',
    label: i18n.t('module.basicData.staff.Name')
  },
  {
    prop: 'code',
    label: i18n.t('module.basicData.staff.EmployeeID')
  },
  // {
  //   prop: 'roleName',
  //   label: i18n.t('module.basicData.staff.role'),
  //
  //   // subcomponent: DictFilter,
  //   // filter: workerRoleList
  // },
  {
    prop: 'sex',
    label: i18n.t('module.basicData.staff.Gender'),
    filter: basicData('sex')
  },
  {
    prop: 'entryTime',
    label: i18n.t('module.basicData.staff.EntryTime'),
    filter: val => moment(val).format('YYYY-MM-DD') || '-'
  },
  {
    prop: 'telephone',
    label: i18n.t('module.basicData.staff.Telephone'),
    filter: nonEmptyFilter
  },
  {
    label: i18n.t('module.basicData.staff.State'),
    prop: 'status',
    filter: basicData('registerState')
  },
  {
    prop: 'department',
    label: i18n.t('module.basicData.staff.Dept'),
    filter: nonEmptyFilter
  },
  {
    prop: 'email',
    label: i18n.t('module.basicData.staff.Email'),
    filter: nonEmptyFilter
  },
  {
    prop: 'wechatCode',
    label: i18n.t('module.basicData.staff.Wechat'),
    filter: nonEmptyFilter
  },
  {
    prop: 'majorArr',
    label: i18n.t('module.basicData.staff.Profession'),
    filter: nonEmptyFilter
  },
  {
    prop: 'workshop',
    label: i18n.t('module.basicData.staff.Workshop'),
    filter: nonEmptyFilter
  },
  {
    prop: 'onDuty',
    label: i18n.t('module.basicData.staff.onDuty'),
    filter: basicData('onDuty')
  },
  {
    prop: 'description',
    label: i18n.t('module.basicData.visual.Remarks'),
    filter: nonEmptyFilter
  }
]

export default {
  name: 'Staff',
  components: { Pagination, BaseTable, MethodBtn, HeadForm, staffAdd },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      addOrUpdateVisible: false,
      topBtnConfig,
      tableBtn,
      trueWidth: 200,
      tableProps,
      list: [],
      total: 0,
      listLoading: true,
      roleList: [],
      listQuery: {
        current: 1,
        size: 20,
        name: '', // 姓名（关键字）
        status: '' // 状态：在职、离职
      },
      headFormConfig: [
        {
          type: 'input',
          label: i18n.t('module.basicData.staff.EmployeeName'),
          placeholder: this.$t('module.basicData.staff.EmployeeName'),
          param: 'name'
        },
        {
          type: 'select',
          label: i18n.t('module.basicData.staff.State'),
          selectOptions: [
            { id: 1, name: i18n.t('module.basicData.staff.OnJob') },
            { id: 0, name: i18n.t('module.basicData.staff.Dimission') }
          ],
          param: 'status'
        },
        {
          type: 'button',
          btnName: 'btn.search',
          name: 'search',
          color: 'primary'
        },
        {
          type: 'uploadButton',
          btnName: 'btn.import',
          action: '/api/basic/worker/importInfo',
          name: 'import',
          nameField: 'excel', // 设置上传的参数名,接口文档里是excel
          color: 'success'
        },
        {
          type: 'button',
          btnName: i18n.t('module.basicData.staff.downloadTemplate'),
          name: 'download'
        }
      ],
      headFormValue: {}
    }
  },
  computed: {
    calculateWidth() {
      return this.tableBtn.length * 40 // 操作列的每个按钮宽度40
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    handleClick(raw) {
      console.log(raw)
      if (raw.type === 'delete') {
        this.$confirm(
          `${this.$t('module.basicData.visual.TipsBefore')}[${raw.data.name}]?`,
          this.$t('module.basicData.visual.Tips'),
          {
            confirmButtonText: this.$t('module.basicData.visual.confirmButtonText'),
            cancelButtonText: this.$t('module.basicData.visual.cancelButtonText'),
            type: 'warning'
          }
        )
          .then(() => {
            del(raw.data.id).then(response => {
              this.$message({
                message: this.$t('module.basicData.visual.success'),
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getList()
                }
              })
            })
          })
          .catch(() => {})
      } else if (raw.type === 'detail') {
        this.addNew(raw.data.id, true)
      } else {
        this.addNew(raw.data.id)
      }
    },
    getList() {
      this.listLoading = true
      this.listQuery.name = this.headFormValue.name
      this.listQuery.status = this.headFormValue.status
      list(this.listQuery).then(response => {
        if (response.data.records) {
          this.list = response.data.records
          this.list.forEach(item => {
            if (item.major) {
              item.majorArr = item.major.toString()
            }
          })
        } else {
          this.list.splice(0, this.list.length)
        }
        this.total = response.data.total
        this.listLoading = false
      })
    },
    async getRole() {
      const res = await getRoleList()
      this.roleList = res.data.records
      this.getList()
    },
    btnClick(val) {
      this.headFormValue = val
      if (this.headFormValue.btnName === 'search') {
        this.getList()
      } else if (this.headFormValue.btnName === 'download') {
        this.$message({
          message: this.$t('module.basicData.staff.startDownload'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            // 下载模板
            import('@/assets/excels/staff_template.xlsx').then(({ default: src }) => {
              const a = document.createElement('a')
              a.href = src
              document.body.appendChild(a)
              a.download = '员工信息模板文件' // 设置文件名
              a.click()
              document.body.removeChild(a)
            })
          }
        })
      }
    },
    clickTopBtn(val) {
      if (val === 'add') {
        this.addNew()
      }
    },

    handleImportResult({ response, file, fileList }) {
      if (response.data) {
        this.$message({
          message: this.$t('module.basicData.visual.upload.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getList()
          }
        })
      } else {
        this.$message({
          message: this.$t('module.basicData.visual.upload.failedAndReason1'),
          type: 'error',
          duration: 2500
        })
      }
    },

    // 新增 / 修改
    addNew(id, isDisabled) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, isDisabled)
      })
    }
  }
}
</script>
