<template>
  <!-- 工程管理页面 -->
  <div class="app-container">
    <el-form
      label-width="100px"
      size="medium"
      ref="towerAddParamsRef"
      :model="towerAddParams"
      :rules="towerAddParamsRules"
    >
      <el-form-item label="杆塔名称" prop="gtName">
        <el-select
          v-model="towerAddParams.gtName"
          clearable
          filterable
          allow-create
          placeholder="请选择"
          style="width: 100%"
          @change="towerChange"
        >
          <el-option
            v-for="item in towerRange"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="坐标经度" prop="lon">
        <el-input :maxlength="50" v-model="towerAddParams.lon" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="坐标纬度" prop="lat">
        <el-input :maxlength="50" v-model="towerAddParams.lat" placeholder="请输入" />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="onSubmit">确认</el-button>
        <el-button
          @click="
              () => {
                  this.$emit('closeAdd')
              }
          "
        >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  queryExistTowerApi,
  addTowerApi,
  editTowerApi
} from '@/api/base/proj'
export default {
  name: 'towerAdd',
  props: {
    sendAddData: {
      type: Object,
      default: null
    }
  },
  methods: {
    /** 校验经纬 */
    validateLonLat(rule, value, callback) {
      if(!this.lonLatReg.test(value)) {
        callback(new Error('经纬度格式不正确'))
      } else {
        callback()
      }
    },
    /** 查询杆塔 */
    async getRanges() {
      let towerRes = await queryExistTowerApi()
      this.towerRange = towerRes.data.map(item => {
        return {
          label: item.gtName,
          value: item.gtName,
          lon: item.lon,
          lat: item.lat
        }
      })
    },
    /** 杆塔改变 */
    towerChange(e) {
      this.towerRange.forEach(item => {
        if(e === item.label) {
          this.towerAddParams.lon = item.lon
          this.towerAddParams.lat = item.lat
        }
      })
    },
    /** 确认按钮 */
    onSubmit() {
      this.$refs.towerAddParamsRef.validate(valid => {
        if (valid) {
          console.log('校验通过', this.towerAddParams, this.sendAddData)
          // 1. 表单校验通过后调后台 Api
          if(this.subSort === 1) {
            addTowerApi(this.towerAddParams).then(res => {
              this.$modal.msgSuccess('操作成功')
              // 2. 成功之后通知父组件关闭弹框
              this.$emit('closeAdd', true)
            }).catch(err => {
              console.log(err)
            })
          } else if(this.subSort === 2) {
            editTowerApi(this.towerAddParams).then(res => {
              this.$modal.msgSuccess('操作成功')
              // 2. 成功之后通知父组件关闭弹框
              this.$emit('closeAdd', true)
            }).catch(err => {
              console.log(err)
            })
          }
        }
      })
    },
  },
  components: {

  },
  created() {
    this.getRanges()
  },
  mounted() {
    Object.assign(this.towerAddParams, this.sendAddData)
    if (this.sendAddData.submitType === 'edit') {
      this.sendAddData.proId = this.sendAddData.id
      this.subSort = 2
    } else {
      this.subSort = 1
    }
    console.log(this.sendAddData, '=======')
  },
  data() {
    return {
      subSort: '', // 提交类型：新增 1 / 修改 2
      towerAddParams: {
        gtName: undefined, //杆塔名称
        lon: undefined, // 经度
        lat: undefined, // 纬度
      },
      // 校验规则
      towerAddParamsRules: {
        gtName: [
          {
            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'
          }
        ],
      },
      // 下拉
      towerRange: [],
      // 经纬正则
      lonLatReg: /^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/
    }
  },
}
</script>
