<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-width="190px">
          <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="9">
              <el-form-item label="驻点类型" prop="type">
                <el-radio-group v-model="addEditForm.type" size="medium">
                  <el-radio v-for="item in resourceList" :key="item.value"
                            :label="item.value"
                            :value="item.value"
                            border
                  >{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <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="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="场所类型" prop="classType">
                <el-select v-model="addEditForm.classType" placeholder="场所类型" style="width: 100%">
                  <el-option v-for="(item, index) in getDictionaryByCode(
                    'jyd-cslx'
                  )" :key="index" :label="item.name" :value="Number(item.value)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所属救援队伍" prop="teamId">
                <el-select v-model="addEditForm.teamId" filterable placeholder="请选择巡查救援队伍" style="width: 100%"
                           @change="teamIdChange">
                  <el-option v-for="item in teamOptions" :key="item.value" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item class="stake-mark" label="点位桩号全值">
                <div class="pegVal-text1">K</div>
                <el-input v-model="addEditForm.peg" clearable placeholder="点位桩号" type="number"></el-input>
                <div class="pegVal-text2">+</div>
                <el-input v-model="addEditForm.pegAdd" clearable placeholder="点位桩号附加" type="number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所属监控中心电话" prop="monitorTel">
                <el-input v-model="addEditForm.monitorTel" clearable placeholder="所属监控中心电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所管辖区交通综合执法大队" prop="managementD">
                <el-input v-model="addEditForm.managementD" clearable placeholder="所管辖区交通综合执法大队"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所管辖区交通综合执法支队" prop="managementZ">
                <el-input v-model="addEditForm.managementZ" clearable placeholder="所管辖区交通综合执法支队"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所管辖区交巡警大队" prop="trafficPoliceD">
                <el-input v-model="addEditForm.trafficPoliceD" clearable placeholder="所管辖区交巡警大队"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="所管辖区交巡警支队" prop="trafficPoliceZ">
                <el-input v-model="addEditForm.trafficPoliceZ" 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="9">
              <el-form-item label="驻点类别" prop="stationType">
                <el-radio-group v-model="addEditForm.stationType" size="medium">
                  <el-radio v-for="item in stationTypeList" :key="item.value"
                            :label="Number(item.value)"
                            :value="Number(item.value)"
                            border
                  >{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">-->
          <!--            <el-col :span="9">-->
          <!--              <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="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="纬度" prop="lng">
                <el-input v-model="addEditForm.lng" clearable placeholder="经度" @blur="updatePoint"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="纬度" prop="lat">
                <el-input v-model="addEditForm.lat" clearable placeholder="纬度" @blur="updatePoint"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <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="9">
              <el-form-item label="负责人" prop="linkName">
                <el-input v-model="addEditForm.linkName" clearable placeholder="负责人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="负责人联系电话" prop="linkTel">
                <el-input v-model="addEditForm.linkTel" clearable placeholder="负责人联系电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="值班电话" prop="dutyTel">
                <el-input v-model="addEditForm.dutyTel" clearable placeholder="值班电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="值班人数" prop="dutyNum">
                <el-input v-model="addEditForm.dutyNum" clearable placeholder="值班人数" type="number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="轮班人数" prop="turnNum">
                <el-input v-model="addEditForm.turnNum" clearable placeholder="轮班人数" type="number"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="9">
              <el-form-item label="救援服务电话" prop="rescusTel">
                <el-input v-model="addEditForm.rescusTel" clearable placeholder="救援服务电话"></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 {getTree, tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/rescueSiteMgmt'
import {getDictionaryByCode} from '@/utils/dictionary'
import {lngAndLatToPie} from '@/utils/pointConversion'
import RoadChoiceDialog from './components/RoadChoiceDialog'
import MineMap from '@/components/MineMap/index.vue'
import {refineRequestBody} from '@/utils/requestWrappers'

import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'

export default {
  name: 'EditAddPage',
  components: {MineMap, RoadChoiceDialog},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      stationTypeList: [
        {value: 1, name: '常驻点'},
        {value: 2, name: '临时驻点'}
      ],
      resourceList: [
        {value: 2, name: '救援驻点'}
      ],
      addEditForm: {
        stationType: 1,
        type: 2,
        resource: '1',
        lng: '',
        lat: '',
        direction: '1',
        roadName: ''
      },
      addEditRules: {
        name: [
          {
            required: true,
            message: '救援点名称不能为空',
            trigger: ['change', 'blur']
          }
        ],

        roadId: [
          {
            required: true,
            message: '所属路段不能为空',
            trigger: ['change', 'blur']
          }
        ],
        teamId: [
          {
            required: true,
            message: '所属巡查救援队伍不能为空',
            trigger: ['change', 'blur']
          }
        ],
        type: [
          {
            required: true,
            message: '场所类型',
            trigger: ['change', 'blur']
          }
        ],
        peg: [
          {
            required: true,
            message: '点位桩号',
            trigger: ['change', 'blur']
          }
        ],
        pegAdd: [
          {
            required: true,
            message: '点位桩号附加',
            trigger: ['change', 'blur']
          }
        ],
        pegVal: [
          {
            required: true,
            message: '点位桩号全值不能为空',
            trigger: ['change', 'blur']
          }
        ]
        // rescusTel: [
        //   {
        //     required: true,
        //     message: '救援服务电话不能为空',
        //     trigger: ['change', 'blur']
        //   },
        //   {
        //     pattern: /\d{3}-\d{8}|\d{4}-\d{7}/, message: '救援服务电话输入格式有误', trigger: 'blur'
        //   }
        // ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      whetherToCancel: false,
      roadChoiceDialog: false, // 是否展示选择路段弹层
      routerData: [], // 路线数据
      pubSub: null,
      // mapLoading: true, // 地图加载loading
      map: null,
      mapDefaultOptions: {
        center: [106.5507, 29.5647] /*地图中心点*/,
        zoom: 9 /*地图默认缩放等级*/
      },
      markers: [],
      teamTreeData: [], // 救援队伍组织树
      monitorTreeData: [], // 监控中心组织树
      roadOptions: [],
      teamOptions: []
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
    this.getOrgTreeData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, 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)
      } else {

      }
      if (data.clearForm) {
        this.resetFormData(data) // 新增时重置表单
      } else if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
      this.getRoadData()
    })
  },
  methods: {
    // 重置表单数据
    resetFormData(treeData) {
      this.addEditForm = {
        stationType: 1,
        type: 2,
        lng: '',
        lat: '',
        direction: '1',
        roadName: treeData.roadName || '',
        roadId: treeData.catalogId || '',
        roadFullId: treeData.path || '',
        peg: '',
        pegAdd: ''
        // 其他字段初始值...
      }
      this.id = '' // 清空ID
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate() // 清除表单验证状态
      })
    },
    getDictionaryByCode,
    // 根据经纬度转桩号全值
    toPile() {
      let data = {
        lon: 106.34042812546483,
        lat: 29.66523822261111,
        pointType: '02',
        routeCode: 'G93',
        upDown: '2'
      }
      lngAndLatToPie(data)
    },
    //获取所在路段列表数据
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map(item => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      if (!this.id) {
        // this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
        this.roadChange(this.roadOptions[0].id)
      }
    },
    // 通过路段信息获取巡查救援队伍信息
    async getTeamData(value) {
      const {rows = []} = await teamData(refineRequestBody({
        querys: [{operation: 'IN', property: 'r.id_', value}]
      }), 'addEdit')
      this.teamOptions = rows
    },

    roadChange(value) {
      if (this.addEditForm.teamId) {
        this.$set(this.addEditForm, 'teamId', '')
      }
      if (this.addEditForm.teamName) {
        this.$set(this.addEditForm, 'teamName', '')
      }
      this.getTeamData(value)
    },

    // 所属救援队伍选择
    teamIdChange(value) {
      let teamInfo = this.teamOptions.find(item => item.id === value)
      this.addEditForm.teamName = teamInfo.name
    },
    // 获取公司树
    async getOrgTreeData() {
      let data = await getTree()
      this.teamTreeData = data
      this.monitorTreeData = data
    },

    // 自定义标记点
    customTagPoints(lnglat = []) {
      this.markers[this.markers.length - 1]?.remove()
      // 自定义点标记的内部DOM元素
      let el = document.createElement('div')
      el.className = 'marker-tip'
      // Marker构造函数接收两个参数，一个为自定义的DOM元素，一个是Object参数，其中包括偏移量等
      let marker = new this.$refs.mineMap.mineMap.Marker(el, {
        draggable: true,
        anchor: 'center',
        offset: [0, 0] // offset参数为标注点相对于其左上角偏移像素大小

      })
        // 调用setLngLat方法指定Marker的坐标位置
        .setLngLat(lnglat)
        .addTo(this.$refs.mineMap.map)
        .on('dragend', ({target}) => {
          const {lng, lat} = target.getLngLat()
          this.addEditForm = {...this.addEditForm, lng, lat}
        })
      this.$refs.mineMap.map.setCenter(lnglat)
      this.markers.push(marker)
    },
    // 修改经纬度更新地图标点
    updatePoint(e) {
      let {lng = '', lat = ''} = this.addEditForm
      if (lng && lat) {
        this.customTagPoints([lng, lat])
      }
    },
    // 打开页面执行
    openPage() {
      this.toPile()
      // this.$refs.mineMap?.map?.resize()
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 关闭页面执行
    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) {
      const response = await tableDetail(id)
      this.addEditForm = {
        ...response,
        roadName: response.roadName || this.addEditForm.roadName // 如果接口返回的 orgName 为空，使用当前表单的 orgName
      }

    },

    // 保存
    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.peg + '+' + data.peg
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            let {state, message, value} = 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.resetFormData({
                roadName: this.addEditForm.roadName,
                catalogId: this.addEditForm.roadId,
                path: this.addEditForm.roadFullId
              })
              this.changePage(
                'TablePage',
                this.id ? 'edit' : 'add'
              )
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 改变页面
    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-new-content {
  width: 100%;
  display: flex;
  height: 0;
  flex: 1;
  column-gap: 20px;

  .form-content {
    flex: 2;
  }

  .map-content {
    flex: 3;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: $--system-border-color3 0.5px 0.5px 5px 1px;

    ::v-deep.marker-tip {
      position: relative;
      background-image: url('~@/assets/img/patrolAndRescue/inspection-points-icon.png');
      background-size: cover;
      width: 48px !important;
      height: 48px !important;
      z-index: 999;

      &::after {
        position: absolute;
        content: '救援点位置';
        left: 100%;
        top: 8px;
        width: 80px;
        height: 25px;
        font-size: 16px;
        color: $--color-warning;
        text-align: center;
        line-height: 25px;
        padding: 5px 10px;
        background-color: rgba(darken($--color-warning, 70%), 0.9);
        border-radius: 3px;
        box-shadow: 0 0 6px rgba($--color-warning, 0.8);
        border: none;
        z-index: 999;
      }
    }
  }

  .stake-mark {
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;

      .pegVal-text2,
      .pegVal-text1 {
        padding-right: 10px;
        font-size: 16px;
        width: fit-content;
      }

      .pegVal-text2 {
        padding-left: 10px;
        font-size: 24px;
      }
    }
  }
}
</style>

<style lang="scss"></style>
