<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:52:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-24 14:37:14
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同编码" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="甲方单位" prop="partyAId">
        <el-select v-model="queryParams.partyAId" clearable filterable remote reserve-keyword placeholder="请输入单位名称"
          :remote-method="remoteMethod" :loading="queryLoading" style="width: 400px;" @change="handleQuery()">
          <el-option v-for="partyA in queryPartyAList" :key="partyA.partyAId" :label="partyA.partyAName"
            :value="partyA.partyAId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作内容" prop="queryString">
        <el-input v-model="queryParams.queryString" placeholder="请输入关键字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleRegister"
          v-hasPermi="['oa:contract:add']">登记承接合同</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="exportOpen = true"
          v-hasPermi="['oa:contract:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="contractList" @selection-change="handleSelectionChange">
      <!-- <el-table-column label="合同id" align="center" prop="contractId" /> -->
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="合同名称" align="center" prop="contractName" width="220px" />
      <el-table-column label="合同金额" align="center" prop="amount" />
      <el-table-column label="甲方单位" align="center" prop="partyA.partyAName" width="220px" />
      <el-table-column label="合同编码（公司）" align="center" prop="contractCode" />
      <el-table-column label="合同编号（业主）" align="center" prop="contractNumber" />
      <el-table-column label="拟稿日期" align="center" prop="draftTime" width="110px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.draftTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签订日期" align="center" prop="signDate" width="110px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="percentage" align="center" label="开票/回款进度" width="180px" sortable>
        <template slot-scope="scope">
          <div class="progress-container">
            <div class="progress-item">
              <div class="progress-header">
                <span class="progress-label invoice-label">
                  <i class="el-icon-tickets"></i>开票
                </span>
                <span class="progress-amount" v-show="scope.row.invoiceAmount">
                  {{ scope.row.invoiceAmount }}元
                </span>
              </div>
              <el-progress :text-inside="true" :stroke-width="20"
                :status="formatStatus(Number(scope.row.invoicePercentage))"
                :percentage="Number(scope.row.invoicePercentage)" text-color="#fff" class="custom-progress">
              </el-progress>
            </div>

            <div class="progress-item">
              <div class="progress-header">
                <span class="progress-label payment-label">
                  <i class="el-icon-money"></i>回款
                </span>
                <span class="progress-amount" v-show="scope.row.paidAmount">
                  {{ scope.row.paidAmount }}元
                </span>
              </div>
              <el-progress :text-inside="true" :stroke-width="20"
                :status="formatStatus(Number(scope.row.paidPercentage))" :percentage="Number(scope.row.paidPercentage)"
                text-color="#fff" class="custom-progress">
              </el-progress>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="拟稿人" align="center" prop="drafter" width="110px">
        <template slot-scope="scope">
          {{ getUserName(scope.row.drafter) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['oa:contract:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:contract:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleProgress(scope.row)"
            v-hasPermi="['oa:contract:paid']">开票/回款进度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改cmc合同评审对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <contract-edit :form="form" @cancel="open = false"></contract-edit>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="60%" append-to-body>
      <contract-form :taskForm="taskForm" :taskName="''" :flowDisabled="false"></contract-form>
    </el-dialog>
    <!-- 回款进度 -->
    <el-dialog :title="title" :visible.sync="progressOpen" width="50%" append-to-body>
      <payment-progress :form="progressContract" @cancel="progressOpen = false" @getList="getList"></payment-progress>
    </el-dialog>
    <!-- 导出对话框 -->
    <el-dialog :title="title" :visible.sync="exportOpen" width="50%" append-to-body>
      <el-form>
        <el-form-item label="选择导出字段名" label-width="120px">
          <div class="export-fields-container">
            <div class="field-selection-header">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                class="check-all-btn">
                全选
              </el-checkbox>
            </div>
            <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange"
              class="field-checkbox-group">
              <div class="field-grid">
                <el-checkbox v-for="field in fieldsObj" :key="field.value" :label="field.value"
                  class="field-checkbox-item">
                  <span class="field-label">{{ field.label }}</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport" :disabled="selectedFields.length === 0">导出</el-button>
        <el-button @click="exportOpen = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContract, listContractFuzzy, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { listPartyA } from "@/api/oa/partyA/partyA";
import contractInfo from './contractInfo.vue';
import ContractForm from '../../flowable/form/business/contractForm.vue';
import { listDefinition } from "@/api/flowable/definition";
import { definitionStart, flowXmlAndNode } from "@/api/flowable/definition";
import { todoList, getNextFlowNodeByStart } from "@/api/flowable/todo";
import { Snowflake } from '@/utils/snowFlake.js'
import { listContractComment, addContractComment, updateContractComment } from "@/api/oa/contract/contractComment";
import contractEdit from './components/edit.vue'
import PaymentProgress from './components/paymentProgress.vue';
import { listContractPaid } from "@/api/oa/contract/contractPaid";
export default {
  components: { contractInfo, ContractForm, contractEdit, PaymentProgress },
  name: "Contract",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc合同评审表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractNumber: null,
        amount: null,
        deposit: null,
        contractDocument: null,
        drafter: null,
        draftTime: null,
        signDate: null,
        signRemark: null,
        signScan: null,
        commentType: null,
        queryString: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      project: {},
      taskForm: {},
      commentList: [],
      commentOpen: false,
      queryPartyAList: [],
      queryLoading: true,
      progressContract: {},
      progressOpen: false,
      exportOpen: false,
      fieldsObj: [
        { label: '合同名称', value: 'contractName' },
        { label: '合同金额', value: 'amount' },
        { label: '甲方单位', value: 'partyAName' },
        { label: '合同编码（公司）', value: 'contractCode' },
        { label: '合同编号（业主）', value: 'contractNumber' },
        { label: '拟稿人', value: 'drafter' },
        { label: '拟稿日期', value: 'draftTime' },
        { label: '签订日期', value: 'signDate' },
        { label: '开票金额', value: 'invoiceAmount' },
        { label: '开票进度', value: 'invoicePercentage' },
        { label: '回款金额', value: 'paidAmount' },
        { label: '回款进度', value: 'paidPercentage' },
      ],
      selectedFields: [],
      checkAll: false,
      isIndeterminate: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询cmc合同评审列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.queryString == '' || this.queryParams.queryString == undefined || this.queryParams.queryString == null) {
        listContract(this.queryParams).then(response => {
          this.contractList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
      else {
        listContractFuzzy(this.queryParams).then(response => {
          this.contractList = response.rows;
          this.total = response.total;
          for (let contract of this.contractList) {
            listContractPaid({ contractId: contract.contractId }).then(res => {
              if (res.total > 0) {
                let percentage = res.rows.reduce((sum, item) => sum + Number(item.paidPercentage), 0);
                let paidAmount = res.rows.reduce((sum, item) => sum + Number(item.paidAmount), 0);
                this.$set(contract, 'percentage', Number(percentage.toFixed(2)))
                this.$set(contract, 'paidAmount', Number(paidAmount.toFixed(2)))
              } else {
                this.$set(contract, 'percentage', 0)
              }
              this.loading = false;
            })
          }
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getCommentType(row) {
      let name = '';
      if (row == '0') {
        name = '无须评审'
      } else if (row == '1') {
        name = '会议评审'
      } else {
        name = '线上评审'
      }
      return name
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractNumber: null,
        amount: null,
        deposit: null,
        contractDocument: null,
        drafter: null,
        draftTime: null,
        remark: null,
        signDate: null,
        signRemark: null,
        signScan: null,
        commentType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加cmc合同评审";
    },
    handleView(row) {
      this.openInfo = true;
      this.title = "合同详情";
      this.form = row;
      this.$set(this.taskForm, 'formId', row.contractId)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const contractId = row.contractId || this.ids
      getContract(contractId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改承接合同评审";
        listContractComment({ pageNum: 1, pageSize: 100, contractId: contractId }).then(res => {
          if (res.rows && res.rows.length != 0) {
            this.commentList = res.rows;
          }
        })
      });
    },
    // 回款进度操作
    handleProgress(row) {
      this.progressContract = row;
      this.title = '回款进度';
      this.progressOpen = true;
    },
    // 登记合同
    async handleRegister() {
      let response = await listDefinition({
        pageNum: 1,
        pageSize: 9999,
        name: "承接合同评审",
        category: "business",
      })
      if (response.data.total == 1) {
        let obj = response.data.records[0]
        this.$confirm("是否发起承接合同评审流程？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleStartProcess(obj)
        }).catch(() => { });
      }
    },
    handleStartProcess(row) {
      let formId = new Snowflake(1n, 1n, 0n).nextId().toString();
      getNextFlowNodeByStart({ deploymentId: row.deploymentId, variables: { formId: formId } }).then(res => {
        let data = res.data;
        const variables = {};
        const formData = {};
        formData.disabled = true;
        formData.formBtns = false;
        formData.formId = formId
        if (row.id) {
          variables.variables = formData;
          let routePath = this.getRoutePath(row);
          definitionStart(row.id, JSON.stringify(variables)).then(res => {
            this.$modal.msgSuccess(res.msg);
            let procInstanceId = res.data;
            todoList({
              pageNum: 1,
              pageSize: 99999999, processInsId: procInstanceId
            }).then(toDoRes => {
              let records = toDoRes.data.records;
              if (records.length == 1) {
                records = records[0]
              }
              this.$router.push({
                path: routePath,
                query: {
                  procInsId: records.procInsId,
                  executionId: records.executionId,
                  deployId: records.deployId,
                  taskId: records.taskId,
                  taskName: records.taskName,
                  startUser: records.startUserName + '-' + records.startDeptName,
                  formId: formData.formId,
                  procDefName: records.procDefName
                }
              })
            })
          })
        }
      })
    },
    getRoutePath(row) {
      let path;
      for (let p of this.publicData.pathRoute) {
        if (p.name == row.name) {
          path = p.path
          break
        } else {
          path = '/flowable/task/todo/detail/index'
        }
      }
      return path
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.contractId != null) {
            for (let comment of this.commentList) {
              updateContractComment(comment);
            }
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      let selectFields = this.selectedFields.join(',');
      console.log(selectFields);
      this.download('oa/contract/exportSelectFields', {
        ...this.queryParams,
        selectFields: selectFields
      }, `contract_${new Date().getTime()}.xlsx`)
    },
    remoteMethod(val) {
      listPartyA({
        pageNum: 1,
        pageSize: 30,
        partyAName: val
      }).then(res => {
        this.queryPartyAList = res.rows;
        this.queryLoading = false;
      })
    },
    formatStatus(row) {
      if (!row) {
        row = 0
        return 'exception'
      }
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
    // 全选处理
    handleCheckAllChange(val) {
      this.selectedFields = val ? this.fieldsObj.map(field => field.value) : [];
      this.isIndeterminate = false;
    },
    // 选择字段变化处理
    handleCheckedFieldsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.fieldsObj.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.fieldsObj.length;
    },
  }
};
</script>

<style scoped>
/* 进度显示样式 */
.progress-container {
  padding: 8px 4px;
}

.progress-item {
  margin-bottom: 12px;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  padding: 0 2px;
}

.progress-label {
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.invoice-label {
  color: #409eff;
}

.payment-label {
  color: #67c23a;
}

.progress-label i {
  font-size: 14px;
}

.progress-amount {
  font-size: 11px;
  color: #909399;
  font-weight: 500;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.custom-progress {
  margin: 2px 0;
}

.custom-progress ::v-deep .el-progress-bar__outer {
  border-radius: 10px;
  overflow: hidden;
}

.custom-progress ::v-deep .el-progress-bar__inner {
  border-radius: 10px;
  transition: all 0.3s ease;
}

.custom-progress ::v-deep .el-progress__text {
  font-size: 11px !important;
  font-weight: 600;
}


.export-fields-container {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.field-selection-header {
  padding-bottom: 12px;
  margin-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.check-all-btn {
  font-weight: 600;
  color: #409eff;
}

.field-checkbox-group {
  width: 100%;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px 16px;
  padding: 8px 0;
}

.field-checkbox-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: all 0.3s ease;
  cursor: pointer;
}

.field-checkbox-item:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.field-checkbox-item.is-checked {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.field-label {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 禁用导出按钮时的样式 */
.dialog-footer .el-button:disabled {
  opacity: 0.6;
}

/* 自定义复选框样式 */
.field-checkbox-item ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.field-checkbox-item ::v-deep .el-checkbox__input:hover .el-checkbox__inner {
  border-color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .field-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 8px 12px;
  }

  .field-checkbox-item {
    padding: 6px 10px;
  }
}
</style>
