<!--
 * @Author: ysh
 * @Date: 2025-02-12 13:40:48
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-24 11:03:22
-->
<template>
  <div>
    <el-form ref="form" :model="form" label-width="130px">
      <el-form-item label="合同名称" prop="contractName">
        <el-input style="width: 100%;" disabled v-model="form.contractName" placeholder="请输入合同名称"></el-input>
      </el-form-item>
      <el-form-item label="甲方单位" prop="partyAId">
        <el-select v-model="form.partyAId" filterable placeholder="请选择" disabled style="width: 100%;">
          <el-option v-for="item in partyAList" :key="item.value" :label="item.partyAName" :value="item.partyAId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同编码" prop="contractCode">
        <el-input style="width: 100%;" disabled v-model="form.contractCode" placeholder="请输入合同编码"></el-input>
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input style="width:  100%;" disabled v-model="form.contractNumber" placeholder="请输入合同编号"></el-input>
      </el-form-item>
      <el-form-item label="合同金额" prop="amount">
        <el-input style="width:50%;" disabled v-model="form.amount" placeholder="请输入合同金额">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item style="text-align: left;" label="履约保证金" prop="deposit">
        <el-input style="width:50%;" disabled v-model="form.deposit" placeholder="请输入履约保证金">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="合同备注" prop="remark">
        <el-input type="textarea" disabled v-model="form.remark" :autosize="{ minRows: 4 }" />
      </el-form-item>
      <el-form-item style="text-align: left;" label="开票进度">
        <table border="1" style="width:100%" v-loading="loading">
          <tr>
            <td style="width: 50px;">序号</td>
            <td>开票金额</td>
            <td>开票比例（%）</td>
            <td>开票时间</td>
            <td style="width: 150px;">备注</td>
          </tr>
          <tr v-for="(invoice, index) in invoiceList" :key="index">
            <td>
              {{ index + 1 }}
            </td>
            <td>
              <el-input-number style="width:100%" :controls="false" v-model="invoice.invoiceAmount" clearable
                @blur="changeInvoiceAmount(invoice)"
                :disabled="!$store.getters.roles.includes('business')"></el-input-number>
            </td>
            <td>
              {{ invoice.invoicePercentage }}
            </td>
            <td>
              <el-date-picker style="width:100%" v-model="invoice.invoiceTime" value-format="yyyy-MM-dd" type="date"
                placeholder="选择日期" :disabled="!$store.getters.roles.includes('business')">
              </el-date-picker>
            </td>
            <td>
              <el-input v-model="invoice.remark" type="textarea" clearable :autosize="{ minRows: 2 }"
                :disabled="!$store.getters.roles.includes('business')"></el-input>
            </td>
            <td v-show="$store.getters.roles.includes('business')">
              <div class="delete-btn" @click="deletInvoiceItem(index)">
                <i class="el-icon-circle-close"></i>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              合计
            </td>
            <td>
              {{ invoiceSumAmount.toFixed(2) }}
            </td>
            <td>
              {{ invoiceSumPercent.toFixed(2) }}
            </td>
          </tr>
        </table>
        <el-button icon="el-icon-plus" size="mini" @click="addInvoiceList()" type="primary" plain></el-button>
      </el-form-item>
      <el-form-item style="text-align: left;" label="回款进度">
        <table border="1" style="width:100%" v-loading="loading">
          <tr>
            <td style="width: 50px;">序号</td>
            <td>回款金额</td>
            <td>回款比例（%）</td>
            <td>回款时间</td>
            <td style="width: 150px;">备注</td>
          </tr>
          <tr v-for="(paid, index) in paidList" :key="index">
            <td>
              {{ index + 1 }}
            </td>
            <td>
              <el-input-number style="width:100%" :controls="false" v-model="paid.paidAmount" clearable
                @blur="changePercentage(paid)"
                :disabled="!($store.getters.roles.includes('finance') || $store.getters.roles.includes('nfinance'))"></el-input-number>
            </td>
            <td>
              {{ paid.paidPercentage }}
            </td>
            <td>
              <el-date-picker style="width:100%" v-model="paid.paidTime" value-format="yyyy-MM-dd" type="date"
                placeholder="选择日期" :disabled="!($store.getters.roles.includes('finance') || $store.getters.roles.includes('nfinance'))">
              </el-date-picker>
            </td>
            <td>
              <el-input v-model="paid.remark" type="textarea" clearable :autosize="{ minRows: 2 }"
                :disabled="!($store.getters.roles.includes('finance') || $store.getters.roles.includes('nfinance'))"></el-input>
            </td>
            <td v-show="$store.getters.roles.includes('finance', 'nfinance')">
              <div class="delete-btn" @click="deletPaiItem(index)">
                <i class="el-icon-circle-close"></i>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              合计
            </td>
            <td>
              {{ sumAmount.toFixed(2) }}
            </td>
            <td>
              {{ sumPercent.toFixed(2) }}
            </td>
          </tr>
        </table>
        <el-button icon="el-icon-plus" size="mini" @click="addPaiList()" type="primary" plain></el-button>
      </el-form-item>
    </el-form>
    <el-row class="text-center">
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-row>
  </div>
</template>

<script>
import { listPartyA } from "@/api/oa/partyA/partyA";
import { listContractPaid, getContractPaid, addContractPaid, updateContractPaid, delContractPaid } from "@/api/oa/contract/contractPaid";
import { listContractInvoice, addContractInvoice, delContractInvoice } from "@/api/oa/contract/contractInvoice";
export default {
  props: {
    form: {
      type: Object
    }
  },
  data() {
    return {
      partyAList: [],
      paidList: [{
        paidPercentage: 0,
        paidAmount: 0,
        paidTime: '',
        remark: ''
      }],
      sumAmount: 0,
      sumPercent: 0,
      loading: true,
      isDisabled: true,
      invoiceList: [{
        invoiceAmount: 0,
        invoicePercentage: 0,
        invoiceTime: '',
        remark: ''
      }],
      invoiceSumAmount: 0,
      invoiceSumPercent: 0,
    }
  },
  watch: {
    'form.contractId'(newVal) {
      this.getPaidList();
      this.getInvoiceList();
    }
  },
  created() {
    this.getPartyAList();
    this.getPaidList();
    this.getInvoiceList();
  },
  methods: {
    // 查询业主单位列表
    getPartyAList() {
      listPartyA({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partyAList = response.rows;
      })
    },
    getPaidList() {
      this.loading = true;
      listContractPaid({ contractId: this.form.contractId }).then(res => {
        if (res.total > 0) {
          this.paidList = res.rows;
        } else {
          this.paidList = [{
            paidPercentage: 0,
            paidAmount: 0,
            paidTime: '',
            remark: ''
          }]
        }
        this.getSum();
        this.loading = false;
      })
    },
    getInvoiceList() {
      this.loading = true;
      listContractInvoice({ contractId: this.form.contractId }).then(res => {
        if (res.total > 0) {
          this.invoiceList = res.rows;
        } else {
          this.invoiceList = [{
            invoiceAmount: 0,
            invoicePercentage: 0,
            invoiceTime: '',
            remark: ''
          }]
        }
        this.getInvoiceSum();
        this.loading = false;
      })
    },
    getSum() {
      this.sumAmount = this.paidList.reduce((sum, item) => sum + Number(item.paidAmount), 0);
      this.sumPercent = this.paidList.reduce((sum, item) => sum + Number(item.paidPercentage), 0);
    },
    getInvoiceSum() {
      this.invoiceSumAmount = this.invoiceList.reduce((sum, item) => sum + Number(item.invoiceAmount), 0);
      this.invoiceSumPercent = this.invoiceList.reduce((sum, item) => sum + Number(item.invoicePercentage), 0);
    },
    addInvoiceList() {
      this.invoiceList.push({
        invoiceAmount: 0,
        invoicePercentage: 0,
        invoiceTime: '',
        remark: ''
      });
    },
    addPaiList() {
      this.paidList.push({
        paidPercentage: 0,
        paidAmount: 0,
        paidTime: '',
        remark: ''
      });
    },
    deletPaiItem(index) {
      let arr = this.paidList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
      this.getSum();
    },
    deletInvoiceItem(index) {
      let arr = this.invoiceList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
      this.getInvoiceSum();
    },
    changePercentage(paid) {
      let percent = ((paid.paidAmount / this.form.amount) * 100).toFixed(2);
      paid.paidPercentage = Number(percent);
      this.getSum();
    },
    changeInvoiceAmount(invoice) {
      let percent = ((invoice.invoiceAmount / this.form.amount) * 100).toFixed(2);
      invoice.invoicePercentage = Number(percent);
      this.getInvoiceSum();
    },
    async confirm() {
      const contractId = this.form.contractId
      await delContractPaid(contractId);
      for (let p of this.paidList) {
        p.contractId = contractId
        await addContractPaid(p);
      }
      await delContractInvoice(contractId);
      for (let i of this.invoiceList) {
        i.contractId = contractId
        await addContractInvoice(i);
      }
      this.$message.success('更新成功');
      this.$emit('cancel')
      this.$emit('getList')
    }
  },
}
</script>

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

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

  i {
    font-size: 25px;
  }
}

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

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