<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" closable @close="removeUser('inner', 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: 160px">备注</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 style="width: 100px" :controls="false" v-model="user.days" placeholder="请输入天数"
                @blur="calculateUserTotal(user)"></el-input-number>
            </td>
            <td>  
              <el-input-number style="width: 100px" :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" closable @close="removeUser('outer', 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="10" 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>
            <td style="width: 160px">备注</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>
              200
            </td>
            <td>
              <el-input-number style="width: 100px" :controls="false" v-model="user.days" placeholder="请输入天数"
                @blur="calculateUserTotal(user)"></el-input-number>
            </td>
            <td>
              <el-input-number style="width: 100px" :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="5">合计</td>
            <td>{{ form.outerDays }}</td>
            <td>——</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"
        :selectedUserIds="currentType === 'inner' ? innerUsers.map(u => u.userId) : outerUsers.map(u => u.userId)"
        :currentType="currentType"
      ></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';
import { getUserDayValue } from "@/api/oa/wage/wage";
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 === '内业').map(user => JSON.parse(JSON.stringify(user)));
          this.outerUsers = allUsers.filter(user => user.type === '外业').map(user => JSON.parse(JSON.stringify(user)));
          let month = this.parseTime(new Date(), '{y}-{m}')
          for (let user of [...this.innerUsers, ...this.outerUsers]) {
            user.nickName = this.getUserName(user.userId);
            user.deptName = this.getDeptName(user.user.deptId);
            getUserDayValue({ userId: user.userId, payMonth: month }).then(res => {
              user.socialSecurityUnit = res.data.socialSecurityUnit;
              user.houseFund = res.data.houseFund;
            })
          }
          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) {
      // 创建深拷贝，确保数据隔离
      const processedUsers = val.map(v => {
        const userCopy = JSON.parse(JSON.stringify(v));
        
        let dayCost;
        if (!userCopy.salary) {
          userCopy.salary = { salary: 0 }
          dayCost = ((1780 * 12) / 365).toFixed(2);
        } else {
          dayCost = (parseFloat(((userCopy.salary.salary + 1780) * 12) / 365) + userCopy.socialSecurityUnit + userCopy.houseFund).toFixed(2);
        }
        userCopy.type = this.currentType === 'inner' ? '内业' : '外业';
        userCopy.days = 0; // 初始化天数为0
        userCopy.staffCost = 0; // 初始化成本为0
        userCopy.coefficient = 1; // 初始化系数为1
        userCopy.otherCoefficient = 1; // 初始化其他系数为1
        userCopy.dayCost = dayCost;
        userCopy.performance = 0; // 初始化绩效为0
        userCopy.amount = 0; // 初始化金额为0
        userCopy.remark = ''; // 初始化备注为空
        
        return userCopy;
      });
      
      if (this.currentType === 'inner') {
        this.innerUsers = this.innerUsers.concat(processedUsers);
      } else {
        this.outerUsers = this.outerUsers.concat(processedUsers);
      }
      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)).toFixed(2);
      }
      if (user.dayCost && user.salary && user.salary.salary != 0) {
        user.dayCost = (parseFloat(((user.salary.salary + 1780) * 12) / 365) + user.socialSecurityUnit + user.houseFund).toFixed(2);
      } else {
        user.dayCost = ((1780 * 12) / 365).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);
      }
    },
    removeUser(type, userId) {
      if (type === 'inner') {
        this.innerUsers = this.innerUsers.filter(user => user.userId !== userId);
      } else if (type === 'outer') {
        this.outerUsers = this.outerUsers.filter(user => user.userId !== userId);
      }
      this.updateStaffCosts();
    },
  },
}
</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>