<template>
  <div>
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="onSearch">
      <template #button>
        <el-upload class="el-button pa-0" action="#" :show-file-list="false" :http-request="onImport">
          <m-button type="primary" icon="el-icon-upload2" :loading="importLoading">导入手工数据</m-button>
        </el-upload>
        <m-button type="primary" icon="el-icon-download" :loading="downloadLoading" @click="onExport">导出手工数据模板</m-button>
      </template>
    </m-search>
    <m-table
      :items="items"
      :headers="headers"
      :loading="loading"
      :total="total"
      :page-size="pageInfo.size"
      :page-current="pageInfo.current"
      :row-class-name="rowClassName"
      @page-change="onPageChange"
      @expand-change="onExpandChange"
    >
      <template #expand="{ row }">
        <el-form label-position="left" inline class="demo-table-expand">
          <m-card shadow="nerve">
            <el-timeline>
              <el-timeline-item
                :hide-timestamp="true">
                <el-row>
                  <el-col :span="4">月份</el-col>
                  <el-col :span="4">绩效薪资</el-col>
                  <el-col :span="4">数据来源</el-col>
                  <el-col :span="4">写入时间</el-col>
                  <el-col :span="4">操作</el-col>
                </el-row>
              </el-timeline-item>
              <el-timeline-item
                v-for="(list, index) in row.childrenList"
                :key="index"
                :hide-timestamp="true">
                <el-row>
                  <el-col class="col" :span="4">{{ list.month }}</el-col>
                  <el-col class="col" :span="4">{{ list.performanceSalary || '暂无' }}</el-col>
                  <el-col class="col" :span="4">{{ list.dataType === 1 ? '手工录入' : '系统数据'}}</el-col>
                  <el-col class="col" :span="4">{{ list.createDate }}</el-col>
                  <el-col class="col" :span="4">
                    <m-button v-if="checked"  type="text" size="small" icon="el-icon-check" disabled>已使用当前版本</m-button>
                    <m-button
                      v-else
                      type="primary"
                      size="small"
                      @click="onConfirm(list)"
                    >确认使用该版本</m-button>
                  </el-col>
                </el-row>
              </el-timeline-item>
            </el-timeline>
          </m-card>
        </el-form>
      </template>
    </m-table>
  </div>
</template>

<script>
import {
  getComparisonPage,
  uploadComparisonTemplate,
  downloadComparisonTemplate,
  getComparisonByEmployee,
  getComparisonConfirm,
  confirmComparisonVersion
} from '@/api/salary'
import { dateFormat } from '@/utils/date'
import { downloadFile } from '@/utils'
export default {
  name: 'salary-employee-comparison',
  data () {
    return {
      expandRow: [],
      importLoading: false,
      downloadLoading: false,
      submitLoading: false,
      searchItems: [
        {
          label: '月份',
          prop: 'month',
          type: 'datePicker',
          option: {
            editable: false,
            clearable: false,
            placeholder: '请选择月份',
            type: 'month',
            valueFormat: 'yyyy-MM',
            format: 'yyyy 年 MM 月'
          }
        },
        { label: '部门', prop: 'organizationName', type: 'input', option: { placeholder: '请输入部门' } },
        { label: '姓名', prop: 'employeeName', type: 'input', option: { placeholder: '请输入姓名' } }
      ],
      searchValues: {
        month: dateFormat('YYYY-mm', new Date()),
        organizationName: null,
        employeeName: null
      },
      headers: [
        { type: 'expand', prop: 'expand' },
        { label: '机构', prop: 'organizationName' },
        { label: '姓名', prop: 'employeeName' },
        { label: '统一认证号', prop: 'unifiedCertificationNumber' },
        { label: '月份', prop: 'month' }
        // { label: '操作', prop: 'action', align: 'center', width: 100 }
      ],
      items: [
      ],
      loading: false,
      total: 0,
      pageInfo: {
        current: 1,
        size: 10
      },
      checked: false
    }
  },
  methods: {
    async onInit () {
      try {
        const { data } = await getComparisonPage({
          page: this.pageInfo,
          ...this.searchValues
        })
        // 确认是否已经确认方案
        const { data: _data } = await getComparisonConfirm({
          page: {
            size: 10,
            current: 1
          },
          month: this.searchValues.month
        })
        this.checked = _data.records[0]?.version ?? false
        this.items = data.records.map(e => {
          return {
            ...e,
            childrenList: []
          }
        })
        this.total = data.total
      } catch (error) {
        this.$message.error(error)
      }
    },
    rowClassName ({ row, rowIndex }) {
      return this.expandRow.includes(row.unifiedCertificationNumber) ? 'grey' : null
    },
    onSearch () {
      this.pageInfo.current = 1
      this.onInit()
    },
    async onImport (response) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', response.file)
      try {
        await uploadComparisonTemplate(formData)
        this.$message.success('导入成功')
        this.onInit()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.importLoading = false
      }
    },
    async onExport () {
      this.downloadLoading = true
      try {
        const { data, name } = await downloadComparisonTemplate()
        downloadFile(data, name)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.downloadLoading = false
      }
    },
    async onExpandChange (row, expandedRows) {
      this.expandRow = expandedRows.map(e => e.unifiedCertificationNumber)
      if (row.childrenList.length) {
        return
      }
      try {
        const { data } = await getComparisonByEmployee({
          page: {
            size: 999,
            current: 1
          },
          entity: {
            unifiedCertificationNumber: row.unifiedCertificationNumber,
            month: row.month
          }
        })
        row.childrenList = data.records
      } catch (error) {
        this.$message.error(error)
      }
    },
    onConfirm (item) {
      const h = this.$createElement
      this.$confirm(h('div', null, [
        h('p', undefined, '确认后将无法修改，是否确认？'),
        h('p', { style: 'color: #ff5555' }, '注：版本确认之后所有人将同步使用当前选择的版本')
      ]), '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await confirmComparisonVersion({
            employeePerformanceConfirmation: {
              month: item.month,
              version: item.version
            }
          })
          this.$message.success('确认成功')
          this.checked = true
        } catch (error) {
          this.$message.error(error)
        }
      }).catch(_ => {})
    },
    onSubmit () {
      this.submitLoading = true
    },
    onPageChange (page) {
      this.pageInfo.current = page
      this.onInit()
    }
  }
}
</script>

<style lang="scss" scoped>
.col {
  height: 32px;
  line-height: 30px;
}
::v-deep .grey {
  background-color: #f0f0f0;
}
</style>
