<template>
  <div class="app-container">
    <el-form ref="form" :model="form" style="padding: 20px 100px 0">
      <!-- 选择内业人员 -->
      <el-form-item label="选择内业人员：">
        <span v-if="innerUsers.length != 0">
          <el-tag effect="plain" type="success" v-for="item in innerUsers" style="margin: 5px; font-size: 14px"
            :key="item.userId">
            {{ item.nickName }}
          </el-tag>
        </span>
        <el-button type="success" plain icon="el-icon-plus" @click="openPeople('inner')" size="mini">选择</el-button>
      </el-form-item>

      <!-- <div class="mb20" style="color:#E23D28;font-size:12px;">
        tips:人员成本=(基础工资+岗位工资)/21.75，固定工资中的年功工资暂忽略不计，绩效工资计入直接成本，津贴补贴、五险一金扣除暂未考虑
      </div> -->

      <!-- 内业人员表格 -->
      <el-form-item v-if="innerUsers.length != 0">
        <table border="1">
          <tr>
            <td :colspan="8" class="head">内业人员成本预算</td>
          </tr>
          <tr>
            <td style="width: 50px">序号</td>
            <td style="width: 80px">姓名</td>
            <td style="width: 100px">部门</td>
            <td style="width: 100px">人员成本（天）</td>
            <td style="width: 100px">预算天数</td>
            <td style="width: 100px">预算绩效</td>
            <td style="width: 100px">金额</td>
            <td style="width: 100px">备注</td>
          </tr>
          <tr v-for="user, index in innerUsers" :key="user.userId">
            <td>{{ index + 1 }}</td>
            <td>{{ user.nickName }}</td>
            <td>{{ user.dept ? user.dept.deptName : user.deptName }}</td>
            <td>
              {{ user.dayCost }}
            </td>
            <td>
              <el-input-number :controls="false" v-model="user.days" placeholder="请输入天数"
                @blur="calculateUserTotal(user)"></el-input-number>
            </td>
            <td>
              <el-input-number :controls="false" v-model="user.performance" placeholder="请输入预算绩效"
                @blur="calculateUserTotal(user)"></el-input-number>
              <el-button type="text" @click="openCalculatePerformance(user)">计算绩效</el-button>
            </td>
            <td class="staffCost">{{ user.amount }}</td>
            <td>
              <el-input v-model="user.remark" type="textarea"></el-input>
            </td>
          </tr>
          <tr>
            <td colspan="4">合计</td>
            <td>{{ form.innerDays }}</td>
            <td>{{ form.innerSettle }}</td>
            <td>{{ form.innerStaffCost }}</td>
          </tr>
        </table>
      </el-form-item>


      <!-- 选择外业人员 -->
      <el-form-item label="选择外业人员：">
        <span v-if="outerUsers.length != 0">
          <el-tag effect="plain" type="success" v-for="item in outerUsers" style="margin: 5px; font-size: 14px"
            :key="item.userId">
            {{ item.nickName }}
          </el-tag>
        </span>
        <el-button type="success" plain icon="el-icon-plus" @click="openPeople('outer')" size="mini">选择</el-button>
      </el-form-item>
      <!-- 外业人员表格 -->
      <el-form-item v-if="outerUsers.length != 0">
        <table border="1">
          <tr>
            <td :colspan="9" class="head">外业人员成本预算</td>
          </tr>
          <tr>
            <td style="width: 50px">序号</td>
            <td style="width: 80px">姓名</td>
            <td style="width: 100px">部门</td>
            <td style="width: 100px">人员成本（天）</td>
            <td style="width: 100px">预算天数</td>
            <td style="width: 100px">预算系数</td>
            <td style="width: 100px">预算绩效</td>
            <td style="width: 100px">总额</td>
            <td style="width: 100px">备注</td>
          </tr>
          <tr v-for="user, index in outerUsers" :key="user.userId">
            <td>{{ index + 1 }}</td>
            <td>{{ user.nickName }}</td>
            <td>{{ user.dept ? user.dept.deptName : user.deptName }}</td>
            <td>
              {{ user.dayCost }}
            </td>
            <td>
              <el-input-number :controls="false" v-model="user.days" placeholder="请输入天数"
                @blur="calculateUserTotal(user)"></el-input-number>
            </td>
            <td>
              <el-input-number :controls="false" v-model="user.coefficient" placeholder="请输入系数"
                @blur="calculateUserTotal(user)"></el-input-number>
            </td>
            <td>
              {{ user.performance }}
            </td>
            <td class="staffCost">{{ user.amount }}</td>
            <td>
              <el-input v-model="user.remark" type="textarea"></el-input>
            </td>
          </tr>
          <tr>
            <td colspan="6">合计</td>
            <td>{{ form.outerSettle }}</td>
            <td>{{ form.outerStaffCost }}</td>
          </tr>
        </table>
      </el-form-item>

      <!-- 总成本合计 -->
      <el-form-item v-if="innerUsers.length != 0 || outerUsers.length != 0">
        <table border="1">
          <tr>
            <td colspan="6"><b>人员成本总计</b></td>
            <td><b>{{ form.staffCost }}</b></td>
          </tr>
        </table>
      </el-form-item>
    </el-form>

    <!-- 选择人员对话框 -->
    <el-dialog :title="currentType === 'inner' ? '选择内业人员' : '选择外业人员'" :visible.sync="isOpenPeople" width="700px"
      append-to-body>
      <choosePeople @chooseUser="getChooseUser"></choosePeople>
    </el-dialog>

    <!-- 计算绩效对话框 -->
    <calculate-performance ref="calculatePerformance" @confirm="handlePerformanceConfirm"></calculate-performance>
  </div>
</template>

<script>
import { listBudgetStaff, addBudgetStaff, delBudgetStaff } from "@/api/oa/budget/budgetStaff.js";
import choosePeople from './components/choosePeople.vue';
import calculatePerformance from './components/calculatePerformance.vue';
export default {
  components: {
    choosePeople,
    calculatePerformance
  },
  props: {
    budgetId: {
      type: String,
      default: ''
    },
    innerSettleLimit: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      form: {
        staffCost: 0,
        innerStaffCost: 0,
        outerStaffCost: 0,
        innerDays: 0,
        innerSettle: 0,
        outerDays: 0,
        outerSettle: 0
      },
      innerUsers: [],
      outerUsers: [],
      isOpenPeople: false,
      currentType: '', // 当前选择的类型：inner 或 outer
      currentUser: null, // 当前操作的用户
    }
  },
  watch: {
    'form.staffCost'(newval) {
      if (!isNaN(newval)) {
        this.$emit('staffCost', newval);
      }
    },
    budgetId() {
      this.initForm()
    },
    innerUsers: {
      handler(newVal) {
        this.$emit('chooseUser', [...newVal, ...this.outerUsers])
      },
      immediate: true,
      deep: true
    },
    outerUsers: {
      handler(newVal) {
        this.$emit('chooseUser', [...this.innerUsers, ...newVal])
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.initForm();
  },
  methods: {
    initForm() {
      if (this.budgetId != '') {
        listBudgetStaff({ pageSize: 100, budgetId: this.budgetId }).then((res) => {
          const allUsers = res.rows;
          this.innerUsers = allUsers.filter(user => user.type === '内业');
          this.outerUsers = allUsers.filter(user => user.type === '外业');
          for (let user of [...this.innerUsers, ...this.outerUsers]) {
            user.nickName = this.getUserName(user.userId);
            user.deptName = this.getDeptName(user.user.deptId);
          }
          this.initStaffCost()
        })
      }
    },
    initStaffCost() {
      this.updateStaffCosts();
    },
    updateStaffCosts() {
      let innerStaffCost = 0;
      let outerStaffCost = 0;
      let innerDays = 0;
      let innerSettle = 0;
      let outerDays = 0;
      let outerSettle = 0;

      for (let user of this.innerUsers) {
        if (user.amount) {
          innerStaffCost += Number(user.amount);
        }
        if (user.days) {
          innerDays += Number(user.days);
        }
        if (user.performance) {
          innerSettle += Number(user.performance);
        }
      }

      for (let user of this.outerUsers) {
        if (user.amount) {
          outerStaffCost += Number(user.amount);
        }
        if (user.days) {
          outerDays += Number(user.days);
        }
        if (user.performance) {
          outerSettle += Number(user.performance);
        }
      }

      // 验证内业预算绩效是否超过限制
      if (innerSettle > Number(this.innerSettleLimit)) {
        this.$message.warning(`内业预算绩效总额(${innerSettle.toFixed(2)})不能超过内业预算绩效合计(${this.innerSettleLimit})`);
        // 发出警告事件
        this.$emit('innerSettleExceeded', {
          current: innerSettle,
          limit: this.innerSettleLimit
        });
      }

      this.$set(this.form, 'innerStaffCost', innerStaffCost.toFixed(2));
      this.$set(this.form, 'outerStaffCost', outerStaffCost.toFixed(2));
      this.$set(this.form, 'staffCost', (innerStaffCost + outerStaffCost).toFixed(2));
      this.$set(this.form, 'innerDays', innerDays.toFixed(2));
      this.$set(this.form, 'innerSettle', innerSettle.toFixed(2));
      this.$set(this.form, 'outerDays', outerDays.toFixed(2));
      this.$set(this.form, 'outerSettle', outerSettle.toFixed(2));
    },
    getChooseUser(val) {
      for (let v of val) {
        if (v.deptId === 115) {
          v.salary = { salary: 7898.75 }
        }
        let dayCost = (parseFloat(((v.salary.salary + 1780) * 12) / 365) + v.socialSecurityUnit + v.houseFund).toFixed(2);
        v.type = this.currentType === 'inner' ? '内业' : '外业';
        v.days = 0; // 初始化天数为0
        v.staffCost = 0; // 初始化成本为0
        v.coefficient = 1; // 初始化系数为1
        v.otherCoefficient = 1; // 初始化其他系数为1
        v.dayCost = dayCost;
      }
      if (this.currentType === 'inner') {
        this.innerUsers = val;
      } else {
        this.outerUsers = val;
      }
      this.isOpenPeople = false;
      this.updateStaffCosts();
    },
    openPeople(type) {
      this.currentType = type;
      this.isOpenPeople = true;
    },
    // 计算单个人员的成本
    calculateUserTotal(user) {
      if (!user.days) {
        user.days = 0;
      }
      if (!user.performance) {
        user.performance = 0;
      }
      if (!user.coefficient) {
        user.coefficient = 1; // 默认值改为1
      }
      let total = 0;
      if (user.type === '外业') {
        // 外业人员计算方式
        user.performance = 200 * Number(user.days) * Number(user.coefficient);
      }
      if (!user.dayCost) {
        user.dayCost = (parseFloat(((user.salary.salary + 1780) * 12) / 365) + user.socialSecurityUnit + user.houseFund).toFixed(2);
      }
      let staffCost = Number(user.dayCost) * Number(user.days)
      total = user.dayCost * Number(user.days) + Number(user.performance);

      if (isNaN(total)) {
        total = 0
      }
      this.$set(user, "amount", total.toFixed(2));
      this.$set(user, "staffCost", staffCost.toFixed(2));
      this.updateStaffCosts();
    },
    openCalculatePerformance(user) {
      this.currentUser = user;
      this.$refs.calculatePerformance.open();
    },
    handlePerformanceConfirm(total) {
      if (this.currentUser) {
        this.$set(this.currentUser, 'performance', total);
        this.calculateUserTotal(this.currentUser);
      }
    },
  },
}
</script>

<style lang="scss" scoped>
table {
  width: 100%;
  /*居中*/
  // margin: 0 auto;
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  border: 1px solid #DCDFE6;

  /*设置背景颜色*/
  /* background-color: #bfa; */
  td {
    padding: 1px;
  }

  .head {
    background-color: #e7f6f3;
    font-family: '微软雅黑';
    font-size: 18;
    font-weight: bold;
  }
}
</style>