<template>
  <div class="white" :class="{ 'pa-3': !$attrs.panorama }">
    <m-search v-if="!$attrs.panorama" :items="searchItems" v-model="searchValues" class="mb-3" @search="onSearch"></m-search>
    <m-table
      :cardTitle="cardTitle || undefined"
      v-loading="loading"
      row-key="id"
      :items="items"
      :headers="headers"
      :page-size="pageInfo.size"
      :page-current="pageInfo.current"
      :total="total"
      :default-sort="{ prop: 'sort', order: 'ascending' }"
      @page-change="pageChange"
    >
      <template #card-tools v-if="!$attrs.panorama">
        <m-button type="orange" size="small" icon="el-icon-plus" @click="onAdd">新增</m-button>
        <el-upload class="el-button pa-0" action="#" :show-file-list="false" :http-request="onImport">
          <m-button type="orange" size="small" icon="el-icon-upload2" :loading="importLoading">上传</m-button>
        </el-upload>
        <m-button type="orange" size="small" icon="el-icon-download" @click="onExport" :loading="exportLoading">导出</m-button>
        <m-button type="orange" size="small" icon="el-icon-download" @click="onDownload" :loading="downloadLoading">下载模板</m-button>
        <m-button type="orange" size="small" icon="el-icon-setting" @click="onChange">变更记录</m-button>
      </template>
      <template #actions="{ row }" v-if="!$attrs.panorama">
        <m-button text type="primary" @click="onEdit(row)">编辑</m-button>
        <m-button text type="danger" @click="onDelete(row)">删除</m-button>
      </template>
    </m-table>
    <RosterEdit ref="rosterEditRef" :title="title" @refresh="init"></RosterEdit>
    <RosterVersion ref="rosterVersionRefs"></RosterVersion>
  </div>
</template>

<script>
import { downloadFile } from '@/utils'
import RosterEdit from './rosterEdit.vue'
import RosterVersion from './rosterVersion.vue'
import {
  getRosterList,
  deleteRoster,
  uploadRoster,
  exportRoster,
  downloadRosterTemplate
} from '@/api/system'
import { mapGetters } from 'vuex'
export default {
  name: 'sys-roster',
  components: { RosterEdit, RosterVersion },
  data () {
    return {
      importLoading: false,
      exportLoading: false,
      downloadLoading: false,
      title: '',
      loading: false,
      searchValues: {
        employeeName: null
      },
      itemData: {},
      items: [],
      orders: [],
      pageInfo: {
        size: 10,
        current: 1
      },
      total: 0,
      cardTitle: null // 用于全景视图显示
    }
  },
  computed: {
    ...mapGetters(['organizationTree']),
    searchItems () {
      return [
        {
          label: '员工名称',
          options: {
            placeholder: '请输入员工名称'
          },
          prop: 'employeeName',
          type: 'input'
        },
        {
          label: '部门名称',
          options: {
            filterable: true,
            clearable: true,
            placeholder: '请选择部门',
            options: this.organizationTree,
            showAllLevels: false,
            props: {
              emitPath: false,
              value: 'organizationNo',
              label: 'organizationName',
              children: 'child'
            }
          },
          prop: 'organizationNo',
          type: 'cascader'
        }
      ]
    },
    headers () {
      const header = [
        // { text: '一级机构', align: 'start', value: 'secondLevelBranch' },
        { label: '上级机构', prop: 'parentOrganizationName' },
        { label: '部门', prop: 'deptName' },
        { label: '员工名称', prop: 'employeeName' },
        { label: '人员类别', prop: 'personnelCategory' },
        { label: '岗位名称', prop: 'postName' },
        { label: '岗位序列', prop: 'positionSequence' },
        { label: '岗位类别', prop: 'positionCategory' },
        { label: '职务层级', prop: 'jobLevel' },
        { label: '通行证号', prop: 'passes' },
        { label: '工行时间', prop: 'tradeUnionsTimeText' },
        { label: '薪酬档次', align: 'center', prop: 'salaryCategory' },
        { label: '薪酬级别', align: 'center', prop: 'salaryLevel' }
      ]
      if (!this.$attrs.panorama) {
        header.push({ label: '操作', prop: 'actions' })
      }
      return header
    }
  },
  created () {
    // 全景视图终止自动调用
    if (this.$attrs.panorama) {
      return
    }
    this.init()
  },
  methods: {
    // 执行全景初始化操作
    onInitPanorama (organizationNo, employeeNo, title) {
      this.cardTitle = title
      this.panorama = { organizationNo, employeeNo }
      if (employeeNo) {
        this.searchValues = {
          personnelCode: employeeNo
        }
      } else {
        this.searchValues = {
          organizationNo: organizationNo
        }
      }
      this.init()
    },
    async init () {
      this.loading = true
      const query = {}
      if (this.$attrs.panorama) {
        if (this.searchValues.personnelCode) {
          query.entity = {
            personnelCode: this.searchValues.personnelCode
          }
        }
        if (this.searchValues.organizationNo) {
          Object.assign(query, {
            organizationNo: this.searchValues.organizationNo
          })
        }
      } else {
        Object.assign(query, {
          entity: this.searchValues
        })
      }
      try {
        const { data } = await getRosterList({
          page: { ...this.pageInfo, orders: this.orders },
          ...query
        })
        this.items = data.records.map(e => {
          const date = new Date(e.tradeUnionsTime)
          // 获取年、月、日
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
          const day = String(date.getDate()).padStart(2, '0')
          return {
            ...e,
            tradeUnionsTimeText: `${year}年${month}月${day}日`
          }
        })
        this.total = data.total
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pageInfo.current = 1
      this.init()
    },
    onAdd () {
      this.title = '新增员工'
      this.$refs.rosterEditRef.open()
    },
    onEdit (item) {
      this.title = '编辑员工'
      this.$refs.rosterEditRef.open(item)
    },
    onDelete (item) {
      this.$confirm('确定删除该员工吗？', '提示').then(async () => {
        try {
          await deleteRoster({ personnelCode: item.personnelCode, employeeName: item.employeeName })
          this.init()
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error(error)
        }
      }).catch(() => {})
    },
    async onImport (response) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', response.file)
      try {
        await uploadRoster(formData)
        this.$message.success('导入成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.importLoading = false
      }
    },
    async onExport () {
      this.exportLoading = true
      try {
        const { data, name } = await exportRoster()
        downloadFile(data, name)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    async onDownload () {
      this.downloadLoading = true
      try {
        const { data, name } = await downloadRosterTemplate()
        downloadFile(data, name)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.downloadLoading = false
      }
    },
    pageChange (index) {
      this.pageInfo.current = index
      this.init()
    },
    onChange () {
      this.$refs.rosterVersionRefs.open(this.headers.slice(0, -1))
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
