<!--
 * @Author: ysh
 * @Date: 2024-03-18 11:00:04
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-09 14:41:48
-->
<template>
  <div class="project-wrapper">
    <!-- 项目登记 -->
    <h2 style="text-align: center" id="scrollToMe">项目登记</h2>
    <el-form ref="projectAdd" :model="addForm" :rules="rules" label-width="110px" :disabled="disabled">
      <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-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="项目来源：" 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="合同编码：">
        <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 allow-create v-model="addForm.partyAId" filterable placeholder="请选择" style="width: 100%;" clearable>
          <el-option v-for="item in partyAList" :key="item.value" :label="item.partyAName" :value="item.partyAId">
          </el-option>
        </el-select>
      </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="'项目任务书'"
          :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="setProjectDocument">
        </FileUpload>
      </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>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { mapGetters } from "vuex";
import { listProject, getProject, addProject, updateProject, delProject } from "@/api/oa/project/project";
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 chooseContract from '../components/chooseContract.vue';
import ArrangeProject from './arrangeProject.vue';
export default {
  components: { chooseContract, ArrangeProject },
  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: [],
      total: 0,
      loading: true,
      modifyOpen: false,
      addForm: {
        registerTime: undefined,
        projectRegistrant: "",
        projectLevel: "0"
      },
      chooseContractInfo: {
        contractCode: '',
        contractNumber: ''
      },
      contractCode: "",
      contractNumber: "",
      rules: {
        projectNumber: [{ required: true, message: "请输入项目编号", trigger: "blur" }],
        projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
      },
      workList: [
        {
          content: "",
          scale: "",
          unit: "",
          workload: "",
          deadline: undefined,
          remark: "",
        },
      ],
      restaurants: [{ value: "中国电建集团成都勘测设计研究院有限公司勘测设计分公司" }],
      registrantUser: ''
    };
  },
  created() {
    this.registerTime = parseTime(new Date(), '{y}-{m}-{d}')
    this.initProjectForm();
    this.getPartyAList();
    this.getContractDataList();
    // 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;
      });
    },
    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 {
        this.addForm.projectRegistrant = this.userId;
        this.registrantUser = this.name;
      }
    },
    getProjectInfo() {
      getProject(this.taskForm.formId).then(res => {
        this.addForm = res.data;
      })
    },
    getProjectWorkList() {
      listProjectWork({ projectId: this.taskForm.formId }).then(res => {
        this.workList = res.rows;
      })
    },
    getContractDataList() {
      listProjectContract({ projectId: this.taskForm.formId }).then(res => {
        if (res.rows) {
          for (let row of res.rows) {
            getContract(row.contractId).then(res => {
              if (res.data) {
                if (this.chooseContractInfo.contractCode != '') {
                  this.chooseContractInfo.contractCode = this.chooseContractInfo.contractCode + '、' + res.data.contractCode;
                } else {
                  this.chooseContractInfo.contractCode = res.data.contractCode;
                }
                if (this.chooseContractInfo.contractNumber != '') {
                  this.chooseContractInfo.contractNumber = this.chooseContractInfo.contractNumber + '、' + res.data.contractNumber;
                } else {
                  this.chooseContractInfo.contractNumber = res.data.contractNumber;
                }
              }
            })
          }
        }
      })
    },
    setContract(val) {
      this.chooseContractInfo = val;
      this.openContract = false;
    },
    // 暂存
    async save() {
      // 新增项目数据
      if (this.formTotal == 0) {
        this.$refs['projectAdd'].validate((vaild) => {
          if (vaild) {
            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 {
            let dom = document.getElementById('scrollToMe')
            dom.scrollIntoView({ behavior: 'smooth' });
          }
        })
      } else {
        // 修改项目数据
        updateProject(this.addForm).then(
          this.$modal.msgSuccess("保存成功")
        );
      }
    },
    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.save()
      const params = { taskId: this.taskForm.taskId };
      // 获取下一个流程节点
      getNextFlowNode(params).then(res => {
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack');
        });
      })
    },
    // 查询业主单位列表
    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);
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    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, // 假设这是一个合理的值  
      };
      if (val === '0') {
        params.partyAName = '中国电建集团成都勘测设计研究院有限公司';
      }
      listPartyA(params).then(response => {
        this.partyAList = response.rows;
      })
    }
  },
};
</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>
