<template>
    <!-- 工程管理 新增、编辑 表单组件 -->
    <div>
        <el-form
            label-width="100px"
            size="medium"
            ref="projectParamsRef"
            :model="projectParams"
            :rules="projectParamsRules"
        >
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="工程名称" prop="proName">
                <el-select
                  v-model="projectParams.proName"
                  allow-create
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in projNameRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属项目部" prop="departId">
                <el-select
                  v-model="projectParams.departId"
                  clearable
                  filterable
                  placeholder="请选择"
                  @change="departChange"
                  class="custom-select"
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in deptRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  <template
                  v-if="item.label.length > maxlength">
                  <el-tooltip
                    class="item-tooltip"
                    effect="dark"
                    :content="item.label"
                    placement="top"
                  >
                    <span class="ellipsis">{{ item.label }}</span>
                   </el-tooltip>
                  
                  </template>
                  
                </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="电压等级" prop="relId">
                <el-select
                  v-model="projectParams.relId"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in volRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建管单位" prop="areaId">
                <el-select
                  v-model="projectParams.areaId"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in provinceRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="工程类型" prop="proType">
                <el-select
                  v-model="projectParams.proType"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in projTypeRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程状态" prop="proStatus">
                <el-select
                  v-model="projectParams.proStatus"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in projStatusRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="经度" prop="lon">
                <el-input :maxlength="50" v-model="projectParams.lon" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="lat">
                <el-input :maxlength="50" v-model="projectParams.lat" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
              <el-button type="success" @click="onSubmit">确认</el-button>
              <el-button
                  @click="
                      () => {
                          this.$emit('closeDialog')
                      }
                  "
                  >取消</el-button
              >
          </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {
  addProjApi,
  editProjApi,
  queryProjNameApi,
  queryProjTypeApi,
  queryDeptApi,
  queryVolLevelApi
} from '@/api/base/proj'
import {
  queryProvincesApi,
  queryProjDeptListApi
} from '@/api/base/projDept'
export default {
    name: 'FormProject',
    props: {
        editParams: {
            type: Object,
            default: () => null,
        },
    },
    components: {  },
    created() {
      this.getRanges()
    },
    mounted() {
        console.log(this.editParams)
        if (this.editParams) {
            Object.assign(this.projectParams, this.editParams)
            this.subSort = 2
        } else {
            this.subSort = 1
        }
    },
    data() {
        return {
          maxlength: 20,
            subSort: '', // 提交类型：新增 1 / 修改 2
            projectParams: {
              proName: undefined, //工程名称
              departId: undefined, //所属项目部
              relId: undefined, // 电压等级
              areaId: undefined, // 建管单位
              proType: undefined, //工程类型
              proStatus: undefined, // 工程状态
              lon: undefined, // 经度
              lat: undefined, // 纬度
            },
            // 校验规则
            projectParamsRules: {
              proName: [
                  {
                      required: true,
                      message: '请输入工程名称',
                      trigger: 'blur',
                  },
              ],
              departId: [
                {
                  required: true,
                  message: '请输入所属项目部',
                  trigger: 'blur',
                },
              ],
              relId: [
                {
                  required: true,
                  message: '请输入电压等级',
                  trigger: 'blur',
                },
              ],
              areaId: [
                {
                  required: true,
                  message: '请输入建管单位',
                  trigger: 'blur',
                },
              ],
              proType: [
                {
                  required: true,
                  message: '请输入工程类型',
                  trigger: 'blur',
                },
              ],
              proStatus: [
                {
                  required: true,
                  message: '请输入工程状态',
                  trigger: 'blur',
                },
              ],
              lon: [
                { required: true, message: "经度不能为空", trigger: "blur" },
                {
                  validator: (rule, value, callback) => {
                    if (value === '' || value === null) {
                      return callback(new Error('请必须输入-180 ~ 180内的数据且小数点后最多保留六位'));
                    }
                    const regex = /^[+-]?(0|[1-9]\d*)(\.\d+)?$/;
                    if(!regex.test(value)){
                      return callback(new Error('请勿输入非数字'));
                    }
                    const longitude = parseFloat(value);
                    if(longitude.toString().includes('.') === true){
                      if (longitude <-180  || longitude > 180 ||longitude.toString().split(".")[1].length>6) {
                        callback(new Error('请必须输入-180 ~ 180内的数据且小数点后最多保留六位'));
                      } else {
                        callback();
                      }
                    }else{
                      if (longitude <-180  || longitude > 180) {
                        callback(new Error('请必须输入-180 ~ 180内的数据且小数点后最多保留六位'));
                      } else {
                        callback();
                      }
                    }
                  },
                  trigger: 'blur'
                }
              ],
              lat: [
                { required: true, message: "纬度不能为空", trigger: "blur" },
                {
                  validator: (rule, value, callback) => {
                    if (value === '' || value === null) {
                      return callback(new Error('请必须输入-90 ~ 90内的数据且小数点后最多保留六位'));
                    }
                    const regexTwo = /^[+-]?(\d+(\.\d*)?|\.\d*[1-9]\d*)$/;
                    if(!regexTwo.test(value)){
                      return callback(new Error('请勿输入非数字'));
                    }
                    const latitude = parseFloat(value);
                    if(latitude.toString().includes('.') === true){
                      if (latitude <-90  || latitude > 90 ||latitude.toString().split(".")[1].length>6) {
                        callback(new Error('请必须输入-90 ~ 90内的数据且小数点后最多保留六位'));
                      } else {
                        callback();
                      }
                    }else{
                      if (latitude <-90  || latitude > 90) {
                        callback(new Error('请必须输入-90 ~ 90内的数据且小数点后最多保留六位'));
                      } else {
                        callback();
                      }
                    }
                  },
                  trigger: 'blur'
                }
              ],
            },
            // 各类下拉
            projNameRange: [],
            deptRange: [],
            volRange: [],
            projStatusRange: [
              { label: '施工', value: '0' },
              { label: '暂停', value: '1' },
            ],
            projTypeRange: [
              { label: '变电工程', value: '1' },
              { label: '线路工程', value: '2' },
              { label: '电缆工程', value: '3' },
            ],
            provinceRange: [],
            // 手机号正则
            phoneReg: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            // 经纬正则
            lonLatReg: /^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/
        }
    },
    methods: {
        /** 校验经纬 */
        validateLonLat(rule, value, callback) {
          if(!this.lonLatReg.test(value)) {
            callback(new Error('经纬度格式不正确'))
          } else {
            callback()
          }
        },
        /** 获取各类下拉框 */
        async getRanges() {
          // 获取工程名称下拉选
          let nameRes = await queryProjNameApi()
          this.projNameRange = nameRes.data.map(item => {
            return {
              label: item.proName,
              value: item.proName,
              departId: item.departId,
              relId: item.relName,
              areaId: item.areaId,
              proType: item.proTypeName,
              proStatus: item.proStatusName,
              lon: item.lon,
              lat: item.lat
            }
          })
          // 获取工程类型下拉选
          let typeRes = await queryProjTypeApi({
            dictType: 'pro_type'
          })
          /* this.provinceRange = provinceRes.data.map(item => {
            return {
              label: item.areaName,
              value: item.areaId
            }
          }) */
          // 获取省份下拉选
          let provinceRes = await queryProvincesApi()
          this.provinceRange = provinceRes.data.map(item => {
            return {
              label: item.areaName,
              value: item.areaId
            }
          })
          // 获取所属项目部下拉选
          let deptRes = await queryDeptApi({
            isAll: 0
          })
          this.deptRange = deptRes.data.map(item => {
            return {
              label: item.departName,
              value: item.id,
            }
          })
          // 获取电压等级下拉选
          let volRes = await queryVolLevelApi({
            dictType: 'rel_level'
          })
          this.volRange = volRes.data.map(item => {
            return {
              label: item.dictLabel,
              value: item.dictCode
            }
          })
        },
        /** 改变树结构 */
        changeTree(leaf) {
          leaf.map(item => {
            item.value = item.id
            if(item.children) {
              this.changeTree(item.children)
            }
          })
          return leaf
        },
        /** 工程名称改变 */
        proNameChange(e) {
          this.projNameRange.forEach(item => {
            if(e === item.label) {
              console.log(e, item)
              this.projectParams.departId = item.departId
              this.projectParams.relId = item.relId
              this.projectParams.areaId = item.areaId
              this.projectParams.proType = item.proType
              this.projectParams.proStatus = item.proStatus
              this.projectParams.lon = item.lon
              this.projectParams.lat = item.lat
            }
          })
        },
        /** 项目部改变 */
        async departChange(e) {
          let res = await queryProjDeptListApi({
            id: e
          })
          this.projectParams.areaId = res.data.rows[0].areaId
        },
        /** 确认按钮 */
        onSubmit() {
            this.$refs.projectParamsRef.validate(valid => {
                if (valid) {
                    console.log('校验通过', this.projectParams, this.subSort)
                    // 1. 表单校验通过后调后台 Api
                    if(this.subSort === 1) {
                      addProjApi(this.projectParams).then(res => {
                        this.$modal.msgSuccess('操作成功')
                        // 2. 成功之后通知父组件关闭弹框
                        this.$emit('closeDialog', true)
                      }).catch(err => {
                        console.log(err)
                      })
                    } else if(this.subSort === 2) {
                      editProjApi(this.projectParams).then(res => {
                        this.$modal.msgSuccess('操作成功')
                        // 2. 成功之后通知父组件关闭弹框
                        this.$emit('closeDialog', true)
                      }).catch(err => {
                        console.log(err)
                      })
                    }
                }
            })
        },
    },
}
</script>

<style scoped>
::v-deep .el-select {
    width: 100%;
}
/* .custom-select .el-select-dropdown__item{
  max-width: 400px; 
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap; 

} */

.ellipsis {
  display: block; /* 确保是块级元素 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏超出的部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 400px; /* 设置最大宽度，调整为你需要的值 */
}
 
::v-deep .el-form-item__label{
  font-weight: normal;
}
</style>
