<!--
 * @Author: ysh
 * @Date: 2024-09-24 11:03:09
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-09-30 10:14:34
-->
<template>
  <div style="width:100%">
    <table class="table" border="1" style="width:100%">
      <tr>
        <td colspan="7" class="head">{{ getDeptName(deptId) }}{{ year }}年{{ month }}月预发绩效表</td>
      </tr>
      <tr>
        <td>序号</td>
        <td>部门</td>
        <td>统计月份</td>
        <td>姓名</td>
        <td>预发绩效（元）</td>
        <td>备注</td>
        <td v-if="taskName == '绩效上报'">操作</td>
      </tr>
      <tr v-for="user, index in wagesList" :key="index">
        <td>
          {{ index + 1 }}
        </td>
        <td>
          {{ getDeptName(user.deptId) }}
        </td>
        <td>
          {{ parseTime(payMonth, '{yy}{mm}') }}
        </td>
        <td>
          {{ user.nickName ? user.nickName : getUserName(user.userId) }}
        </td>
        <td>
          <el-input-number :controls="false" v-model="user.performanceSalary" style="width:100%;"
            @blur="getTotal()" :disabled="taskName != '绩效上报'"></el-input-number>
        </td>
        <td>
          <el-input v-model="user.remark" :disabled="taskName != '绩效上报'"></el-input>
        </td>
        <td v-if="taskName == '绩效上报'">
          <el-popover trigger="click" v-model="user.popVisible" title="确认删除" width="200" :close-on-click-modal="false">
            <p>
              <i class="el-icon-question" style="color:rgb(255, 153, 0);"></i>
              您确定要删除{{ user.nickName ? user.nickName : getUserName(user.userId) }}吗？
            </p>
            <div style="text-align: right;">
              <el-button size="mini" @click="cancelDelete(user)">取消</el-button>
              <el-button size="mini" type="primary" @click="confirmDelete(user)">确认</el-button>
            </div>
          </el-popover>
          <div class="delete-btn" @click="user.popVisible = true">
            <i class="el-icon-circle-close"></i>
          </div>
        </td>
      </tr>
      <tr>
        <td colspan="4"><b>合计</b></td>
        <td><b>{{ total }}</b></td>
        <td></td>
      </tr>
    </table>
    <el-button type="primary" size="mini" icon="el-icon-plus" @click="addUser()" v-if="taskName == '绩效上报'">新增人员</el-button>
    <!-- 选择人员对话框 -->
    <el-dialog title="选择人员" :visible.sync="openPeople" width="700px" append-to-body>
      <choosePeople @chooseUser="getChooseUser"></choosePeople>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser } from '@/api/system/user'
import { parseTime } from "@/utils/ruoyi";
import { listWage, getWage, addWage, updateWage, delWage } from "@/api/oa/wage/wage"
import choosePeople from '@/views/flowable/form/budget/components/choosePeople.vue';
export default {
  components: { choosePeople },
  props: {
    deptId: {
      type: Number,
      require: true,
    },
    performanceId: {
      type: String,
    },
    taskName: {
      type: String,
      require:true
    }
  },
  data() {
    return {
      month: new Date().getMonth() + 1,
      year: new Date().getFullYear(),
      payMonth: '',
      formTotal: 0,
      wagesList: [],
      total: 0,
      openPeople: false,
      generate: false,
    }
  },
  created() {
    this.payMonth = this.getLastMonthYearFormatted();
    this.initWages();
  },
  methods: {
    async initWages() {
      const params = { pageSize: 999, performanceId: this.performanceId, payMonth: this.payMonth }
      let res = await listWage(params)
      if (res.total > 0) {
        this.formTotal = 1;
        for (let w of res.rows) {
          let userData = await getUser(w.userId);
          w.deptId = userData.data.deptId;
        }
        this.wagesList = res.rows;
        this.initWagesPopver(this.wagesList)
      } else {
        let userRes = await listUser({ pageSize: 100, deptId: this.deptId });
        if (userRes.total > 0) {
          let list = userRes.rows;
          let uList = []
          for (let l of list) {
            let obj = {};
            obj.userId = l.userId;
            obj.deptId = this.deptId;
            obj.nickName = l.nickName;
            obj.payMonth = this.payMonth;
            obj.performanceSalary = 0;
            obj.performanceId = this.performanceId;
            uList.push(obj);
          }
          this.wagesList = uList;
          this.addWageList(uList);
          this.initWagesPopver(this.wagesList)
        }
      }
      this.getTotal()
    },
    initWagesPopver(list) {
      list.forEach(item => {
        this.$set(item, 'popVisible', false);
      });
    },
    async addWageList(list) {
      for (let i of list) {
        await addWage(i)
      }
      this.initWages();
    },
    getTotal() {
      this.total = this.wagesList.reduce((accumulator, currentValue) => {
        return accumulator + currentValue.performanceSalary;
      }, 0);
      let num = this.wagesList.length
      this.$emit('getTotal', [this.total, num])
    },
    async addUser() {
      for (let wages of this.wagesList) {
        await updateWage(wages)
      }
      this.openPeople = true;
    },
    getChooseUser(val) {
      if (val.length == 0) return
      let addList = []
      val.forEach((v) => {
        v.performanceSalary = 0
        v.performanceId = this.performanceId
        v.payMonth = this.payMonth;
        addList.push(v)
      })
      this.addWageList(addList);
      this.initWages();
      this.openPeople = false;
    },
    getLastMonthYearFormatted() {
      // 获取当前日期  
      const now = new Date();
      // 设置月份为上个月，注意月份是从0开始的，所以要减1  
      // 同时，如果现在是1月，减1会变为-1，所以使用上个月份的逻辑  
      let lastMonth = now.getMonth() - 1;
      if (lastMonth < 0) {
        lastMonth = 11; // 变为去年的12月  
        now.setFullYear(now.getFullYear() - 1); // 并将年份也减1  
      }
      // 设置日期为上个月的第一天（为了不影响月份）  
      now.setDate(1);
      now.setMonth(lastMonth);
      return now
    },
    deleItem(user) {
      delWage(user.wageId).then(() => {
        this.initWages()
      })
    },
    confirmDelete(user) {
      this.deleItem(user)
      user.popVisible = false; // 关闭气泡
    },
    cancelDelete(user) {
      user.popVisible = false; // 关闭气泡
    },
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  border: 1px solid #a5abb0;

  /*设置背景颜色*/
  /* background-color: #bfa; */
  td {
    // padding: 2px;
    padding: 0;
    font-size: 14px;
  }

  tr:hover {
    background-color: #eaf2f8;
    cursor: pointer;
  }
}

.delete-btn {
  color: #F56C6C;
  cursor: pointer;

  i {
    font-size: 25px;
  }
}

.head {
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 3px;
  font-family: '微软雅黑';
}
</style>