<template>
  <div class="edit-add-detail">
    <div class="edit-add-detail-new-content">
      <div class="form-content">
        <el-form
          ref="addEditForm"
          :model="addEditForm"
          :rules="addEditRules"
          label-position="left"
          label-suffix="："
          label-width="100px"
        >
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">巡查点位信息</div>
            </div>
          </div>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="8">
              <el-form-item label="所属路段" prop="roadName">
                <el-input v-model="addEditForm.roadName" :disabled="true" clearable
                          readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="点位名称" prop="name">
                <el-input
                  v-model="addEditForm.name"
                  clearable
                  placeholder="请输入点位名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="点位类型" prop="type">
                <el-select
                  v-model="addEditForm.type"
                  placeholder="请选择点位类型"
                  style="width: 100%"
                  @change="typeChange"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('xcdwlx')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="点位级别" prop="pointLevel">
                <el-select
                  v-model="addEditForm.pointLevel"
                  placeholder="请选择点位级别"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('dwjb')"
                    :key="Number(item.value)"
                    :label="item.name"
                    :value="Number(item.value)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="巡检周期" prop="inspectionCycle">
                <el-select
                  v-model="addEditForm.inspectionCycle"
                  placeholder="请选择巡检周期"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('xjzq')"
                    :key="Number(item.value)"
                    :label="item.name"
                    :value="Number(item.value)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="内容" prop="content">
                <el-select
                  v-model="addEditForm.content"
                  placeholder="请选择内容"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in contentOpt"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="点位类别" prop="category">
                <el-select
                  v-model="addEditForm.category"
                  placeholder="请选择点位类别"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('xcdwlb')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="方向" prop="direction">
                <el-select
                  v-model="addEditForm.direction"
                  clearable
                  placeholder="请选择方向"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('xsfx')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="点位桩号" prop="pegVal">
                <el-col :span="2" class="line" style="text-align: center">
                  <span class="peg-text-1">K</span>
                </el-col>
                <el-col :span="10" style="padding: 0; text-align: center">
                  <el-input
                    v-model="addEditForm.pegAdd"
                    placeholder="请输入点位桩号"
                    type="number"
                  />
                </el-col>
                <el-col
                  :span="2"
                  class="line"
                  style="padding: 0; text-align: center"
                >
                  <span class="peg-text-2">+</span>
                </el-col>
                <el-col :span="10" style="padding: 0; text-align: center">
                  <el-input
                    v-model="addEditForm.peg"
                    placeholder="请输入点位桩号附加"
                    type="number"
                  />
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="经度" prop="lng">
                <el-input
                  v-model="addEditForm.lng"
                  clearable
                  placeholder="请输入经度"
                  type="number"
                  @blur="lngLatBlur"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="纬度" prop="lat">
                <el-input
                  v-model="addEditForm.lat"
                  clearable
                  placeholder="请输入纬度"
                  type="number"
                  @blur="lngLatBlur"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <!--  所在路段选择弹层  -->
    <!--    <RoadChoiceDialog-->
    <!--      :is-show.sync="roadChoiceDialog"-->
    <!--      :selected-content.sync="addEditForm.road"-->
    <!--    />-->
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/inspectionPointMgmt'
import {getCascadeDictByCodeEvent, getDictionaryByCode} from '@/utils/dictionary'
import MineMap from '@/components/MineMap/index.vue'
import RoadChoiceDialog from './components/RoadChoiceDialog'

export default {
  name: 'EditAddPage',
  components: {RoadChoiceDialog, MineMap},
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    const validatePegVal = (_, __, callback) => {
      const {pegAdd, peg} = this.addEditForm

      if (pegAdd && !peg) {
        callback(new Error('请输入点位桩号附加'))
      } else if (!pegAdd && peg) {
        callback(new Error('请输入点位桩号'))
      } else {
        callback()
      }
    }

    const validateLng = (_, value, callback) => {
      if (Number.isFinite(value)) {
        if (!(value >= -180 && value <= 180)) {
          callback(new Error('请输入合法的经度值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    const validateLat = (_, value, callback) => {
      if (Number.isFinite(value)) {
        if (!(value >= -90 && value <= 90)) {
          callback(new Error('请输入合法的纬度值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      addEditForm: {
        category: '1',
        type: '1',
        direction: '1',
        content: '',
        road: [],
        roadName: '',
        pointLevel: 1,
        inspectionCycle: 1
      },
      addEditRules: {
        name: [
          {
            required: true,
            message: '点位名称不能为空',
            trigger: ['change', 'blur']
          }
        ],
        category: [
          {required: true, message: '点位类别不能为空', trigger: 'change'}
        ],
        type: [
          {required: true, message: '点位类型不能为空', trigger: 'change'}
        ],
        pointLevel: [
          {required: true, message: '点位级别不能为空', trigger: 'change'}
        ],
        inspectionCycle: [
          {required: true, message: '巡检周期不能为空', trigger: 'change'}
        ],
        content: [
          {required: true, message: '具体内容不能为空', trigger: 'change'}
        ],
        road: [
          {required: true, message: '路段不能为空', trigger: 'change'}
        ],
        direction: [
          {required: true, message: '行驶方向不能为空', trigger: 'change'}
        ],
        pegVal: [
          {required: true, validator: validatePegVal, message: '点位桩号不能为空', trigger: 'blur'}
        ],
        // pegVal: [{required: false, validator: validatePegVal, trigger: 'blur'}],
        lng: [
          {
            required: true,
            validator: validateLng,
            trigger: ['change', 'blur']
          }
        ],
        lat: [
          {
            required: true,
            validator: validateLat,
            trigger: ['change', 'blur']
          }
        ]
      },
      currentDataDel: [],
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      roadOpt: [],
      roadChoiceDialog: false, // 是否展示选择路段弹层
      // mapLoading: true, // 地图加载loading
      mapDefaultOptions: {
        center: [106.5507, 29.5647] /*地图中心点*/,
        zoom: 6.5 /*地图默认缩放等级*/
      },
      markers: [] // 地图点位数组
    }
  },
  computed: {
    contentOpt() {
      // 获取级联字典
      return getCascadeDictByCodeEvent('xcdwlx', this.addEditForm.type)
    }
  },
  watch: {
    componentName(newVal) {
      if (newVal === this.$options.name) {
        this.openPage()
      } else {
        this.closePage()
      }
    }
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      console.log(data, '//////')
      if (data.roadName !== '') {
        this.addEditForm.roadName = data?.roadName || ''
        this.addEditForm.roadId = data?.catalogId || ''
        this.addEditForm.roadFullId = data?.path || ''
      }
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    getDictionaryByCode,


    // 打开页面执行
    openPage() {
      this.typeChange()
      this.$refs.mineMap?.map?.resize() // 根据地图的 container 元素的尺寸调整地图的大小。
    },

    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules
      })

      // this.$refs.mineMap?.resetMap((_) => (this.mapLoading = false)) // 重置地图

      this.$nextTick((_) => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

    // 获取详情
    // async getDetail(id) {
    //   let {
    //     lng,
    //     lat,
    //     roadId = '',
    //     roadCode = '',
    //     roadName = '',
    //     name = '',
    //     content = '',
    //     ...addEditForm
    //   } = await tableDetail(id)
    //
    //   // 创建点位并聚焦点位
    //   if (Number.isFinite(lng) && Number.isFinite(lat)) {
    //     this.$nextTick((_) => {
    //       this.customTagPoints([lng, lat], name)
    //       this.$refs.mineMap.map.setCenter([lng, lat])
    //       this.$refs.mineMap.map.flyTo({
    //         center: [lng, lat],
    //         duration: 5000, // 动画过渡时间
    //         zoom: 16 // 新的缩放级别
    //       })
    //     })
    //   }
    //
    //   const oldContent = content // 保持详情原始content内容，避免因表单赋值后触发typeChange事件而丢失content的值
    //
    //   this.addEditForm = {
    //     ...addEditForm,
    //     name,
    //     lng,
    //     lat,
    //     road: {roadId, roadCode, roadName}
    //   }
    //   this.addEditForm.content = oldContent
    // },

    async getDetail(id) {
      const response = await tableDetail(id)
      this.addEditForm = {
        ...response,
        roadName: response.roadName || this.addEditForm.roadName // 如果接口返回的 orgName 为空，使用当前表单的 orgName
      }
    },
    // 点位类型发生变化
    typeChange() {
      // 当表单中点位类型发生改变的时候，赋值内容字典中的第一项字典值给表单中内容字段
      this.addEditForm.content = this.contentOpt[0]?.value || ''
    },

    // 经度维度输入值改变
    lngLatBlur() {
      // const {lng, lat, name} = this.addEditForm
      // if (!(lng && lat)) return
      // let verified = true
      // this.$refs.addEditForm.validateField(['lng', 'lat'], (errorMessage) => {
      //   if (errorMessage) verified = false
      // })
      // verified && this.customTagPoints([lng, lat], name)
    },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          let data = JSON.parse(JSON.stringify(this.addEditForm))
          data.pegVal = 'k' + data.pegAdd + '+' + data.peg
          const myInterFace = this.id ? tableEdit : tableAdd

          // const {
          //   pegAdd = '',
          //   peg = '',
          //   road: {roadId = '', roadCode = '', roadName = ''} = {},
          //   ...addEditForm
          // } = this.addEditForm

          try {
            let {state, message} = await myInterFace({
              ...data, ...data.road,
              type: this.addEditForm.type // 传递队伍类型的 value})
            })

            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`巡查点位${message}成功`)
              PubSub.publish('TablePage', {type: 'add'})
              // 手动将 orgName 添加到返回的数据中
              data.roadName = this.addEditForm.roadName
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, (_) => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';

.edit-add-detail {
  .edit-add-detail-new-content {
    width: 100%;
    display: flex;
    height: 0;
    flex: 1;
    column-gap: 20px;

    .form-content {
      flex: 1;

      .peg-text-1 {
        font-size: 14px;
      }

      .peg-text-2 {
        font-size: 24px;
      }
    }

    .map-content {
      flex: 2.5;
      border-radius: 10px;
      overflow: hidden;
      border: 1px solid darken($--system-border-color2, 10%);

      /* 自定义标记样式 */
      ::v-deep .mine-map {
        /* 自定义标记样式 */
        .custom-marker {
          display: flex;
          align-items: center;
          cursor: pointer;

          .custom-icon {
            width: 48px;
            height: 48px;
            background-size: cover;
            background-image: url('~@/assets/img/patrolAndRescue/inspection-points-icon.png');
            /* 替换为你的图标 URL */
          }

          .custom-label {
            background-color: rgba(darken($--color-warning, 70%), 0.9);
            padding: 6px 8px;
            border-radius: 3px;
            font-size: 16px;
            color: $--color-warning;
            box-shadow: 0 0 6px rgba($--color-warning, 0.8);
          }
        }
      }
    }
  }
}
</style>
