<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:52:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-24 14:38:46
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="128px">
      <el-form-item label="合同名称" prop="subContractName">
        <el-input v-model="queryParams.subContractName" placeholder="请输入合同名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="承接单位" prop="partnerId">
        <el-select v-model="queryParams.partnerId" clearable filterable remote reserve-keyword placeholder="请输入承接单位"
          :remote-method="remoteMethod" :loading="loading" style="width: 400px;">
          <el-option v-for="partner in partnerList" :key="partner.partnerId" :label="partner.partnerName"
            :value="partner.partnerId">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="拟稿人" prop="drafter">
        <el-select v-model="queryParams.drafter" filterable clearable @change="handleQuery">
          <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
            :value="item.userId">
          </el-option>
        </el-select>
      </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="openExportDialog"
          v-hasPermi="['oa:subContract:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="subContractList" @selection-change="handleSelectionChange">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="合同名称" align="center" prop="subContractName" width="300px" />
      <el-table-column label="分包合同金额" align="center" prop="subAmount" />
      <el-table-column label="承接单位" align="center" prop="partner.partnerName" />
      <el-table-column label="拟稿日期" align="center" prop="draftTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.draftTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="合同备注" align="center" prop="remark" /> -->
      <el-table-column label="签订日期" align="center" prop="signDate">
        <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-document"></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-wallet"></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">
        <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:subContract:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:subContract: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>
      <sub-edit :form="form" @cancel="cancel()"></sub-edit>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openInfo" append-to-body width="60%">
      <sub-contract :taskForm="taskForm" :taskName="''" :flowDisabled="false"></sub-contract>
    </el-dialog>

    <!-- 回款进度 -->
    <el-dialog :title="title" :visible.sync="progressOpen" width="50%" append-to-body>
      <sub-progress :form="progressContract" @cancel="progressOpen = false" @getList="getList"></sub-progress>
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog :title="title" :visible.sync="exportOpen" width="60%" 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 { listSubContract, getSubContract, delSubContract, addSubContract, updateSubContract } from "@/api/oa/contract/subContract";
import { listPartner } from "@/api/oa/partner/partner";
import subContract from '../../flowable/form/business/subContract.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, delContractComment } from "@/api/oa/contract/contractComment";
import SubEdit from './components/subEdit.vue';
import SubProgress from "./components/subProgress.vue";
import { listContractPaid } from "@/api/oa/contract/contractPaid";

export default {
  components: { subContract, SubEdit, SubProgress },
  name: "SubContract",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc分包合同评审表格数据
      subContractList: [],
      partnerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractId: null,
        subContractName: null,
        subAmount: null,
        partnerId: null,
        contactPerson: null,
        drafter: null,
        draftTime: null,
        signDate: null,
        signRemark: null,
        signScan: null,
        commentType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      taskForm: {
        formId: ''
      },
      commentList: [],
      commentOpen: false,
      progressOpen: false,
      progressContract: {},
      exportOpen: false,
      fieldsObj: [
        { label: '分包合同名称', value: 'subContractName' },
        { label: '分包合同金额', value: 'subAmount' },
        { label: '承接单位', value: 'partnerName' },
        { 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;
      listSubContract(this.queryParams).then(response => {
        this.subContractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    remoteMethod(val) {
      listPartner({
        pageNum: 1,
        pageSize: 20,
        partnerName: val
      }).then(res => {
        this.partnerList = res.rows;
      })
    },
    handleView(row) {
      this.openInfo = true;
      this.title = "合同详情";
      this.form = row;
      this.$set(this.taskForm, 'formId', row.subContractId)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        subContractId: null,
        contractId: null,
        subContractName: null,
        subAmount: null,
        partnerId: null,
        contactPerson: 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.subContractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增分包合同评审";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const subContractId = row.subContractId || this.ids
      getSubContract(subContractId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分包合同评审";
        listContractComment({ pageNum: 1, pageSize: 100, contractId: subContractId }).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
                }
              })
            })
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.subContractId != null) {
            for (let comment of this.commentList) {
              updateContractComment(comment);
            }
            updateSubContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    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
    },
    /** 导出按钮操作 */
    handleExport() {
      let selectFields = this.selectedFields.join(',');
      this.download('oa/subContract/exportSelectFields', {
        ...this.queryParams,
        selectFields: selectFields
      }, `subContract_${new Date().getTime()}.xlsx`)
      this.exportOpen = false;
    },
    // 全选处理
    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;
    },
    // 打开导出对话框
    openExportDialog() {
      this.title = "导出分包合同";
      this.exportOpen = true;
    },
    setCommentType(commentType) {
      if (commentType == '2') {
        return '线上评审'
      } else if (commentType == '0') {
        return '无须评审'
      } else {
        return '会议评审'
      }
    },
    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'
      }
    },
  }
};
</script>
<style lang="scss" scoped>
table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;

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

/* 进度显示样式 */
.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>
