<template>
  <div class="white" :class="{ 'pa-3': !panorama.organizationNo }">
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="onSearch">
      <template #button>
        <m-button type="primary" icon="el-icon-plus" plain @click="onAdd">新增</m-button>
        <el-upload class="el-button pa-0" action="#" :show-file-list="false" :http-request="onImport">
          <m-button type="primary" icon="el-icon-upload2" plain :loading="importLoading">上传</m-button>
        </el-upload>
        <m-button type="primary" icon="el-icon-download" plain @click="onExport" :loading="exportLoading">导出</m-button>
        <m-button type="primary" icon="el-icon-download" plain @click="onDownload" :loading="downloadLoading">下载模板</m-button>
      </template>
    </m-search>
    <m-table
      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 #actions="{ row }">
        <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>
  </div>
</template>

<script>
import { downloadFile } from '@/utils'
import rosterEdit from './rosterEdit.vue'
import {
  getRosterList,
  deleteRoster,
  uploadRoster,
  exportRoster,
  downloadRosterTemplate
} from '@/api/system'
export default {
  name: 'sys-roster',
  components: { rosterEdit },
  data () {
    return {
      panorama: {},
      importLoading: false,
      exportLoading: false,
      downloadLoading: false,
      title: '',
      searchItems: [
        {
          label: '员工名称',
          options: {
            placeholder: '请输入员工名称'
          },
          prop: 'employeeName',
          type: 'input'
        },
        {
          label: '机构名称',
          options: {
            placeholder: '请输入机构名称'
          },
          prop: 'organizationName',
          type: 'input'
        }
      ],
      loading: false,
      searchValues: {
        employeeName: null
      },
      headers: [
        // { 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' },
        { label: '操作', prop: 'actions' }
      ],
      itemData: {},
      items: [],
      orders: [],
      pageInfo: {
        size: 10,
        current: 1
      },
      total: 0
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 执行全景初始化操作
    onInitPanorama (organizationNo, employeeNo) {
      this.panorama = { organizationNo, employeeNo }
    },
    async init () {
      this.loading = true
      try {
        const { data } = await getRosterList({
          page: { ...this.pageInfo, orders: this.orders },
          entity: {
            ...this.searchValues
          }
        })
        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('确定删除该员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteRoster({ personnelCode: item.personnelCode })
          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()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
