<template>
  <m-dialog title="分润认领" ref="dialog" append-to-body @sure="onSure">

    <m-form :items="formItems" v-model="formValues" v-loading="loading" label-width="140px">
      <template #msg>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户编号">{{ formValues.customerId }}</el-descriptions-item>
          <el-descriptions-item label="机构名称">{{ formValues.organizationName }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ formValues.residualAmount }}</el-descriptions-item>
          <el-descriptions-item label="当前已分配">{{ count }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template #sharing>
        <el-form ref="form" :model="formQuery">
          <m-table
            clearHeader
            shadow="never"
            :headers="headers"
            :items="formQuery.items"
          >
            <template #unifiedCertificationNumber="scope">
              <el-form-item
                :prop="`items.${scope.$index}.unifiedCertificationNumber`"
                :rules="{ required: true, message: '请选择员工', trigger: 'change' }"
              >
                <el-cascader
                  v-model="scope.row.unifiedCertificationNumber"
                  placeholder="请选择员工"
                  filterable
                  :options="employeeItems"
                  :props="{
                    emitPath: false,
                    value: 'id',
                    label: 'title',
                    children: 'child'
                  }"
                ></el-cascader>
                <!-- <el-select v-model="scope.row.unifiedCertificationNumber" filterable placeholder="请选择员工">
                  <el-option
                    v-for="item in employeeItems"
                    :key="item.personnelCode"
                    :label="item.employeeName"
                    :value="item.personnelCode">
                  </el-option>
                </el-select> -->
              </el-form-item>
            </template>
            <template #amount="scope">
              <el-form-item
                :prop="`items.${scope.$index}.amount`"
                :rules="employeeProfitSharingRatioRules"
              >
                <el-input v-model="scope.row.amount" placeholder="请输入分配金额">
                  <!-- <template #append>
                    %
                  </template> -->
                </el-input>
              </el-form-item>
            </template>
            <template #actions="{ $index }">
              <m-button v-if="formQuery.items.length > 1" type="danger" text size="small" @click="removeItem($index)">移除</m-button>
            </template>
            <!-- <template #employeeProfitSharingRatio="{ row }">
              <el-tag>{{ row.employeeProfitSharingRatio }} %</el-tag>
            </template> -->
            <div class="d-flex justify-center pa-3">
              <m-button size="small" type="orange" icon="el-icon-plus" @click="addItem">新增一个分润</m-button>
            </div>
          </m-table>
        </el-form>
      </template>
    </m-form>
  </m-dialog>
</template>

<script>
import { getOrganizationAtlasAll } from '@/api/system'
import {
  claimPerformanceMore
} from '@/api/salary'
const defaultItem = {
  unifiedCertificationNumber: null
  // employeeProfitSharingRatio: null
}
export default {
  name: 'sharingClaimDetailsClaim',
  data () {
    return {
      formValues: {},
      loading: false,
      employeeItems: [],
      formQuery: {
        items: []
      },
      headers: [
        { label: '员工姓名', prop: 'unifiedCertificationNumber' },
        { label: '分润金额', prop: 'amount' },
        { label: '操作', prop: 'actions' }
        // { label: '分润占比', prop: 'employeeProfitSharingRatio' }
      ],
      formItems: [
        {
          label: '分润信息',
          prop: 'msg'
        },
        {
          label: '分润',
          prop: 'sharing'
        }
      ],
      employeeProfitSharingRatioRules: [
        {
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('请输入分润金额'))
            }
            if (isNaN(value) || isNaN(parseFloat(value))) {
              callback(new Error('请输入数字值'))
            } else {
              callback()
            }
          },
          trigger: ['blur', 'change']
        }
      ]
    }
  },
  computed: {
    count () {
      return this.formQuery.items.reduce((sum, e) => {
        return sum + +(e.amount || 0)
      }, 0)
    }
  },
  methods: {
    open (item) {
      this.formValues = {
        organizationName: item.organizationName,
        customerId: item.customerId,
        serialNumber: item.serialNumber,
        residualAmount: item.residualAmount
      }
      this.formQuery.items = [{ ...defaultItem }]
      this.$refs.dialog.open()
      this.getEmployeeItems()
      // this.getEmployeeItems(item.organizationNo)
    },
    async getEmployeeItems () {
      this.loading = true
      try {
        const { data } = await getOrganizationAtlasAll({ type: 0 })
        this.employeeItems = [data]
      } catch (error) {
        this.employeeItems = []
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    removeItem (index) {
      this.formQuery.items.splice(index, 1)
    },
    // async getEmployeeItems (organizationNo) {
    //   if (!organizationNo) {
    //     this.employeeItems = []
    //     return
    //   }
    //   this.loading = true
    //   try {
    //     const params = {
    //       organizationNo,
    //       page: { current: 1, size: 9999 }
    //     }
    //     const { data } = await getRosterList(params)
    //     this.employeeItems = data.records
    //   } catch (error) {
    //     this.employeeItems = []
    //     this.$message.error(error)
    //   } finally {
    //     this.loading = false
    //   }
    // },
    addItem () {
      this.formQuery.items.push({ ...defaultItem })
    },
    onSure () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          this.$message.error('请填写完整')
          return
        }
        if (this.count > this.formValues.residualAmount) {
          this.$message.error('分润金额不能超过可分配金额')
          return
        }
        try {
          await claimPerformanceMore({
            serialNumber: this.formValues.serialNumber,
            items: this.formQuery.items.map(e => {
              return {
                serialNumber: this.formValues.serialNumber,
                amount: e.amount,
                unifiedCertificationNumber: e.unifiedCertificationNumber
              }
            })
          })
          this.$message.success('分润成功')
          this.$refs.dialog.close()
          this.$emit('success')
        } catch (error) {
          this.$message.error(error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
