<template>
  <div class="consulting-agency-container">
    <el-form :model="comProjectDetailInfo" :rules="rules" :show-message="false" class="basic-engineering-information-inner"
      ref="comProjectDetailForm">
      <!-- 基础信息 -->
      <div class="project-basic-information">
        <div class="info-module-title"><span>基础信息</span></div>
        <table>
          <colgroup>
            <col>
            <col :style="{width : tableKeyWidth}">
            <col>
            <col :style="{width : tableKeyWidth}">
          </colgroup>
          <tr>
            <td class="table-key">咨询机构名称</td>
            <td>
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBody && comProjectDetailInfo.advisoryBody.advisoryBodyName ? comProjectDetailInfo.advisoryBody.advisoryBodyName : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBody.advisoryBodyName">
                <el-input v-model="comProjectDetailInfo.advisoryBody.advisoryBodyName" clearable v-focus placeholder="请输入完整咨询机构名称"
                  @input="searchConsulting"></el-input>
              </el-form-item>
            </td>
            <td class="table-key">法人代表</td>
            <td>
              {{comProjectDetailInfo.corporatePerson ? comProjectDetailInfo.corporatePerson : "-"}}
            </td>
          </tr>
          <tr>
            <!-- <td class="table-key">法人联系电话</td>
            <td>
              {{comProjectDetailInfo.corporatePerson ? comProjectDetailInfo.corporatePerson : "-"}}
            </td> -->
            <td class="table-key">注册地址</td>
            <td colspan="3">
              {{comProjectDetailInfo.regAddress ? comProjectDetailInfo.regAddress : "-"}}
            </td>
          </tr>
        </table>
      </div>
      <!-- 项目联系人 -->
      <div class="project-contact">
        <div class="info-module-title"><span>项目联系人</span></div>
        <table>
          <colgroup>
            <col>
            <col :style="{width : tableKeyWidth}">
            <col>
            <col :style="{width : tableKeyWidth}">
          </colgroup>
          <tr>
            <td class="table-key">项目负责人</td>
            <td>
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && comProjectDetailInfo.advisoryBodyProject.projectLeader ? comProjectDetailInfo.advisoryBodyProject.projectLeader : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.projectLeader">
                <el-input v-model="comProjectDetailInfo.advisoryBodyProject.projectLeader" clearable placeholder="请输入项目负责人"></el-input>
              </el-form-item>
            </td>
            <td class="table-key">项目负责人专业</td>
            <td>
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && comProjectDetailInfo.advisoryBodyProject.projectLeaderMajor ? comProjectDetailInfo.advisoryBodyProject.projectLeaderMajor : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.projectLeaderMajor">
                <el-input v-model="comProjectDetailInfo.advisoryBodyProject.projectLeaderMajor" clearable placeholder="请输入项目负责人专业"></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="table-key">联系电话</td>
            <td colspan="3">
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && comProjectDetailInfo.advisoryBodyProject.projectLeaderPhone ? comProjectDetailInfo.advisoryBodyProject.projectLeaderPhone : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.projectLeaderPhone">
                <el-input v-model="comProjectDetailInfo.advisoryBodyProject.projectLeaderPhone" clearable placeholder="请输入项目负责人联系电话"></el-input>
              </el-form-item>
            </td>
          </tr>
        </table>
      </div>
      <!-- 项目结算信息 -->
      <div class="project-settlement-information">
        <div class="info-module-title"><span>项目结算信息</span></div>
        <table>
          <colgroup>
            <col>
            <col :style="{width : tableKeyWidth}">
            <col>
            <col :style="{width : tableKeyWidth}">
          </colgroup>
          <tr>
            <td class="table-key">结算开始时间</td>
            <td>
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && comProjectDetailInfo.advisoryBodyProject.settleStartTime ? comProjectDetailInfo.advisoryBodyProject.settleStartTime : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.settleStartTime">
                <el-date-picker v-model="comProjectDetailInfo.advisoryBodyProject.settleStartTime" type="datetime" placeholder="选择结算开始时间"
                  :value-format="'yyyy-MM-dd HH:mm:ss'">
                </el-date-picker>
              </el-form-item>
            </td>
            <td class="table-key">结算完成时间</td>
            <td>
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && comProjectDetailInfo.advisoryBodyProject.settleFinishTime ? comProjectDetailInfo.advisoryBodyProject.settleFinishTime : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.settleFinishTime">
                <el-date-picker v-model="comProjectDetailInfo.advisoryBodyProject.settleFinishTime" type="datetime" placeholder="选择结算完成时间"
                  :value-format="'yyyy-MM-dd HH:mm:ss'">
                </el-date-picker>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="table-key">是否为终审单位</td>
            <td colspan="3">
              <div class="normal-value" v-if="!comIsModify">
                {{comProjectDetailInfo.advisoryBodyProject && statusCheck(comProjectDetailInfo.advisoryBodyProject.isFinalJudgeUnit) ? statusCheck(comProjectDetailInfo.advisoryBodyProject.isFinalJudgeUnit) : "-"}}
              </div>
              <el-form-item label="" v-if="comIsModify" prop="advisoryBodyProject.isFinalJudgeUnit">
                <el-radio-group v-model="comProjectDetailInfo.advisoryBodyProject.isFinalJudgeUnit">
                  <el-radio :label="'0'">是</el-radio>
                  <el-radio :label="'1'">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
          </tr>
        </table>
      </div>
    </el-form>
  </div>
</template>
<script>
import { searchConsultingApi } from "@/api/consultingOrgManagement";
import { elementMessageSingleton } from "@/utils";
export default {
  name: "consultingAgency",
  props: {
    projectDetailInfo: Object,
    isModify: {
      type: Boolean,
      default: false
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.querySelector(".el-input__inner").focus();
      }
    }
  },
  watch: {
    projectDetailInfo: {
      handler(newValue, oldValue) {
        this.setInitData(this.comProjectDetailInfo, JSON.parse(JSON.stringify(newValue)), "comProjectDetailInfo");
        this.setInitData(this.oldComProjectDetailInfo, JSON.parse(JSON.stringify(oldValue)), "oldComProjectDetailInfo");
      },
      deep: true
    },
    isModify: {
      handler(newValue) {
        this.comIsModify = newValue;
      }
    }
  },
  data() {
    const phoneValidator = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/;
      // if (!value && !value?.toString()?.trim()) {
      //   return callback(new Error(`请输入项目负责人联系电话`));
      // }
      if (value && !phoneReg.test(value)) {
        return callback(new Error(`请输入正确的联系电话`));
      }
      return callback();
    };
    return {
      comIsModify: this.isModify,
      comProjectDetailInfo: {},
      oldComProjectDetailInfo: {},
      rules: {
        "advisoryBody.advisoryBodyName": [{ required: true, trigger: ["blur", "change"], message: "咨询机构名称不能为空" }],
        "advisoryBodyProject.projectLeaderPhone": [{ required: true, trigger: ["blur", "change"], validator: phoneValidator }],
      },
      tableKeyWidth: 0,
      searchTimer: null,
    };
  },
  //可访问data属性
  created() {
    this.setInitData(this.comProjectDetailInfo, JSON.parse(JSON.stringify(this.projectDetailInfo)), "comProjectDetailInfo");
    this.setInitData(this.oldComProjectDetailInfo, JSON.parse(JSON.stringify(this.projectDetailInfo)), "oldComProjectDetailInfo");
    this.setTableKeyWidth();
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    setInitData(originData, mergeData, mergeKey) {
      if (!mergeData.advisoryBody) mergeData.advisoryBody = {};
      if (!mergeData.advisoryBodyProject) mergeData.advisoryBodyProject = {};
      // 响应更新
      this.$set(this, mergeKey, { ...this[mergeKey], ...mergeData });
    },
    statusCheck(status) {
      if (status == "0") {
        return "是";
      }
      if (status == "1") {
        return "否";
      }
      return "";
    },
    async setTableKeyWidth() {
      try {
        await this.$nextTick();
        /** 
         * @type {HTMLDivElement}
        */
        const inner = this.$el.querySelector(".basic-engineering-information-inner");
        if (inner) {
          const td = parseInt((inner.offsetWidth - 140 * 2) / 2);
          this.tableKeyWidth = `${parseInt(parseFloat(td / inner.offsetWidth) * 100)}%`;
        }
      } catch (error) {

      }
    },
    cancelModify() {
      this.comProjectDetailInfo = JSON.parse(JSON.stringify(this.oldComProjectDetailInfo));
    },
    async searchConsulting(keywords) {
      try {
        if ((keywords || keywords == "0") && keywords?.toString()?.trim() && keywords?.toString()?.trim()?.length >= 1) {
          this.clearSearchTimer();
          this.searchTimer = setTimeout(async () => {
            const result = await this.searchConsultingHandle(keywords.toString().trim());
            if (result) {
              this.updateTemplate(result);
            }
          }, 1000);
        }
      } catch (error) {

      }
    },
    async searchConsultingHandle(keywords) {
      try {
        const searchResult = await searchConsultingApi(keywords);
        if (searchResult.code == 200 && searchResult.data) {
          return searchResult.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    updateTemplate(data) {
      const updateMap = new Map([
        ["advisoryBody.advisoryBodyName", "advisoryBodyName"],
        ["advisoryBody.advisoryBodyCid", "advisoryBodyCid"],
        ["advisoryBody.businessScope", "businessScope"],
        ["isNewAdvisoryBody", "isNewAdvisoryBody"],
        ["corporatePerson", "corporatePerson"],
        ["regAddress", "regAddress"],
      ]);
      this.setTemplateData(updateMap, data);
      console.log(this.comProjectDetailInfo);
    },
    setTemplateData(mapData, data) {
      /** 
       * @type {Map<string,string>}
      */
      const _mapTemp = mapData;
      // 寻找对应的赋值对象
      for (const [key, value] of _mapTemp) {
        const keys = key.split(".");
        const len = keys.length;
        if (len == 1) {
          this.$set(this.comProjectDetailInfo, key, data[value]);
          continue;
        }
        const currentObjectKey = keys[len - 2];
        const currentKey = keys[len - 1];
        const currentObject = this.findCurrent(this.comProjectDetailInfo, currentObjectKey);
        this.$set(currentObject, currentKey, data[value]);
      }
    },
    findCurrent(originData, key) {
      for (const _key in originData) {
        if (_key == key) {
          return originData[_key];
        }
        if (Object.prototype.toString.call(originData[_key]) == "[object Object]") {
          return this.findCurrent(originData[_key], key);
        }
      }
    },
    clearSearchTimer() {
      clearTimeout(this.searchTimer);
      this.searchTimer = null;
    },
    async updateConsultingDetail() {
      try {
        const flag = await this.$refs["comProjectDetailForm"].validate();
        if (flag) {
          // 通过验证校验咨询机构是否存在
          const result = await this.searchConsultingHandle(this.comProjectDetailInfo.advisoryBody.advisoryBodyName);
          if (result.advisoryBodyCid) {
            const _temp = JSON.parse(JSON.stringify(this.comProjectDetailInfo));
            const paramsData = {
              isNewAdvisoryBody: _temp.isNewAdvisoryBody,
              projectKey: _temp.projectKey,
              advisoryBodyCid: _temp.advisoryBody.advisoryBodyCid,
              advisoryBodyName: _temp.advisoryBody.advisoryBodyName ?? "",
              businessScope: _temp.advisoryBody.businessScope ?? "",
              projectLeader: _temp.advisoryBodyProject.projectLeader ?? "",
              projectLeaderMajor: _temp.advisoryBodyProject.projectLeaderMajor ?? "",
              projectLeaderPhone: _temp.advisoryBodyProject.projectLeaderPhone ?? "",
              projectLeaderPhone: _temp.advisoryBodyProject.projectLeaderPhone ?? "",
              settleStartTime: _temp.advisoryBodyProject.settleStartTime ?? "",
              settleFinishTime: _temp.advisoryBodyProject.settleFinishTime ?? "",
              isFinalJudgeUnit: _temp.advisoryBodyProject.isFinalJudgeUnit ?? "",
            };
            this.$emit("editComProjectDetailSuccess", paramsData);
          }
        }
      } catch (error) {
        if (error) {
          for (const key in error) {
            const _temp = error[key];
            _temp instanceof Array ? elementMessageSingleton("error", `${_temp[0].message}`) : null;
            break;
          }
        }
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.consulting-agency-container {
  width: 100%;
  height: 100%;
  background: #fff;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
  overflow: auto;

  ::v-deep .basic-engineering-information-inner {
    width: 100%;
    .info-module-title {
      line-height: 24px;
      color: #232323;
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      & > span {
        display: inline-block;
        position: relative;
        padding-left: 8px;
        box-sizing: border-box;
        &::before {
          content: "";
          position: absolute;
          left: 0px;
          top: 50%;
          transform: translateY(-50%);
          background: rgba(35, 35, 35, 0.8);
          width: 2px;
          height: 14px;
        }
      }
    }
    table {
      width: 100%;
      border-spacing: 0;
      border-collapse: collapse;
      &,
      th,
      td {
        border: 1px solid #e6eaf1;
        box-sizing: border-box;
      }

      td {
        padding: 9px 12px;
        line-height: 22px;
        color: #232323;
        font-size: 12px;
        position: relative;

        .normal-value {
          vertical-align: middle;
          line-height: 22px;
        }

        .el-form-item {
          position: absolute;
          left: 0px;
          top: 0px;
          width: 100%;
          height: 100%;
          margin-bottom: 0px;
          z-index: 9;

          &.is-error {
            .el-form-item__content {
              .el-input {
                .el-input__inner {
                  border-color: #ff4949;
                }
              }
            }
          }

          .el-form-item__content {
            height: 100%;
            font-size: 12px;
            line-height: unset;

            .el-input {
              height: 100%;
              font-size: 12px;
            }

            .el-input__inner {
              height: 40px;
              line-height: 40px;
              border-radius: unset;
              border-color: transparent;
              color: #232323;
              font-size: 12px;
              font-weight: 400;
              padding-left: 12px;
              outline: unset;
              box-sizing: border-box;

              &:focus {
                border: 1px solid #0081ff;
              }
            }

            .el-date-editor {
              width: 100%;

              .el-input__prefix {
                display: none;
              }
            }

            .el-radio-group {
              display: flex;
              height: 100%;
              align-items: center;
              padding-left: 12px;
              box-sizing: border-box;

              .el-radio__input.is-checked .el-radio__inner {
                border-color: #0081ff;
                background: #0081ff;
              }

              .el-radio__input.is-checked + .el-radio__label {
                color: #0081ff;
              }

              .el-radio__inner:hover {
                border-color: #0081ff;
              }
            }
          }
        }
      }

      .table-key {
        background: #f0f3fa;
        color: rgba(35, 35, 35, 0.8);
        width: 140px;
        &.lot {
          height: 62px;
        }
      }
      .data-td {
        width: calc(100% - 140px);
      }
    }

    .project-contact,
    .project-settlement-information {
      margin-top: 24px;
    }
  }
}
</style>
