<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="合同名称" prop="subContractName">
        <el-input style="width: 100%;" v-model="form.subContractName" placeholder="请输入合同名称"></el-input>
      </el-form-item>
      <el-form-item label="承接单位" prop="partnerId">
        <el-select style="width:84%;" v-model="form.partnerId" multiple filterable placeholder="请选择" disabled clearable>
          <el-option v-for="item in partnerList" :key="item.value" :label="item.partnerName" :value="item.partnerId">
          </el-option>
        </el-select>
        <el-button type="primary" @click="partnerOpen = true" size="mini">选择单位</el-button>
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model="form.telephone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="分包合同金额" prop="subAmount">
        <el-input-number :controls="false" v-model="form.subAmount" placeholder="请输入分包合同金额" />(元)
      </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="projectId">
        <el-button type="primary" size="mini" @click="open = true" icon="el-icon-plus">新增关联项目</el-button>
        <el-table :data="connectProjectList" border>
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column label="项目编号" align="center" key="projectNumber" prop="projectNumber" />
          <el-table-column label="项目名称" align="center" key="projectName" prop="projectName" />
          <el-table-column label="项目负责人" align="center" key="projectLeaderName" prop="projectLeaderUser.nickName" />
          <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="contractOpen = true" icon="el-icon-plus">新增关联主合同</el-button>
        <el-table v-loading="contractloading" :data="connectContractList" border>
          <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">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-view" @click="clickContractFn(scope.row)">查看</el-button>
              <el-button type="text" style="color:#F56C6C;" icon="el-icon-delete"
                @click="handleDeleteContract(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 表1：工作量计划-->
      <work-table ref="workTableRef" :contractId="form.subContractId" :taskName="'合同拟稿'"></work-table>

      <p class="mb20 mt20"></p>
      <!-- 表2：回款计划 -->
      <payment-table ref="paymentRef" :contractId="form.subContractId" :amount="form.subAmount"
        :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="partnerOpen" width="70%" append-to-body>
      <choose-partner @confirm="confirmPartners"></choose-partner>
    </el-dialog>
    <el-dialog title="选择承接合同" :visible.sync="contractOpen" width="70%" append-to-body>
      <choose-contract @choose="confirmContract"></choose-contract>
    </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="formOpen" title="" :size="'60%'" append-to-body>
      <contract-form :taskForm="taskForm" :taskName="''" :formDisabled="true" :flowDisabled="false"></contract-form>
    </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 { listProjectContract, addProjectContract, delProjectContract } from "@/api/oa/contract/projectContract";
import { listSubContract, getSubContract, delSubContract, addSubContract, updateSubContract } from "@/api/oa/contract/subContract";
import { listProjectSubcontract, addProjectSubcontract, delProjectSubcontract } from '@/api/oa/contract/projectSubcontract'
import { listContractSubcontract, delContractSubcontractByContractId, addContractSubcontract } from "@/api/oa/contract/contractSubcontract"
import { listPartner, getPartner } from "@/api/oa/partner/partner";
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 ChoosePartner from '@/views/flowable/form/components/choosePartner.vue';
import ChooseContract from '@/views/flowable/form/components/chooseContract.vue';
import ContractForm from '@/views/flowable/form/business/contractForm.vue';
export default {
  components: {
    chooseProject, chooseTender, ChoosePartyA, WorkTable, paymentTable, projectInfo,
    ChoosePartner,
    ChooseContract,
    ContractForm,
  },
  props: {
    form: {
      type: Object
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      open: false,
      tbOpen: false,
      partyAOpen: false,
      drawerOpen: false,
      partnerOpen: false,
      commentList: [],
      workList: [],
      paymentList: [],
      partyAList: [],
      partnerList: [],
      chooseTender: {},
      rules: {
        subContractName: [
          { required: true, message: '请输入合同名称', trigger: 'blur' },
        ],
        subAmount: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
        ],
      },
      projectloading: false,
      connectProjectList: [],
      projectContractForm: {
        projectIds: [],
      },
      contractOpen: false,
      connectContractList: [],
      contractloading: true,
      formOpen: false,
      taskForm: {
        formId: ''
      }
    }
  },
  watch: {
    'form.contractId'() {
      // this.init();
      this.getContractSubcontractList();
      this.getProjectSubcontractList();
      this.form.partnerId = this.form.partnerId ? this.form.partnerId.split(',') : null;
    }
  },
  created() {
    this.getPartyAList();
    this.init();
  },
  methods: {
    init() {
      this.getPartnerList();
      this.getContractSubcontractList();
      this.form.partnerId = this.form.partnerId ? this.form.partnerId.split(',') : null;
      this.getContractCommentList();
      this.getProjectSubcontractList();
    },
    getContractCommentList() {
      const subContractId = this.form.subContractId;
      listContractComment({ pageNum: 1, pageSize: 100, contractId: subContractId }).then(res => {
        if (res.rows && res.rows.length != 0) {
          this.commentList = res.rows;
        }
      })
    },
    getProjectSubcontractList() {
      const subContractId = this.form.subContractId;
      listProjectSubcontract({ subContractId: subContractId }).then(res => {
        if (res.rows) {
          let list = []
          for (let row of res.rows) {
            getProject(row.projectId).then(response => {
              list.push(response.data)
            })
          }
          this.connectProjectList = list;
        }
      })
    },
    // 获取关联承接合同
    getContractSubcontractList() {
      this.contractloading = true;
      const subContractId = this.form.subContractId;
      if (!subContractId) return
      listContractSubcontract({ subContractId: subContractId }).then(async res => {
        let list = []
        for (let r of res.rows) {
          let obj = await getContract(r.contractId)
          list.push(obj.data)
        }
        this.connectContractList = list
        this.contractloading = false;
      })
    },
    // 查询承接单位列表
    getPartnerList() {
      listPartner({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partnerList = response.rows;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.subContractId != null) {
            for (let comment of this.commentList) {
              updateContractComment(comment);
            }
            if (this.form.partnerId)
              this.form.partnerId = this.form.partnerId.join(',')
            this.updateSubContractFn()
            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.projectContractForm.projectIds.push(v.projectId);
        this.connectProjectList.push(v)
      }
    },
    // 确定合作单位
    confirmPartners(val) {
      this.partnerOpen = false
      if (val) {
        let ids = []
        let contactPerson = []
        let telephone = []
        val.map(item => {
          ids.push(item.partnerId)
          if (item.contactPerson)
            contactPerson.push(item.contactPerson)
          if (item.telephone)
            telephone.push(item.telephone)
        })
        this.$set(this.form, 'contactPerson', contactPerson.join(','));
        this.$set(this.form, 'telephone', telephone.join(','));
        this.form.partnerId = ids
      }
    },
    async confirmContract(val) {
      let isSame = this.haveSameIds([val], this.connectContractList, 'contractId');
      if (isSame) {
        this.$message.error('请勿重复添加已有的合同');
        return
      }
      this.contractOpen = false;
      this.connectContractList.push(val)
      await addContractSubcontract({ contractId: val.contractId, subContractId: this.form.subContractId })

    },
    haveSameIds(arr1, arr2, key) {
      return arr1.some(obj1 => arr2.some(obj2 => obj1[key] === obj2[key]))
    },
    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)
      }
    },
    getContractPath(val) {
      let arr = val.split('/upload')
      this.form.contractDocument = arr[1]
      if (val == "") {
        this.form.contractDocument = ""
      }
    },
    // updateSubContractFn() {
    //   const subContractId = this.form.subContractId
    //   this.workList = this.$refs.workTableRef.workList;
    //   this.paymentList = this.$refs.paymentRef.paymentList;
    //   updateSubContract(this.form).then(() => {
    //     this.$modal.msgSuccess("修改成功");
    //     delProjectSubcontract(subContractId).then(() => {
    //       this.connectProjectList.forEach(item => {
    //         addProjectSubcontract({ subContractId: subContractId, projectId: item.projectId })
    //       })
    //     })
    //     delContractWork(subContractId).then(() => {
    //       for (let work of this.workList) {
    //         work.contractId = subContractId;
    //         addContractWork(work);
    //       }
    //     })
    //     delContractPayment(subContractId).then(() => {
    //       for (let payment of this.paymentList) {
    //         payment.contractId = subContractId;
    //         addContractPayment(payment);
    //       }
    //     })
    //   })

    // },
    async updateSubContractFn() {
      const subContractId = this.form.subContractId;
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      try {
        // 更新子合同
        await updateSubContract(this.form);
        this.$modal.msgSuccess("修改成功");
        // 删除项目分包合同
        await delProjectSubcontract(subContractId);
        // 添加新的项目分包合同
        for (let item of this.connectProjectList) {
          await addProjectSubcontract({ subContractId: subContractId, projectId: item.projectId });
        }
        // 删除合同工作
        await delContractWork(subContractId);
        // 添加新的合同工作
        for (let work of this.workList) {
          work.contractId = subContractId;
          await addContractWork(work);
        }
        // 删除合同付款
        await delContractPayment(subContractId);
        // 添加新的合同付款
        for (let payment of this.paymentList) {
          payment.contractId = subContractId;
          await addContractPayment(payment);
        }
      } catch (error) {
        console.error("更新合同时出错:", error);
        this.$modal.msgError("更新失败");
      }
    },
    updateRelatedProject() {
      delProjectContract(this.form.contractId).then(() => {
        for (let projectId of this.projectContractForm.projectIds) {
          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)
      this.projectContractForm.projectIds.splice(row.contractId)
    },
    clickContractFn(row) {
      this.formOpen = true;
      this.taskForm.formId = row.contractId
    },
    handleDeleteContract(index, row) {
      this.connectContractList.splice(index, 1)
      delContractSubcontractByContractId(row.contractId)
    }
  },
}
</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>
