<template>
  <div class="app-container">

    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
      <h2 style="color: #409EFF;background: #e8e8e8;padding: 15px;border-radius: 10px">工程基本信息填写</h2>
      <el-row :gutter="gutterValue">
        <el-col :span="7">
          <el-form-item label-width="120px" v-no-whitespace label="工程名称" prop="proName">
            <el-input v-model="formData.proName" placeholder="请输入工程名称" :maxlength="60" show-word-limit clearable
                      :style="{width: '90%'}" v-no-whitespace
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="120px" label="工程负责人" prop="proLeader">
            <el-select v-model="formData.proLeader" placeholder="请选择工程负责人" clearable :style="{width: '86.5%'}" @change="changeLeader">
              <el-option v-for="dict in proLeaderOptions"
                         :key="dict.label"
                         :label="dict.label"
                         :value="dict.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="120px" label="负责人联系方式" prop="proLeaderPhone">
            <el-input v-model="formData.proLeaderPhone" placeholder="请输入负责人联系方式" :maxlength="11" :disabled="true"
                      show-word-limit clearable v-no-whitespace
                      :style="{width: '90%'}"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row ::gutter="gutterValue">
        <el-col :span="7">
          <el-form-item label-width="120px" label="工程类型" prop="proType">
            <el-select v-model="formData.proType" placeholder="请选择工程类型" clearable :style="{width: '86.5%'}">
              <el-option v-for="dict in proTypeOptions"
                         :key="dict.value"
                         :label="dict.label"
                         :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="125px" label="计划开工日期" prop="startDate">
            <el-date-picker v-model="formData.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :editable="false" :style="{width: '85%'}" placeholder="请选择计划开工日期"
                            clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="130px" label="计划竣工日期" prop="endDate">
            <el-date-picker v-model="formData.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :editable="false" :style="{width: '89.5%'}" placeholder="请选择计划竣工日期" clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row ::gutter="gutterValue" v-if="formData.proType == 2">
        <el-col :span="7">
          <el-form-item label-width="120px" label="选择监理单位" prop="supervisorUnitId">
            <el-select v-model="formData.supervisorUnitId" placeholder="请选择监理单位" clearable
                       @change="changeSupervisorUnit"
                       :style="{width: '87%'}"
            >
              <el-option v-for="(item,index) in supervisorUnitUserOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="createUnit">创建监理单位</el-button>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="120px" label="选择总监" prop="supervisorUnitUserId">
            <el-select v-model="formData.supervisorUnitUserId" placeholder="请选择总监" clearable
                       @change="changeSupervisorUnitUser"
                       :style="{width: '87%'}"
            >
              <el-option v-for="(item,index) in supervisorUnitOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="createUnitUser">添加总监</el-button>
        </el-col>
      </el-row>
      <h2 style="color: #409EFF;background: #e8e8e8;padding: 15px;border-radius: 10px">工程地址配置</h2>
      <el-row :gutter="gutterValue">
        <el-form-item
          v-for="(domain, index) in formData.proAddress"
          :label="'工程地址' + (index+1)"
          label-width="130px"
          :key="domain.key"
          :prop="'proAddress.' + index + '.value'"
          :rules="{
      required: true, message: '请选择工程地址', trigger: 'change'
    }"
        >
          <el-select v-model="domain.value" placeholder="请选择工程地址" clearable @clear="clearAddress(index)"
                     :style="{width: '26%'}"
                     @change="changeLonLat(domain.value,index)"
          >
            <el-option v-for="(option, i) in proAddressOptions" :key="i" :label="option.label" :value="option.value"
                       :disabled="option.disabled"
            ></el-option>
          </el-select>
          <el-input v-model="domain.lon" placeholder="经度" clearable :disabled="true"
                    :style="{width: '20%',marginLeft:'2%'}" v-no-whitespace
          ></el-input>
          <el-input v-model="domain.lat" placeholder="经度" clearable :disabled="true"
                    :style="{width: '20%',marginLeft:'2%'}" v-no-whitespace
          ></el-input>
          <el-button type="primary" plain size="medium" icon="el-icon-circle-plus" circle :style="{marginLeft:'2%'}"
                     @click="addAddressOption"
          ></el-button>
          <el-button v-if="index !== 0" v-show="true" type="danger" plain icon="el-icon-remove" circle
                     @click="removeAddressOption(domain)"
          ></el-button>
          <el-button v-if="index === 0" v-show="true" type="primary" @click="addAddress">新增地址</el-button>
        </el-form-item>

      </el-row>
      <h2 style="color: #409EFF;background: #e8e8e8;padding: 15px;border-radius: 10px">承包商配置</h2>
      <el-row :gutter="gutterValue">
        <el-form-item
          v-for="(domain, index) in formData.consArr"
          :label="'选择承包商' + (index+1)"
          label-width="120px"
          :key="domain.key"
          :prop="'consArr.' + index + '.value'"
          :rules="{
      required: true, message: '请选择承包商', trigger: 'change'
    }"
        >
          <el-col :span="7">
            <el-select v-model="domain.value" placeholder="请选择承包商" clearable :style="{width: '93%'}"
                       @change="changeCons(domain.value,index)"
            >
              <el-option v-for="(option, i) in consOptions" :key="i" :label="option.label" :value="option.value"
                         :disabled="option.disabled"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="12" style="display: flex;flex-direction: row">
            <span style="color:red;">*</span>
            <el-form-item label-width="160px" label="承包商需上传材料选择" prop="checkListTemp">
              <el-checkbox-group v-model="domain.checkList">
                <el-checkbox v-for="(option,index) in materialOptions" :label="option.value" :key="index">
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" plain size="medium" icon="el-icon-circle-plus" circle
                       @click="addConsOption"
            ></el-button>
            <el-button v-if="index !== 0" v-show="true" type="danger" plain icon="el-icon-remove" circle
                       @click="removeConsOption(domain)"
            ></el-button>
            <el-button v-if="index === 0" v-show="true" type="primary" @click="addCons">新增承包商单位</el-button>
          </el-col>
        </el-form-item>

      </el-row>
    </el-form>
    <el-dialog :title="'创建工程地址'" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <bns-map
        :items="mapItems"
        v-on:closeMain="closeMain"
      >
      </bns-map>
    </el-dialog>

    <!--   创建监理单位 -->
    <el-dialog :title="'创建监理单位'" :visible.sync="supervisorFormOpen" width="30%" :close-on-click-modal="false">
      <el-form ref="unitForm" :model="unitForm" :rules="unitRules" size="medium" label-width="100px">
        <el-form-item label="监理单位名称" prop="unitName" label-width="140px">
          <el-input v-model="unitForm.unitName" placeholder="请输入监理单位名称" show-word-limit :maxlength="60"
                    @blur="checkIsExistUnitName" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="监理单位地址" prop="unitAddress" label-width="140px">
          <el-input v-model="unitForm.unitAddress" placeholder="请输入监理单位地址" show-word-limit :maxlength="200"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" prop="corporateName" label-width="140px">
          <el-input v-model="unitForm.corporateName" placeholder="请输入法人姓名" show-word-limit :maxlength="20"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人联系方式" prop="corporatePhone" label-width="140px">
          <el-input v-model="unitForm.corporatePhone" placeholder="请输入法人联系方式" show-word-limit :maxlength="11"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="社会统一征信代码" prop="socialUnifiedCreditCode" label-width="140px">
          <el-input v-model="unitForm.socialUnifiedCreditCode" placeholder="请输入社会统一征信代码" show-word-limit
                    :maxlength="20" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
<!--        <el-form-item label="总监" prop="directorsName" label-width="140px">-->
<!--          <el-input v-model="unitForm.directorsName" placeholder="请输入总监姓名" show-word-limit :maxlength="20"-->
<!--                    clearable v-no-whitespace-->
<!--                    :style="{width: '100%'}"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="总监联系方式" prop="directorsPhone" label-width="140px">-->
<!--          <el-input v-model="unitForm.directorsPhone" placeholder="请输入总监联系方式" show-word-limit :maxlength="11"-->
<!--                    clearable v-no-whitespace-->
<!--                    :style="{width: '100%'}"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="总监身份证" prop="directorsIdCard" label-width="140px">-->
<!--          <el-input v-model="unitForm.directorsIdCard" placeholder="请输入总监身份证" show-word-limit :maxlength="18"-->
<!--                    clearable v-no-whitespace-->
<!--                    :style="{width: '100%'}"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUnitUserForm" v-preventReClick="5000">提 交</el-button>
        <el-button @click="unitCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--   添加总监-->
    <el-dialog :title="'添加总监'" :visible.sync="supervisorUserFormOpen" width="30%" :close-on-click-modal="false">
      <el-form ref="unitForm" :model="unitForm" :rules="unitRules" size="medium" label-width="100px">

        <el-form-item label="总监" prop="directorsName" label-width="140px">
          <el-input v-model="unitForm.directorsName" placeholder="请输入总监姓名" show-word-limit :maxlength="20"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="总监联系方式" prop="directorsPhone" label-width="140px">
          <el-input v-model="unitForm.directorsPhone" placeholder="请输入总监联系方式" show-word-limit :maxlength="11"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="总监身份证" prop="directorsIdCard" label-width="140px">
          <el-input v-model="unitForm.directorsIdCard" placeholder="请输入总监身份证" show-word-limit :maxlength="18"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUnitForm" v-preventReClick="5000">提 交</el-button>
        <el-button @click="unitUserCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--   创建承包商单位 -->
    <el-dialog :title="'创建承包商单位'" :visible.sync="consFormOpen" width="30%" :close-on-click-modal="false">
      <el-form ref="consForm" :model="consForm" :rules="consRules" size="medium" label-width="100px">
        <el-form-item label="承包商单位名称" prop="consName" label-width="170px">
          <el-input v-model="consForm.consName" placeholder="请输入承包商单位名称" show-word-limit :maxlength="60"
                    @blur="checkIsExistConsName" v-no-whitespace
                    clearable
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="consAddress" label-width="170px">
          <el-input v-model="consForm.consAddress" placeholder="请输入单位地址" show-word-limit :maxlength="200"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" prop="corporateName" label-width="170px">
          <el-input v-model="consForm.corporateName" placeholder="请输入法人姓名" show-word-limit :maxlength="20"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人联系方式" prop="corporatePhone" label-width="170px">
          <el-input v-model="consForm.corporatePhone" placeholder="请输入法人联系方式" show-word-limit :maxlength="11"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="社会统一征信代码" prop="socialUnifiedCreditCode" label-width="170px">
          <el-input v-model="consForm.socialUnifiedCreditCode" placeholder="请输入社会统一征信代码" show-word-limit
                    :maxlength="20" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="承包商负责人" prop="contractorPrincipal" label-width="170px">
          <el-input v-model="consForm.contractorPrincipal" placeholder="请输入承包商负责人" show-word-limit
                    :maxlength="20" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="承包商负责人联系方式" prop="contractorPrincipalPhone" label-width="170px">
          <el-input v-model="consForm.contractorPrincipalPhone" placeholder="请输入承包商负责人联系方式" show-word-limit
                    :maxlength="11" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="承包商负责人身份证" prop="contractorPrincipalIdCard" label-width="170px">
          <el-input v-model="consForm.contractorPrincipalIdCard" placeholder="请输入承包商负责人身份证" show-word-limit
                    :maxlength="18" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConsForm" v-preventReClick="5000">提 交</el-button>
        <el-button @click="consCancel">取 消</el-button>
      </div>
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="position: absolute;top: 90%;left: 85%">
      <el-button @click="resetForm" :style="{float:'right',marginLeft:'10px'}">取 消</el-button>
      <el-button type="primary" @click="submitForm" :style="{float:'right'}" v-preventReClick="5000">提 交</el-button>
    </div>
  </div>

</template>
<script>
import bnsMap from '@/components/pro-tabs/bns-map.vue'
import {
  dictTableOption,
  selectProAddress,
  selectCons,
  selectMaterial,
  selectSupervisionUnit, getProLeaderOption, selectSupervisionUnitUser,
} from '@/api/tool/select'
import {
  addSupervisoryUnit,
  addConsUnit,
  addProInfo,
  updateProInfo,
  selectProInfoDetails,
  checkIsExistUnitName,
  checkIsExistConsName,
  checkIsExistProName, addSupervisoryUnitUser,
} from '@/api/pro/proList'
import numberUtils from '@/utils/validate'

export default {
  components: { bnsMap },
  props: [],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 是否显示创建监理单位弹出层
      supervisorFormOpen: false,

      supervisorUserFormOpen: false,
      // 是否显示创建承包商单位弹出层
      consFormOpen: false,
      // 是否显示创建工程地址弹出层
      open: false,
      // 监理单位form表单
      unitForm: {},
      // 承包商单位form表单
      consForm: {},
      // 工程地址form表单
      proAddressForm: {},
      //工程地址
      mapItems: {},
      //监理单位form表单 校验
      unitRules: {
        unitName: [{
          required: true,
          message: '请输入监理单位名称',
          trigger: 'blur'
        }],
        unitAddress: [{
          required: true,
          message: '请输入监理单位地址',
          trigger: 'blur'
        }],
        corporateName: [{
          required: true,
          message: '请输入法人姓名',
          trigger: 'blur'
        }],
        corporatePhone: [{
          required: true,
          validator: numberUtils.checkPhone,
          trigger: 'blur'
        }],
        socialUnifiedCreditCode: [{
          required: true,
          message: '请输入社会统一征信代码',
          trigger: 'blur'
        }, {
          pattern: /^[a-zA-Z0-9]+$/,
          message: '请输入数字或字母',
          trigger: 'blur'
        }],
        directorsName: [{
          required: true,
          message: '请输入总监姓名',
          trigger: 'blur'
        }],
        directorsPhone: [{
          required: true,
          validator: numberUtils.checkPhone,
          trigger: 'blur'
        }],
        directorsIdCard: [{
          required: true,
          validator: numberUtils.checkIdCardNumber,
          trigger: 'blur'
        }]
      },
      //承包商单位form表单 校验
      consRules: {
        consName: [{
          required: true,
          message: '请输入承包商单位名称',
          trigger: 'blur'
        }],
        consAddress: [{
          required: true,
          message: '请输入单位地址',
          trigger: 'blur'
        }],
        corporateName: [{
          required: true,
          message: '请输入法人姓名',
          trigger: 'blur'
        }],
        corporatePhone: [{
          required: true,
          validator: numberUtils.checkPhone,
          trigger: 'blur'
        }],
        socialUnifiedCreditCode: [{
          required: true,
          message: '请输入社会统一征信代码',
          trigger: 'blur'
        }, {
          pattern: /^[a-zA-Z0-9]+$/,
          message: '请输入数字或字母',
          trigger: 'blur'
        }],
        contractorPrincipal: [{
          required: true,
          message: '请输入承包商负责人',
          trigger: 'blur'
        }],
        contractorPrincipalPhone: [{
          required: true,
          validator: numberUtils.checkPhone,
          trigger: 'blur'
        }],
        contractorPrincipalIdCard: [{
          required: true,
          validator: numberUtils.checkIdCardNumber,
          trigger: 'blur'
        }]
      },
      gutterValue: parseInt('20', 10),
      mainFormFields: [  // 主表单字段定义
        {
          label: '工程地址',
          prop: 'proAddress',
          type: 'select',
          labelWidth: '120px',
          disabled: false,
          options: this.proAddressOptions
        },
        { label: '经度', prop: 'lon', type: 'input', labelWidth: '120px', disabled: true },
        { label: '纬度', prop: 'lat', type: 'input', labelWidth: '120px', disabled: true }
      ],
      isOne:{
          one:false
      },
      formData: {
        proId: undefined,
        jlId:undefined,
        //工程名称
        proName: undefined,
        //工程负责人
        proLeader: undefined,
        proLeaderId: undefined,
        //工程负责人联系方式
        proLeaderPhone: undefined,
        //工程类型
        proType: undefined,
        //开工日期
        startDate: null,
        //竣工日期
        endDate: null,
        //监理单位
        supervisorUnit: undefined,

        supervisorUnitUser: undefined,
        //监理单位id
        supervisorUnitId: undefined,
        //人员id
        supervisorUnitUserId: undefined,
        //工程地址
        proAddress: [
          {
            label: '',
            value: '',
            lon: '',
            lat: '',
            key: Date.now()
          }
        ],
        //承包商
        consArr: [
          {
            label: '',
            value: '',
            checkList: [],
            key: Date.now()
          }
        ]
      },
      //主表单校验
      rules: {
        proName: [{
          required: true,
          message: '请输入工程名称',
          trigger: 'blur'
        }],
        proLeader: [{
          required: true,
          message: '请选择工程负责人',
          trigger: 'change'
        }],
        // proLeaderPhone: [{
        //   required: true,
        //   validator: numberUtils.checkPhone,
        //   trigger: 'blur'
        // }],
        supervisorUnit: [{
          required: true,
          message: '请选择监理单位',
          trigger: 'change'
        }],
        startDate: [{
          required: true,
          message: '请选择计划开工日期',
          trigger: 'change'
        }],
        endDate: [{
          required: true,
          message: '请选择计划竣工日期',
          trigger: 'change'
        }],
        proType: [{
          required: true,
          message: '请选择工程类型',
          trigger: 'change'
        }],
        supervisorUnitId: [{ required: true, message: '请选择监理单位', trigger: 'blur' }],
        supervisorUnitUserId: [{ required: true, message: '请选择总监', trigger: 'blur' }]
      },
      // 监理单位校验
      supervisorUnitRules: {},
      //工程类型下拉选
      proTypeOptions: [],
      //监理单位下拉选
      supervisorUnitOptions: [],
      supervisorUnitUserOptions: [],
      //承包商下拉选
      consOptions: [],
      //材料选项
      materialOptions: [],
      //工程地址选项
      proAddressOptions: [],
      proLeaderOptions: [],
    }
  },
  computed: {},
  watch: {
    // 监听项目类型的变化，根据不同的值动态设置校验规则
    'formData.proType'(newVal) {
      console.log(newVal)
      console.log(this.formData.proType)
      if (newVal === 1) {
        this.$set(this.supervisorUnitRules, 0, { required: true, message: '请选择监理单位', trigger: 'blur' })
      } else {
        // 当不选择外委外包项目时，取消监理单位的校验规则
        this.$delete(this.supervisorUnitRules, 0)
        // 重置监理单位字段的值，确保不触发错误提示
        this.formData.supervisorUnit = ''
      }
    },
    'formData.supervisorUnitId'(newVal) {
      this.formData.jlId=newVal;
      console.log(this.isOne.one,"-->one"
      )
      if(!this.isOne.one){
        this.formData.supervisorUnitUserId='';
        this.formData.supervisorUnitUser='';
      }else{
        this.isOne.one=false;
      }
      this.supervisorUnitOptions=[];
      this.getSupervisionUnit(newVal)


    },
    open: {
      handler(newVal, oldVal) {
        // 在 mapItems 数据变化后，关闭 el-dialog
        if (newVal === false) {
          // 或者其他关闭对话框的逻辑
          this.getProAddress()
        }
      },
      deep: true // 监听对象或数组的变化
    }
  },
  created() {
    const proId = this.$route.params && this.$route.params.proId
    this.proId = proId
    this.getProType()
    this.getProAddress()
    this.getCons()
    this.getMaterial()
    this.getProLeaderOption()

    this.selectSupervisionUnitUser()
    if (proId !== '0') {
      this.getData(proId)
    }
  }
  ,
  mounted() {
  }
  ,
  methods: {
    //检查工程名称是否存在
    async checkIsExistProName() {
      const params = {
        proName: this.formData.proName,
        proId: this.formData.proId
      }
      try {
        const response = await checkIsExistProName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
          // 返回 false 或者其他值，表示单位名称已存在
          return false
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true
        }
      } catch (error) {
        return false
      }
    }
    ,
    //检查单位名称是否存在
    async checkIsExistUnitName() {
      const params = {
        unitName: this.unitForm.unitName
      }
      try {
        const response = await checkIsExistUnitName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
          // 返回 false 或者其他值，表示单位名称已存在
          return false
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true
        }
      } catch (error) {
        return false
      }
    }
    ,
    //检查承包商单位名称是否存在
    async checkIsExistConsName() {
      const params = {
        consName: this.consForm.consName
      }
      try {
        const response = await checkIsExistConsName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
          // 返回 false 或者其他值，表示单位名称已存在
          return false
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true
        }
      } catch (error) {
        return false
      }
    },
    clearAddress(index) {
      this.formData.proAddress[index].lon = ''
      this.formData.proAddress[index].lat = ''
    },
    //获取工程类型选项
    getProType() {
      const params = {
        dictType: 'sys_pro_type',
        dictValue: ''
      }
      dictTableOption(params).then(response => {
        this.proTypeOptions = response.data
      })
    },
    //获取工程类型选项
    getProLeaderOption() {
      getProLeaderOption({}).then(response => {
        this.proLeaderOptions = response.data
      })
    },
    //获取工程地址选项
    getProAddress() {
      const params = {}
      selectProAddress(params).then(response => {
        this.proAddressOptions = response.data
      })
    },
    //获取承包商选项
    getCons() {
      const params = {}
      selectCons(params).then(response => {
        this.consOptions = response.data
      })
    },
    //获取材料选项
    getMaterial() {
      const params = {}
      selectMaterial(params).then(response => {
        this.materialOptions = response.data
      })
    },
    //获取监理单位人员
    getSupervisionUnit(key) {
      const params = {
        'key':key
      }
      selectSupervisionUnit(params).then(response => {
        console.log(response)
        this.supervisorUnitOptions = response.data
      })
    },
    //获取监理单位
    selectSupervisionUnitUser() {
      const params = {}
      selectSupervisionUnitUser(params).then(response => {
        console.log(response)
        this.supervisorUnitUserOptions = response.data
      })
    },
    //提交工程表单
    async submitForm() {
      this.$refs['elForm'].validate(async valid => {
        if (!valid) {
          return false
        } else {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistProName()
          if (isExist === false) {
            // 如果工程名称已存在，可以做出相应的提示或处理
            return
          }
          if (this.formData.startDate >= this.formData.endDate) {
            this.$message({
              message: '计划竣工日期不能早于或等于计划开工日期',
              type: 'error'
            })
            return false
          }
          if (this.hasDuplicates(this.formData.proAddress,'label')){
            this.$message({
              message: '工程地址不能重复',
              type: 'error'
            })
            return false
          }
          if (this.hasDuplicates(this.formData.consArr,'label')){
            this.$message({
              message: '承包商不能重复',
              type: 'error'
            })
            return false
          }
          for (let i = 0; i < this.formData.consArr.length; i++) {
            if (this.formData.consArr[i].checkList.length === 0) {
              this.$message({
                message: '请选择材料',
                type: 'error'
              })
              return false
            }
          }
          this.loading = true
          if (this.proId !== '0') {
            // TODO 提交表单
            updateProInfo(this.formData).then(response => {
              if (response.code === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loading = false
                this.resetForm()
                this.formData.consArr = []
                this.formData.proAddress = []
                //关闭tab页
                // this.close()
              } else {
                this.loading = false
                this.$message({
                  message: response.msg,
                  type: 'error'
                })
              }
            })
          } else {
            // TODO 提交表单
            addProInfo(this.formData).then(response => {
              if (response.code === 200) {
                this.loading = false
                this.$message({
                  message: '新建成功',
                  type: 'success'
                })
                this.resetForm()
                this.formData.consArr = []
                this.formData.proAddress = []
                //关闭tab页
                // this.close()
              } else {
                this.loading = false
                this.$message({
                  message: response.msg,
                  type: 'error'
                })
              }
            })
          }
        }
      })
    },
    /**
     * 判断对象数组中的数据是否重复
     * @param arr
     * @param key
     * @returns {boolean}
     */
    hasDuplicates(arr, key) {
      const seen = new Set()
      for (const item of arr) {
        if (seen.has(item[key])) {
          return true
        }
        seen.add(item[key])
      }
      return false
    },
    //提交监理表单
    async submitUnitForm() {
      this.$refs['unitForm'].validate(async valid => {
        if (!valid) {
          return false
        } else {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistUnitName()
          if (isExist === false) {
            // 如果单位名称已存在，可以做出相应的提示或处理
            return
          }
          console.log(this.formData)
          this.unitForm.jlId=this.formData.jlId;
          // TODO 提交表单
          addSupervisoryUnit(this.unitForm).then(response => {
            if (response.code === 200) {
              this.getSupervisionUnit(this.unitForm.jlId)
              this.$message({
                message: '新建成功',
                type: 'success'
              })
              this.formData.supervisorUnit = this.unitForm.unitName
              this.unitResetForm()
              this.supervisorUserFormOpen = false
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },

    //提交监理表单
    async submitUnitUserForm() {
      this.$refs['unitForm'].validate(async valid => {
        if (!valid) {
          return false
        } else {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistUnitName()
          if (isExist === false) {
            // 如果单位名称已存在，可以做出相应的提示或处理
            return
          }
          // TODO 提交表单
          addSupervisoryUnitUser(this.unitForm).then(response => {
            if (response.code === 200) {
              this.$message({
                message: '新建成功',
                type: 'success'
              })
              this.selectSupervisionUnitUser()
              this.formData.supervisorUnit = this.unitForm.unitName
              this.unitResetForm()
              this.supervisorFormOpen = false
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    //提交承包商表单
    async submitConsForm() {
      this.$refs['consForm'].validate(async valid => {
        if (!valid) {
          return false
        } else {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistConsName()
          if (isExist === false) {
            // 如果单位名称已存在，可以做出相应的提示或处理
            return
          }
          // TODO 提交表单
          addConsUnit(this.consForm).then(response => {
            if (response.code === 200) {
              this.$message({
                message: '新建成功',
                type: 'success'
              })
              this.getCons()
              for (let i = 0; i < this.consOptions.length; i++) {
                if (this.consOptions[i].label === this.consForm.consName) {
                  this.formData.consArr[this.formData.consArr.length - 1].value = this.consOptions[i].value
                  this.formData.consArr[this.formData.consArr.length - 1].label = this.consOptions[i].label
                }
              }

              this.consResetForm()
              this.consFormOpen = false
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    //工程表单重置
    resetForm() {
      this.$refs['elForm'].resetFields()
      // this.close()
      const obj = { path: '/project/projectManagement/proList/index' }
      this.$tab.closeOpenPage(obj)
    },
    //监理单位表单重置
    unitResetForm() {
      this.unitForm = {
        unitName: undefined,
        jlId:undefined,
        unitAddress: undefined,
        corporateName: undefined,
        corporatePhone: undefined,
        socialUnifiedCreditCode: undefined,
        directorsName: undefined,
        directorsPhone: undefined
      }
    },
    //承包商表单重置
    consResetForm() {
      this.consForm = {
        consName: undefined,
        consAddress: undefined,
        corporateName: undefined,
        corporatePhone: undefined,
        socialUnifiedCreditCode: undefined,
        contractorPrincipal: undefined,
        contractorPrincipalPhone: undefined
      }
    },
    //监理单位表单重置
    unitCancel() {
      this.unitResetForm()
      this.supervisorFormOpen = false
    },
    unitUserCancel() {
      this.unitResetForm()
      this.supervisorUserFormOpen = false
    },
    //承包商单位表单重置
    consCancel() {
      this.consResetForm()
      this.consFormOpen = false
    },
    createUnit() {
      //创建监理单位
      this.unitResetForm()
      this.supervisorFormOpen = true
    },
    createUnitUser() {
      //创建监理单位
      this.unitResetForm()
      this.supervisorUserFormOpen = true
    },
    addCons() {
      //创建监理单位
      this.consResetForm()
      this.consFormOpen = true
    },
    //新增工程地址
    addAddress() {
      // this.proAddressCancel();
      this.open = true
      this.mapItems = { addressId: -1, open: 'true' }
    },
    //添加工程地址选项
    addAddressOption() {
      this.formData.proAddress.push({
        label: '',
        value: '',
        lon: '',
        lat: '',
        key: Date.now()
      })
    },
    //移除工程地址选项
    removeAddressOption(item) {
      const i = this.formData.proAddress.indexOf(item)
      if (i !== -1) {
        this.formData.proAddress.splice(i, 1)
      }
    },
    //添加承包商选项
    addConsOption() {
      this.formData.consArr.push({
        label: '',
        value: '',
        checkList: [],
        key: Date.now()
      })
    },
    //移除承包商选项
    removeConsOption(item) {
      const i = this.formData.consArr.indexOf(item)
      if (i !== -1) {
        this.formData.consArr.splice(i, 1)
      }
    },
    //更改工程地址选项   同时修改对应的经纬度
    changeLonLat(e, index) {
      if (e === undefined || e === '') {
        return
      }
      for (let i = 0; i < this.proAddressOptions.length; i++) {
        const item = this.proAddressOptions[i]
        if (e === item.value) {
          this.formData.proAddress[index].label = item.label
          this.formData.proAddress[index].value = item.value
          this.formData.proAddress[index].lon = item.lon
          this.formData.proAddress[index].lat = item.lat
        }
      }
    },
    changeLeader(e, index){
      console.log(e)
      if (e === undefined || e === '') {
        return
      }
      for (let i = 0; i < this.proLeaderOptions.length; i++) {
        const item = this.proLeaderOptions[i]
        if (e === item.label) {
          this.formData.proLeader = item.label
          this.formData.proLeaderPhone = item.phone
          this.formData.proLeaderId = item.value
        }
      }
    },
    //更改监理单位名称值
    changeSupervisorUnit() {
      this.supervisorUnitUserOptions.forEach(item => {
        if (item.value === this.formData.supervisorUnitId) {
          this.formData.supervisorUnit = item.label
        }
      })
    },
    //更改监理单位名称值
    changeSupervisorUnitUser() {
      this.supervisorUnitOptions.forEach(item => {
        if (item.value === this.formData.supervisorUnitUserId) {
          this.formData.supervisorUnitUser = item.label
        }
      })
    },

    //更改承包商名称值
    changeCons(e, index) {
      if (e === undefined || e === '') {
        return
      }
      for (let i = 0; i < this.consOptions.length; i++) {
        const item = this.consOptions[i]
        if (e === item.value) {
          this.formData.consArr[index].label = item.label
          this.formData.consArr[index].value = item.value
        }
      }
    },
    /** 关闭按钮 */
    close() {
      this.$tab.closePage()
    }
    ,
    getData(proId) {
      this.loading = true
      // TODO 获取数据
      selectProInfoDetails(proId).then(response => {
        this.isOne.one=true;
        console.log(5)
        console.log( response.projectInfo[0].supervisorUnitUserId)
        console.log( response.projectInfo[0].supervisorUnitUser)
        console.error(response.projectInfo[0])
        this.formData= response.projectInfo[0]
        this.loading = false
      })
    },
    closeMain() {
      this.open = false
      console.log('closeMain')
    }
  }
}
</script>
<style>
</style>
