<template>
  <div class="white pa-3">
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="onSearch"></m-search>
    <BonusTable ref="bonusTableRefs" :filter-header="auditStatus !== 0 && auditStatus !== 1 ? [] : ['actions']">
      <template #card-tools="{ items }">
        <div class="content">
          <div>
            <template v-if="auditStatusList[auditStatus]">
              审批状态：
              <el-tag :type="auditStatusList[auditStatus]?.type ?? 'info'" class="mr-3">
                {{ auditStatusList[auditStatus]?.label ?? '未知状态' }}
              </el-tag>
            </template>
            可发放绩效：<el-tag>{{ totalAllocationPerformanceSalary }}</el-tag>
            总绩效： <el-tag>{{ totalGrantPerformanceSalary }}</el-tag>
            <m-button
              class="ml-3"
              type="orange"
              :loading="auditStatusLoading"
              v-show="auditStatus !== 0 && auditStatus !== 1 && items.length"
              @click="onSave">
              确认分配
            </m-button>
          </div>
        </div>
      </template>
      <template #actions="{ row, items }">
        <el-input v-show="auditStatus !== 0 && auditStatus !== 1 && items.length" v-model="values[row.employeePerformanceId]" placeholder="请输入绩效" size="small"></el-input>
      </template>
    </BonusTable>
  </div>
</template>

<script>
import BonusTable from '../components/bonusTable.vue'
import { dateFormat } from '@/utils/date'
import Decimal from 'decimal.js'
import {
  // getAllocationPage,
  saveAllocationGrant,
  getAllocationEmployeeCategory,
  checkAllocationSubmitStatus,
  getAllocationStatistics,
  saveAllocation
} from '@/api/bonus'
import { STATUS_LIST } from '../utils'
import { mapGetters } from 'vuex'
export default {
  name: 'bonusAllocation',
  components: {
    BonusTable
  },
  data () {
    return {
      auditStatusList: STATUS_LIST,
      auditStatus: null,
      auditStatusLoading: true,
      values: {},
      searchValues: {
        month: dateFormat('YYYY-mm', new Date()),
        organizationNo: null,
        employeeCategory: null
      },
      query: {},
      employeeCategoryItems: [],
      totalGrantPerformanceSalary: 0,
      loading: false
    }
  },
  computed: {
    ...mapGetters(['employeeInfo', 'organizationTree']),
    totalAllocationPerformanceSalary () {
      return Object.values(this.values).reduce((r, v) => {
        return new Decimal(r).plus(v || 0)
      }, 0).toFixed(2)
    },
    searchItems () {
      return [
        {
          label: '月份',
          prop: 'month',
          type: 'datePicker',
          options: {
            placeholder: '请选择月份',
            clearable: false,
            type: 'month',
            valueFormat: 'yyyy-MM',
            format: 'yyyy 年 MM 月'
          },
          handles: {
            change: this.getEmployeeCategoryItems
          }
        },
        {
          label: '部门',
          prop: 'organizationNo',
          type: 'cascader',
          options: {
            clearable: true,
            placeholder: '请选择部门',
            options: this.organizationTree,
            showAllLevels: false,
            props: {
              emitPath: false,
              value: 'organizationNo',
              label: 'organizationName',
              children: 'child'
            }
          }
        },
        {
          label: '员工类型',
          prop: 'employeeCategory',
          type: 'select',
          options: {
            clearable: false,
            placeholder: '请选择员工类型',
            items: this.employeeCategoryItems
          }
        }
      ]
    }
  },
  async mounted () {
    this.loading = true
    await this.getEmployeeCategoryItems()
    this.searchValues.organizationNo = this.employeeInfo.organizationNo
    this.query = { ...this.searchValues }
    this.$nextTick(() => {
      this.$refs.bonusTableRefs && this.onInit()
    })
  },
  methods: {
    async onInit (pageInfo) {
      this.loading = true
      await this.onCheckStatus()
      await this.onStatistics()
      if (!this.$refs.bonusTableRefs) {
        return
      }
      const data = await this.$refs.bonusTableRefs.onInit(this.query, pageInfo)
      this.loading = false
      if (!data) {
        return
      }
      this.values = data.records.reduce((res, item) => {
        res[item.employeePerformanceId] = item.allocationPerformanceSalary || null
        return res
      }, {})
    },
    async getEmployeeCategoryItems () {
      try {
        const { data } = await getAllocationEmployeeCategory({
          month: this.searchValues.month
        })
        this.employeeCategoryItems = data.map(e => {
          return {
            label: e,
            value: e
          }
        })
        if (!data.length) {
          this.searchValues.employeeCategory = null
          return
        }
        this.searchValues.employeeCategory = this.employeeCategoryItems[0].value
        return data
      } catch (error) {
        this.employeeCategoryItems = []
        this.$message.error(error)
      }
    },
    async onSearch () {
      this.query = { ...this.searchValues }
      this.onInit({ current: 1 })
    },
    // 领导分配绩效薪资
    onSave () {
      const h = this.$createElement
      const _el = [
        h('p', undefined, `提交月份：${this.query.month}`),
        h('p', undefined, `提交员工类型：${this.query.employeeCategory ?? null}`)
      ]
      try {
        if (this.totalGrantPerformanceSalary !== this.totalAllocationPerformanceSalary) {
          const el = h('div', [
            h('p', undefined, '当前非完全配额，是否强制提交？'),
            ..._el
          ])
          this.$confirm(el, '提示').then(() => {
            this.onSaveAll(true)
          }).catch(_ => {})
          return
        }
        const el = h('div', [
          h('p', undefined, '确定提交所有数据？'),
          ..._el
        ])
        this.$confirm(el, '提示').then(() => {
          this.onSaveAll(false)
        }).catch(_ => {})
      } catch (error) {
        this.$message.error(error)
      }
    },
    async onSaveAll (force) {
      const employeePerformanceGrantItems = Object.keys(this.values).reduce((res, key) => {
        res.push({
          employeePerformanceId: key,
          allocationPerformanceSalary: this.values[key]
        })
        return res
      }, [])
      if (!employeePerformanceGrantItems.length) {
        this.$message.error('请先分配金额')
        return
      }
      try {
        await saveAllocationGrant({
          ...this.query,
          employeePerformanceGrantItems
        })
        await saveAllocation({
          ...this.query,
          force: force ? 1 : 0
        })
        this.$message.success('提交成功')
        this.onInit()
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 查询提交状态
    async onCheckStatus () {
      this.auditStatusLoading = true
      try {
        const { data } = await checkAllocationSubmitStatus(this.query)
        this.auditStatus = data?.status ?? null
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.auditStatusLoading = false
      }
    },
    // 统计分配
    async onStatistics () {
      try {
        const { data } = await getAllocationStatistics(this.query)
        const { totalGrantPerformanceSalary } = data
        this.totalGrantPerformanceSalary = totalGrantPerformanceSalary
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  justify-content: flex-end;
}
</style>
