<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:52:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-02-17 15:15:23
-->
<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="handleExport"
          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="contactPerson" /> -->
      <!-- <el-table-column label="合同文件" align="center" prop="contractDocument" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + scope.row.contractDocument}`)">
            {{ getFileName(scope.row.contractDocument) }}
          </el-link>
        </template>
</el-table-column> -->
      <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="120px" sortable>
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="26" :status="formatStatus(scope.row.percentage)"
            :percentage="scope.row.percentage" text-color="#fff"></el-progress>
          <div>
            {{ scope.row.paidAmount }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="签订备注" align="center" prop="signRemark" /> -->
      <!-- <el-table-column label="签订扫描件" align="center" prop="signScan">
        <template slot-scope="scope">
          <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + scope.row.signScan}`)">
            {{ getFileName(scope.row.signScan) }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="评审方式" align="center" prop="commentType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.commentType == '2' ? 'success' : 'warning'">
            {{ setCommentType(scope.row.commentType) }}
          </el-tag>
        </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>
  </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: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询cmc分包合同评审列表 */
    getList() {
      this.loading = true;
      listSubContract(this.queryParams).then(response => {
        this.subContractList = response.rows;
        this.total = response.total;
        for (let subContract of this.subContractList) {
          listContractPaid({ contractId: subContract.subContractId }).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(subContract, 'percentage', Number(percentage.toFixed(2)));
              this.$set(subContract, 'paidAmount', Number(paidAmount.toFixed(2)));
            } else {
              this.$set(subContract, 'percentage', 0)
            }
            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() {
      this.download('oa/subContract/export', {
        ...this.queryParams
      }, `subContract_${new Date().getTime()}.xlsx`)
    },
    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;
  }
}
</style>
