<!--
 * @Author: ysh
 * @Date: 2024-03-18 11:00:04
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-10 17:19:05
-->
<template>
  <div class="project-wrapper">
    <!-- 项目登记 -->
    <h2 style="text-align: center" id="scrollToMe">项目登记</h2>
    <el-form ref="projectAdd" :model="addForm" :rules="rules" label-width="130px" :disabled="disabled">
      <el-form-item label="项目来源：" prop="projectSource">
        <el-radio-group v-model="addForm.projectSource" @change="changeProjectSource">
          <el-radio label="0" border>院内</el-radio>
          <el-radio label="1" border>院外</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目编号：" prop="projectNumber">
        <el-input v-model="addForm.projectNumber"></el-input>
      </el-form-item><el-form-item label="项目名称：" prop="projectName">
        <el-input v-model="addForm.projectName"></el-input>
      </el-form-item>
      <el-form-item label="项目类型：" prop="projectType">
        <!-- <el-input v-model="addForm.projectType"></el-input> -->
        <el-autocomplete clearable style="width: 400px;" v-model="addForm.projectType"
          :fetch-suggestions="querySearchProjectType" placeholder="请输入关键词"></el-autocomplete>
      </el-form-item>
      <el-form-item label="项目级别：" prop="projectLevel">
        <el-radio v-model="addForm.projectLevel" label="0" border>一般项目</el-radio>
        <el-radio v-model="addForm.projectLevel" label="1" border>重大项目</el-radio>
      </el-form-item>
      <el-form-item label="合同编码：">
        <el-input v-model="chooseContractInfo.contractCode">
          <el-button slot="append" @click="openContract = true">选择</el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="合同编号：">
        <el-input v-model="chooseContractInfo.contractNumber" disabled></el-input>
      </el-form-item>
      <el-form-item label="甲方单位" prop="partyAId">
        <el-select v-model="addForm.partyAId" filterable placeholder="请选择" disabled style="width: 100%;">
          <el-option v-for="item in partyAList" :key="item.value" :label="item.partyAName" :value="item.partyAId"
            :disabled="disabled">
          </el-option>
        </el-select>
        <el-button type="primary" @click="partyAOpen = true" size="mini"
          v-if="$route.query.taskName == '项目登记'">选择单位</el-button>
      </el-form-item>
      <el-form-item label="联系人：" prop="contactPerson">
        <el-input v-model="addForm.contactPerson"></el-input>
      </el-form-item>
      <el-form-item label="联系电话：" prop="telephone">
        <el-input v-model="addForm.telephone"></el-input>
      </el-form-item>
      <el-form-item label="任务书上传：" prop="taskDocument">
        <div v-if="addForm.taskDocument" class="upload-list">
          <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + addForm.taskDocument}`)">
            {{ getFileName(addForm.taskDocument) }}
          </el-link>
          <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + addForm.taskDocument}`"
            :underline="false" target="_blank">
            <span class="el-icon-download">下载文件</span>
          </el-link>
        </div>
        <FileUpload v-if="$route.query.taskName == '项目登记'" ref="orz" :limit="1"
          :filePathName="'项目任务书/' + parseTime(new Date(), '{y}-{m}-{d}-{h}-{i}-{s}')"
          :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setProjectDocument">
        </FileUpload>
      </el-form-item>
      <el-form-item label="计划工作量：" prop="taskDocument">
        <plan-workload ref="planworkRef" :projectId="taskForm.formId"></plan-workload>
      </el-form-item>
      <el-form-item label="承担部门：" prop="deptId">
        <el-select v-model="addForm.deptId" multiple clearable style="width:100%" @change="getDeptLeader">
          <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId"
            v-if="item.deptName != '四川中水成勘院测绘工程有限责任公司'">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门负责人：" prop="deptLeader">
        <el-select v-model="addForm.deptLeader" multiple clearable style="width:100%">
          <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 label="资料提交要求：" prop="projectRequest">
        <el-input v-model="addForm.projectRequest" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }"></el-input>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input v-model="addForm.remark" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="6" :xs="24" :offset="12">
          <el-form-item label="项目登记人：" prop="registrantUser">
            <span class="auditor"> {{ addForm.projectRegistrantUser ? addForm.projectRegistrantUser.nickName :
              registrantUser }} </span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="登记日期：" label-width="120px">
            <span> {{ addForm.registerTime ? addForm.registerTime : registerTime }} </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button type="warning" @click="save" :disabled="disabled">保 存</el-button>
      <el-button type="primary" @click="confirmAddForm" :disabled="disabled">提 交</el-button>
    </div>
    <el-dialog title="选择合同" :visible.sync="openContract" width="70%" append-to-body>
      <choose-contract @choose="setContract" @close="openContract = false"></choose-contract>
    </el-dialog>

    <el-dialog title="选择甲方单位" :visible.sync="partyAOpen" width="60%" append-to-body>
      <choose-party-a @confirm="confirmPartyA" :projectSource="addForm.projectSource"></choose-party-a>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { mapGetters } from "vuex";
import { listProject, getProject, addProject, updateProject, delProject, getProjectNmuber, sendMessage, getProjectType } from "@/api/oa/project/project";
import { listDept } from '@/api/system/dept'
import { getUser } from "@/api/system/user";
import { getUsersDeptLeaderByDept } from "@/api/system/post";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { listProjectWork, addProjectWork, delProjectWork } from "@/api/oa/project/projectWork";
import { listProjectContract, addProjectContract } from "@/api/oa/contract/projectContract";
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { listPartyA } from "@/api/oa/partyA/partyA";
import { listContractWork, addContractWork, delContractWork } from "@/api/oa/contract/contractWork";
import chooseContract from '../components/chooseContract.vue';
import ChoosePartyA from '@/views/flowable/form/components/choosePartyA.vue';
import ArrangeProject from './arrangeProject.vue';
import planWorkload from "./planWorkload.vue";
export default {
  components: { chooseContract, ArrangeProject, ChoosePartyA, planWorkload },
  dicts: ['cmc_scale_grade', 'cmc_unit'],
  props: {
    disabled: {
      type: Boolean,
      require: true,
    },
    taskForm: {
      type: Object,
      required: true,
    },
  },
  computed: {
    ...mapGetters(["userId", "name"]),
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      openContract: false,
      registerTime: undefined,
      formTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: "",
        projectLeader: "",
        projectLeaderName: undefined,
        projectName: "",
      },
      projectList: [],
      partyAList: [],
      deptList: [],
      deptLeaderList: [],
      total: 0,
      loading: true,
      modifyOpen: false,
      partyAOpen: false,
      addForm: {
        registerTime: undefined,
        projectRegistrant: "",
        projectLevel: "0",
        taskDocument: '',
        undertakingDept: ''
      },
      chooseContractInfo: {
        contractCode: '',
        contractNumber: ''
      },
      contractCode: "",
      contractNumber: "",
      rules: {
        projectNumber: [
          { required: true, message: "请输入项目编号", trigger: "blur" },
          { pattern: /^[0-9A-Z]+$/, message: '只能输入数字和大写字母', trigger: 'blur' }
        ],
        projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        projectSource: [{ required: true, message: "请选择项目来源", trigger: "change" }],
        projectType: [{ required: true, message: "请输入项目类型", trigger: "blur" }],
        projectLevel: [{ required: true, message: "请选择项目级别", trigger: "change" }],
        partyAId: [{ required: true, message: "请选择甲方单位", trigger: "change" }],
        contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        telephone: [{ required: true, message: "请输入联系人联系方式", trigger: "blur" }],
        deptId: [
          { required: true, message: "请选择承担部门", trigger: "change" }
        ],
        deptLeader: [
          { required: true, message: "部门负责人不能为空", trigger: "change" }
        ]
        // projectRequest: [{ required: true, message: "请输入资料提交要求", trigger: "blur" }],
        // taskDocument: [{ required: true, message: "请上传任务书", trigger: "blur" }]
      },
      workList: [
        {
          content: "",
          scale: "",
          unit: "",
          workload: "",
          deadline: undefined,
          remark: "",
        },
      ],
      restaurants: [{ value: "中国电建集团成都勘测设计研究院有限公司勘测设计分公司" }],
      registrantUser: '',
      projectTypeList: []
    };
  },
  created() {
    this.registerTime = parseTime(new Date(), '{y}-{m}-{d}')
    this.initProjectForm();
    this.getPartyAList();
    this.getDeptList();
    this.getProjectTypeList();
    this.getContractDataList();
    if (this.$cache.local.get('contractId')) {
      const contractId = this.$cache.local.get('contractId')
      this.afterJumpByContract(contractId)
    }
    // this.getList();
  },
  mounted() {
  },
  methods: {
    // 查询项目列表
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = [];
        for (let p of response.rows) {
          if (p.projectLeader != null) {
            getUser(Number(p.projectLeader)).then(res => {
              p.projectLeaderName = res.data.nickName;
            });
          }
          this.projectList.push(p);
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    getProjectTypeList() {
      getProjectType().then(res => {
        if (res) {
          this.projectTypeList = res.data;
        }
      })
    },
    querySearchProjectType(queryString, cb) {
      let projectTypeList = this.projectTypeList;
      let res1 = queryString ? projectTypeList.filter(this.createFilter(queryString)) : projectTypeList;
      let res2 = res1.map(item => ({ value: item }));
      cb(res2)
    },
    createFilter(queryString) {
      return (projectType) => {
        return (projectType.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    getDeptList() {
      listDept({
        deptName: undefined,
        status: undefined
      }).then(res => {
        this.deptList = res.data
      })
    },
    async initProjectForm() {
      let datas = await listProject({ projectId: this.taskForm.formId });
      if (datas.rows.length > 0) {
        this.formTotal = 1
        this.getProjectInfo(this.taskForm.formId)
        // this.getProjectWorkList();
      }
      else {
        let kcDatas = await listProject({ projectId: this.taskForm.formId, undertakingDept: 113 });
        if (kcDatas.rows.length > 0) {
          this.formTotal = 1
          this.getProjectInfo(this.taskForm.formId)
        } else {
          this.addForm.projectRegistrant = this.userId;
          this.registrantUser = this.name;
        }
      }
    },
    async getDeptLeader(val) {
      this.deptLeaderList = [];
      for (let v of val) {
        let res = await getUsersDeptLeaderByDept({ deptId: Number(v) })
        this.deptLeaderList.push(res.data.userId);
      }
      this.$set(this.addForm, 'deptLeader', this.deptLeaderList);
      this.addForm.undertakingDept = this.addForm.deptId.join(',');
    },
    getProjectInfo() {
      getProject(this.taskForm.formId).then(res => {
        this.addForm = res.data;
        if (this.addForm.undertakingDept != null && this.addForm.undertakingDept != "" && this.addForm.undertakingDept != undefined) {
          this.addForm.deptId = this.addForm.undertakingDeptName.split(',')
        }
        this.$set(this.addForm, 'deptLeader', [])
        if (this.addForm.undertakingDept) {
          let arr = (this.addForm.undertakingDept.split(',')).map(Number)
          this.$set(this.addForm, 'deptId', arr)
          this.getDeptLeader(arr);
        } else {
          this.$set(this.addForm, 'deptId', [])
        }
      })
    },
    getProjectWorkList() {
      listProjectWork({ projectId: this.taskForm.formId }).then(res => {
        this.workList = res.rows;
      })
    },
    getContractDataList() {
      listProjectContract({ projectId: this.taskForm.formId }).then(res => {
        if (res.rows) {
          // 创建一个数组来存储所有的 getContract 请求
          const contractPromises = res.rows.map(row => getContract(row.contractId));
          // 使用 Promise.all 来处理所有的请求
          Promise.all(contractPromises).then(contractResponses => {
            contractResponses.forEach(res => {
              if (res.data) {
                // 合并合同信息
                this.chooseContractInfo.contractCode += this.chooseContractInfo.contractCode ? '、' : '' + res.data.contractCode;
                this.chooseContractInfo.contractNumber += this.chooseContractInfo.contractNumber ? '、' : '' + res.data.contractNumber;
              }
            });
          }).catch(err => {
            console.error('获取合同失败:', err);
            // 可以在这里处理错误，比如设置一个错误状态
          });
        }
      }).catch(err => {
        console.error('获取项目合同失败:', err);
        // 可以在这里处理错误，比如设置一个错误状态
      });
    },
    // 从承接合同跳转过来的
    afterJumpByContract(contractId) {
      getContract(contractId).then(res => {
        if (res.data) {
          this.chooseContractInfo = res.data;
          this.$set(this.addForm, 'partyAId', res.data.partyAId);
          this.$set(this.addForm, 'projectName', res.data.contractName);
          if (res.data.partyA) {
            let partyAName = res.data.partyA.partyAName;
            if (partyAName.indexOf('中国电建集团成都勘测设计研究院') != -1) {
              this.$set(this.addForm, 'projectSource', '0');
              this.changeProjectSource('0');
            } else {
              this.$set(this.addForm, 'projectSource', '1');
              this.changeProjectSource('1');
            }
          }
        }
      })
    },
    setContract(val) {
      this.chooseContractInfo = val;
      if (val.partyAId) {
        this.addForm.partyAId = val.partyAId
      }
      this.openContract = false;
    },
    async updatePlanWorkload() {
      const workList = this.$refs.planworkRef.workList;
      const projectId = this.taskForm.formId
      await delProjectWork(projectId)
      for (let work of workList) {
        work.projectId = projectId;
        await addProjectWork(work);
      }
    },
    // 暂存
    async save() {
      this.updatePlanWorkload();
      // 新增项目数据
      if (this.formTotal == 0) {
        this.addForm.projectId = this.taskForm.formId;
        await addProject(this.addForm)
        this.$modal.msgSuccess("新增项目成功");
        this.getList();
        let contractId = this.chooseContractInfo.contractId ? this.chooseContractInfo.contractId : ''
        let pcobj = { projectId: this.taskForm.formId, contractId }
        if (contractId != '') {
          await addProjectContract(pcobj)
          this.$modal.msgSuccess("合同关联成功");
        }
        this.initProjectForm();
      } else {
        // 修改项目数据
        await updateProject(this.addForm)
        this.$modal.msgSuccess("保存成功")
      }
      if (this.$cache.local.get('contractId')) {
        this.$cache.local.remove('contractId')
      }
    },
    async confirmAddForm() {
      let leaderData = await getUsersDeptLeaderByDept({ deptId: 109 })
      let approvalId;
      if (leaderData.data) {
        approvalId = leaderData.data.userId
      }
      this.$set(this.taskForm.variables, "approval", approvalId);
      this.$set(this.taskForm.variables, "formId", this.taskForm.formId);
      // 获取下一个流程节点
      this.$refs['projectAdd'].validate((vaild) => {
        if (vaild) {
          this.updatePlanWorkload();
          if (this.formTotal == 0) {
            this.addForm.projectId = this.taskForm.formId;
            addProject(this.addForm).then(response => {
              this.$modal.msgSuccess("项目登记成功");
              this.getList();
            });
            let contractId = this.chooseContractInfo.contractId ? this.chooseContractInfo.contractId : ''
            let pcobj = { projectId: this.taskForm.formId, contractId }
            if (contractId != '') {
              addProjectContract(pcobj).then(response => {
                this.$modal.msgSuccess("合同关联成功");
              })
            }
          } else {
            // 修改项目数据
            updateProject(this.addForm).then(
              this.$modal.msgSuccess("保存成功")
            );
          }
          const params = { taskId: this.taskForm.taskId };
          getNextFlowNode(params).then(res => {
            complete(this.taskForm).then(response => {
              this.$modal.msgSuccess(response.msg);
              sendMessage(this.addForm);
              this.$emit('goBack');
            });
          })
        } else {
          let dom = document.getElementById('scrollToMe')
          dom.scrollIntoView({ behavior: 'smooth' });
        }
      })
      if (this.$cache.local.get('contractId')) {
        this.$cache.local.remove('contractId')
      }
    },
    confirmPartyA(val) {
      this.partyAOpen = false
      if (val && val.length > 1) {
        return this.$message.error('请选择一个甲方单位')
      }
      if (val) {
        this.getPartyAList();
        this.$set(this.addForm, 'partyAId', val[0].partyAId)
      }
    },
    // 查询业主单位列表
    getPartyAList() {
      this.loading = true
      let partyAName = ''
      if (this.taskName == '项目登记') {
        partyAName = '中国电建集团成都勘测设计研究院有限公司'
      }
      listPartyA({
        pageNum: 1,
        pageSize: 999999,
        partyAName: partyAName
      }).then(response => {
        this.partyAList = response.rows;
      })
    },
    cancel() {
      this.addForm = {};
    },
    addWorkList() {
      this.workList.push({
        content: "",
        scale: "",
        unit: "",
        workload: "",
        deadline: undefined,
        remark: "",
      });
    },
    deletWorkItem(index) {
      let arr = this.workList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    setProjectDocument(val) {
      let arr = val.split('/upload')
      this.addForm.taskDocument = arr[1]
      if (val == "") {
        this.addForm.taskDocument = ""
      }
    },
    getFileName(name) {
      if (name != null) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
    // 修改项目来源
    changeProjectSource(val) {
      let params = {
        pageNum: 1,
        pageSize: 1000,
      };
      let year = new Date().getFullYear();
      let isCorW = '';
      if (val === '0') {
        params.partyAName = '中国电建集团成都勘测设计研究院有限公司';
        isCorW = 'C'
      } else {
        isCorW = 'W'
      }
      listPartyA(params).then(response => {
        this.partyAList = response.rows;
      })
      getProjectNmuber({ projectNumber: year + isCorW }).then(res => {
        this.$set(this.addForm, 'projectNumber', res.msg)
      })
    }
  },
};
</script>

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

.project-wrapper {
  padding: 25px;
}

.table-header {
  background-color: #f5f5f5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}

table {
  /*居中*/
  margin: 0 auto;
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #686a6e;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner,
.el-radio__input.is-disabled+span.el-radio__label {
  color: #686a6e;
}

::v-deep .el-radio__input.is-disabled+span.el-radio__label {
  color: #686a6e;
}

::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  background-color: var(--current-color);
  width: 6px;
  height: 6px;
}

::v-deep .el-radio__input.is-disabled .el-radio__inner,
.el-radio__input.is-disabled.is-checked .el-radio__inner {
  border-color: var(--current-color);
}
</style>
