<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="投标项目名称" prop="tenderId">
        <el-button type="primary" size="mini" @click="tbOpen = true">选择投标项目</el-button>
        <el-button type="danger" size="mini" @click="form.tenderId = null"
          v-if="form.tenderId != null">删除投标项目</el-button>
        <el-descriptions border v-if="form.tenderId" style="margin-top: 10px;" :column="1">
          <el-descriptions-item label="投标项目名称" label-class-name="my-label" :span="3">
            {{ chooseTender.projectName }}
          </el-descriptions-item>
          <el-descriptions-item label="项目来源" label-class-name="my-label">
            {{ getProjectSource(chooseTender) }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人" label-class-name="my-label">
            {{ chooseTender.aPerson }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话" label-class-name="my-label">
            {{ chooseTender.aPhone }}
          </el-descriptions-item>
        </el-descriptions>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input style="width: 100%;" 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: 90%;">
          <el-option v-for="item in partyAList" :key="item.value" :label="item.partyAName" :value="item.partyAId">
          </el-option>
        </el-select>
        <el-button type="primary" @click="partyAOpen = true" size="mini">选择单位</el-button>
      </el-form-item>
      <el-form-item label="合同编码" prop="contractCode">
        <el-input style="width: 100%;" v-model="form.contractCode" placeholder="请输入合同编码"></el-input>
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input style="width:  100%;" v-model="form.contractNumber" placeholder="请输入合同编号"></el-input>
      </el-form-item>
      <el-form-item label="合同金额" prop="amount">
        <el-input style="width:50%;" 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%;" v-model="form.deposit" placeholder="请输入履约保证金">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="合同文件" prop="contractDocument">
        <FileUpload ref="contractFile" :limit="1" :filePathName="'承接合同/合同文件'" :isModify="true" :isShowTip="false"
          :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getContractPath">
        </FileUpload>
        <div>
          <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.contractDocument}`)">
            {{ getFileName(form.contractDocument) }}
          </el-link>
          <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.contractDocument}`"
            :underline="false" target="_blank">
            <span class="el-icon-download">下载文件</span>
          </el-link>
        </div>
      </el-form-item>
      <el-form-item label="关联项目：" prop="projectIds">
        <el-button type="primary" size="mini" @click="open = true" icon="el-icon-plus">新增关联项目</el-button>
        <el-table v-loading="projectloading" border :data="connectProjectList">
          <el-table-column label="序号" type="index" width="50px"></el-table-column>
          <el-table-column label="项目编号" align="center" prop="projectNumber"></el-table-column>
          <el-table-column label="项目名称" align="center" prop="projectName"></el-table-column>
          <el-table-column label="项目负责人" align="center" prop="projectLeaderUser.nickName"></el-table-column>
          <el-table-column label="承担部门" align="center" prop="undertakingDeptName"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-view" @click="clickProjectFn(scope.row)">查看</el-button>
              <el-button type="text" style="color:#F56C6C;" icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="关联分包合同：">
        <el-button type="primary" size="mini" @click="subOpen = true" icon="el-icon-plus">新增分包合同</el-button>
        <el-table v-loading="subloading" border :data="connectSubContractList">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column label="合同名称" align="center" prop="subContractName" />
          <el-table-column label="承接单位" align="center" prop="partner.partnerName" />
          <el-table-column label="分包合同金额" align="center" prop="subAmount" width="120" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-view" @click="clickSubFn(scope.row)">查看</el-button>
              <el-button type="text" style="color:#F56C6C;" icon="el-icon-delete"
                @click="handleDeleteSub(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 表1：工作量计划-->
      <work-table ref="workTableRef" :contractId="form.contractId" :taskName="'合同拟稿'"></work-table>

      <p class="mb20 mt20"></p>
      <!-- 表2：回款计划 -->
      <payment-table ref="paymentRef" :contractId="form.contractId" :amount="form.amount"
        :taskName="'合同拟稿'"></payment-table>

      <el-form-item label="合同备注" prop="remark">
        <el-input v-model="form.remark" :autosize="{ minRows: 4 }" type="textarea" placeholder="请输入合同备注" />
      </el-form-item>

      <el-divider></el-divider>

      <el-row>
          <el-form-item label="拟稿日期" prop="draftTime">
          <el-date-picker clearable v-model="form.draftTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择拟稿日期">
          </el-date-picker>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="分管审批日期" prop="managerTime">
            <el-date-picker clearable v-model="form.managerTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择分管审批日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分管审核意见" prop="managerComment">
            <el-input type="textarea" v-model="form.managerComment" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="总经理审批日期" prop="gmTime">
            <el-date-picker clearable v-model="form.gmTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择总经理审批日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总经理审批意见" prop="gmComment">
            <el-input type="textarea" v-model="form.gmComment" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="签订日期" prop="signDate">
          <el-date-picker clearable v-model="form.signDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择签订日期">
          </el-date-picker>
        </el-form-item>
      </el-row>
      <el-form-item label="评审方式">
        <el-tag :type="form.commentType == '2' ? 'success' : 'warning'">
          {{ getCommentType(form.commentType) }}</el-tag>
      </el-form-item>
      <el-form-item label="" label-width="0" v-if="form.commentType == '2'">
        <table border="1" style="width:100%;">
          <tr>
            <td style="width: 50px;">序号</td>
            <td>会审部门</td>
            <td>会审人</td>
            <td>会审意见</td>
            <td style="width: 200px;">会审附件</td>
            <td style="width: 100px;">日期</td>
          </tr>
          <tr v-for="(comment, index) in commentList" :key="index">
            <td>
              {{ index + 1 }}
            </td>
            <td>
              {{ getDeptName(comment.deptId) }}
            </td>
            <td>
              {{ getUserName(comment.userId) }}
            </td>
            <td>
              {{ comment.comment }}
            </td>
            <td>
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + comment.document}`)">
                {{ getFileName(comment.document) }}
              </el-link>
            </td>
            <td>
              <el-date-picker v-model="comment.commentTime" type="date" value-format="yyyy-MM-dd" style="width:140px;"
                placeholder="选择日期"></el-date-picker>
            </td>
          </tr>
        </table>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer text-center">
      <el-button type="primary" @click="submitForm">修 改</el-button>
      <el-button @click="$emit('cancel')">取 消</el-button>
    </div>

    <el-dialog title="选择项目" :visible.sync="open" width="60%" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>
    <el-dialog title="选择投标项目" :visible.sync="tbOpen" width="60%" append-to-body>
      <choose-tender @choose="confirmTender"></choose-tender>
    </el-dialog>
    <el-dialog :visible.sync="subOpen" title="选择分包合同" :size="'70%'" append-to-body>
      <choose-subcontract @choose="confirmSubContract"></choose-subcontract>
    </el-dialog>
    <el-drawer :visible.sync="partyAOpen" title="选择甲方单位" :size="'40%'" append-to-body>
      <div class="app-container">
        <choose-party-a @confirm="confirmPartyA"></choose-party-a>
      </div>
    </el-drawer>
    <el-drawer :visible.sync="drawerOpen" title="" :size="'70%'" append-to-body @close="closeDrawerFn">
      <projectInfo :needReturn="false"></projectInfo>
    </el-drawer>
    <el-drawer :visible.sync="subInfoOpen" title="" :size="'55%'" append-to-body>
      <sub-contract :taskForm="taskForm" :taskName="''" :formDisabled="true" :flowDisabled="false"></sub-contract>
    </el-drawer>
  </div>

</template>

<script>
import { listContractWork, addContractWork, delContractWork } from "@/api/oa/contract/contractWork";
import { listContractPayment, addContractPayment, delContractPayment } from "@/api/oa/contract/contractPayment";
import { listContractComment, addContractComment, updateContractComment } from "@/api/oa/contract/contractComment";
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { listSubContract, getSubContract, delSubContract, addSubContract, updateSubContract } from "@/api/oa/contract/subContract";
import { listProjectContract, addProjectContract, delProjectContract } from "@/api/oa/contract/projectContract";
import { listContractSubcontract, delContractSubcontract, addContractSubcontract } from "@/api/oa/contract/contractSubcontract"
import { listProject, getProject } from "@/api/oa/project/project";
import { listPartyA } from "@/api/oa/partyA/partyA";
import chooseProject from "@/views/flowable/form/components/chooseProject.vue";
import chooseTender from "@/views/flowable/form/components/chooseTender.vue";
import ChoosePartyA from '@/views/flowable/form/components/choosePartyA.vue';
import WorkTable from '@/views/flowable/form/business/components/workTable.vue';
import paymentTable from '@/views/flowable/form/business/components/paymentTable.vue';
import projectInfo from '@/views/oa/project/info'
import ChooseSubcontract from '@/views/flowable/form/components/chooseSubcontract.vue';
import SubContract from '@/views/flowable/form/business/subContract.vue';
export default {
  components: { chooseProject, chooseTender, ChoosePartyA, WorkTable, paymentTable, projectInfo, ChooseSubcontract, SubContract },
  props: {
    form: {
      type: Object
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      open: false,
      tbOpen: false,
      partyAOpen: false,
      drawerOpen: false,
      subInfoOpen: false,
      subOpen: false,
      commentList: [],
      workList: [],
      paymentList: [],
      partyAList: [],
      chooseTender: {},
      rules: {
        contractCode: [
          { required: true, message: '请输入合同编码', trigger: 'blur' },
        ],
        amount: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
        ],
      },
      projectloading: false,
      subloading: false,
      connectProjectList: [],
      connectSubContractList: [],
      deleteSubList: [],
      taskForm: {
        formId: ''
      },
    }
  },
  watch: {
    'form.contractId'() {
      this.init();
    }
  },
  created() {
    this.getPartyAList();
    this.init();
  },
  methods: {
    init() {
      const contractId = this.form.contractId;
      this.chooseTender = this.form.tender;
      const tenderId = this.form.tenderId;
      this.connectProjectList = [];
      this.connectSubContractList = [];
      this.deleteSubList = [];
      listContractComment({ pageNum: 1, pageSize: 100, contractId: contractId }).then(res => {
        if (res.rows && res.rows.length != 0) {
          this.commentList = res.rows;
        }
      })
      this.getProjectContractList();
      this.getContractSubcontractList();
    },
    // 获取关联项目
    getProjectContractList() {
      this.projectloading = true;
      const contractId = this.form.contractId;
      listProjectContract({ contractId: contractId }).then(async res => {
        if (res.rows) {
          let list = []
          for (let row of res.rows) {
            let response = await getProject(row.projectId)
            list.push(response.data)
          }
          this.connectProjectList = list;
          this.projectloading = false;
        }
      })
    },
    // 获取关联分包合同
    getContractSubcontractList() {
      this.subloading = true;
      const contractId = this.form.contractId;
      listContractSubcontract({ contractId: contractId }).then(async res => {
        let list = []
        for (let r of res.rows) {
          let obj = await getSubContract(r.subContractId)
          list.push(obj.data)
        }
        this.connectSubContractList = list
        this.subloading = false;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.contractId != null) {
            for (let comment of this.commentList) {
              updateContractComment(comment);
            }
            this.updateContractData();
            this.updateRelatedProject();
            this.$emit('cancel')
          }
        }
      });
    },
    // 查询业主单位列表
    getPartyAList() {
      listPartyA({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partyAList = response.rows;
      })
    },
    getCommentType(row) {
      let name = '';
      if (row == '0') {
        name = '无须评审'
      } else if (row == '1') {
        name = '会议评审'
      } else {
        name = '线上评审'
      }
      return name
    },
    getProjectSource(chooseTender) {
      const TARGET_COMPANY = '中国电建集团成都勘测设计研究院有限公司';
      if (!chooseTender || !chooseTender.partyA || !chooseTender.partyA.partyAName) {
        return '';
      }
      return chooseTender.partyA.partyAName.includes(TARGET_COMPANY) ? '院内' : '院外';
    },
    confirmProject(val) {
      let isSame = this.haveSameIds(val, this.connectProjectList, 'projectId');
      if (isSame) {
        this.$message.error('请勿重复添加已有项目')
        return
      }
      this.open = false
      for (let v of val) {
        this.connectProjectList.push(v)
      }
    },
    haveSameIds(arr1, arr2, key) {
      return arr1.some(obj1 => arr2.some(obj2 => obj1[key] === obj2[key]))
    },
    confirmTender(val) {
      this.tbOpen = false
      this.form.amount = val.quote
      this.form.deposit = val.deposit
      this.form.tenderId = val.tenderId
      this.chooseTender = val
      this.isSelect = true
      this.form.partyAId = val.partyAId
    },
    confirmPartyA(val) {
      this.partyAOpen = false
      if (val && val.length > 1) {
        return this.$message.error('请选择一个甲方单位')
      }
      if (val) {
        this.getPartyAList();
        this.$set(this.form, 'partyAId', val[0].partyAId)
      }
    },
    async confirmSubContract(val) {
      let isSame = this.haveSameIds(val, this.connectSubContractList, 'subContractId');
      if (isSame) {
        this.$message.error('请勿重复添加已有的分包合同')
        return
      }
      this.subOpen = false
      for (let v of val) {
        this.connectSubContractList.push(v)
        await addContractSubcontract({ contractId: this.form.contractId, subContractId: v.subContractId })
      }
      this.getContractSubcontractList()
    },
    getContractPath(val) {
      let arr = val.split('/upload')
      this.form.contractDocument = arr[1]
      if (val == "") {
        this.form.contractDocument = ""
      }
    },
    updateContractData() {
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      updateContract(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        // 删除合同的工作和支付信息，并等待两个操作完成
        Promise.all([
          delContractWork(this.form.contractId),
          delContractPayment(this.form.contractId)
        ]).then(([workRes, paymentRes]) => {
          // 添加工作信息
          const workPromises = this.workList.map(work => {
            work.contractId = this.form.contractId;
            return addContractWork(work);
          });
          // 添加支付信息
          const paymentPromises = this.paymentList.map(payment => {
            payment.contractId = this.form.contractId;
            return addContractPayment(payment);
          });
          // 等待所有添加操作完成
          return Promise.all([...workPromises, ...paymentPromises]);
        }).then(() => {
          // this.$modal.msgSuccess("计划工作量和回款计划添加成功");
        }).catch(error => {
          this.$modal.msgError("操作失败: " + error.message);
        });
      }).catch(error => {
        this.$modal.msgError("合同更新失败: " + error.message);
      });
    },
    async updateRelatedProject() {
      let projectIds = this.connectProjectList.map(item => item.projectId);
      await delProjectContract(this.form.contractId)
      for (let projectId of projectIds) {
        await addProjectContract({ projectId: projectId, contractId: this.form.contractId });
      }
    },
    clickProjectFn(row) {
      this.$router.replace({ query: { ...this.$route.query, projectId: row.projectId } });
      this.drawerOpen = true;
      // 找到当前tab并修改当前tab显示的标题
      let currentView = this.$store.state.tagsView.visitedViews.find(item => item.path === this.$route.path);
      if (currentView != null) {
        currentView.title = row.projectName;
      }
    },
    closeDrawerFn() {
      this.drawerOpen = false;
      // 只需要删除 query 中的 projectId参数，保留其他参数
      const { projectId, ...otherQuery } = this.$route.query;
      this.$router.replace({ 
        path: this.$route.path, 
        query: otherQuery 
      });
      // 找到当前tab并修改当前tab显示的标题为"承接合同"
      let currentView = this.$store.state.tagsView.visitedViews.find(item => item.path === this.$route.path);
      if (currentView != null) {
        currentView.title = '承接合同';
      }
    },
    handleDelete(index, row) {
      this.connectProjectList.splice(index, 1)
    },
    clickSubFn(row) {
      this.taskForm.formId = row.subContractId
      this.subInfoOpen = true
    },
    handleDeleteSub(index, row) {
      delContractSubcontract(row.subContractId)
      this.deleteSubList.push(row)
      this.connectSubContractList.splice(index, 1)
    },
  },
}
</script>

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

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

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

::v-deep .el-descriptions-item__label.is-bordered-label {
  color: #5a5757;
  background: rgba($color: #a9adb3, $alpha: 0.1);
  width: 150px;
  min-width: 150px;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 1px solid #cdd0d3;
}
</style>
