<template>
  <div class="edit-add-detail">
    <div class="edit-add-detail-new-content">
      <div
        v-loading="false"
        class="form-content"
        element-loading-background="rgba(10 ,38 ,61, 0.95)"
        element-loading-text="数据加载中..."
      >
        <el-form
          ref="addEditForm"
          :model="addEditForm"
          :rules="addEditRules"
          label-position="top"
          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">
            <el-col :span="8">
              <el-form-item label="报案电话" prop="eventTel">
                <el-input
                  v-model="addEditForm.eventTel"
                  clearable
                  placeholder="报案电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事件来源">
                <el-select
                  v-model="addEditForm.eventSrc"
                  clearable
                  placeholder="事件来源"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('sjly')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属路段" prop="roadId">
                <el-input
                  v-model="addEditForm.road.roadName"
                  class="el-click-input"
                  clearable
                  placeholder="点击选所在路段"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('roadChoice')"
                >
                  <template v-if="addEditForm.road.roadCode" v-slot:prepend>
                    {{ addEditForm.road.roadCode }}
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item class="stake-mark" label="事件开始点位桩号全值">
                <div class="pegVal-text1">K</div>
                <el-input v-model="addEditForm.startPeg" clearable
                          oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
                <div class="pegVal-text2">+</div>
                <el-input
                  v-model="addEditForm.startPegAdd"
                  clearable
                  oninput="value=value.replace(/[^0-9]/g,'')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="stake-mark" label="事件结束点位桩号全值">
                <div class="pegVal-text1">K</div>
                <el-input v-model="addEditForm.endPeg" clearable
                          oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
                <div class="pegVal-text2">+</div>
                <el-input v-model="addEditForm.endPegAdd" clearable
                          oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
              </el-form-item>
            </el-col>
            <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, index) in getDictionaryByCode('xsfx')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="开始巡查站" prop="startPatrolId">
                <el-input
                  v-model="addEditForm.startPatrolId"
                  clearable
                  placeholder="开始巡查站"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束巡查站" prop="endPatrolId">
                <el-input
                  v-model="addEditForm.endPatrolId"
                  clearable
                  placeholder="结束巡查站"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事件类型" prop="eventType">
                <el-select
                  v-model="addEditForm.eventType"
                  clearable
                  placeholder="事件类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('sjlx')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="事件等级" prop="eventLevel">
                <el-select
                  v-model="addEditForm.eventLevel"
                  clearable
                  placeholder="事件等级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in eventGradeOptions"
                    :key="index"
                    :label="item.label"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="拥堵里程" prop="blockLength">
                <el-input
                  v-model="addEditForm.blockLength"
                  class="number-input"
                  placeholder="请输入内容"
                  type="number"
                >
                  <template slot="append">KM</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="滞留人员数量" prop="holdupUserNum">
                <el-input
                  v-model="addEditForm.holdupUserNum"
                  clearable
                  placeholder="滞留人员数量"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="滞留车辆数量" prop="holdupCarNum">
                <el-input
                  v-model="addEditForm.holdupCarNum"
                  clearable
                  placeholder="滞留车辆数量"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受伤人员数量" prop="hurtUserNum">
                <el-input
                  v-model="addEditForm.hurtUserNum"
                  clearable
                  placeholder="受伤人员数量"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="死亡人数" prop="deadUserNum">
                <el-input
                  v-model="addEditForm.deadUserNum"
                  clearable
                  placeholder="死亡人数"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="损坏车辆数量" prop="brokenCarNum">
                <el-input
                  v-model="addEditForm.brokenCarNum"
                  clearable
                  placeholder="损坏车辆数量"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="肇事方" prop="cause">
                <el-input
                  v-model="addEditForm.cause"
                  clearable
                  placeholder="肇事方"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="肇事车辆" prop="causeCar">
                <el-input
                  v-model="addEditForm.trafficPoliceZ"
                  clearable
                  placeholder="肇事车辆"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="路产损失" prop="loss">
                <el-input
                  v-model="addEditForm.loss"
                  clearable
                  placeholder="路产损失"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经度" prop="lng">
                <el-input
                  v-model="addEditForm.lng"
                  clearable
                  placeholder="经度"
                  @blur="updatePoint"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <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>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="处置队伍" prop="teamId">
                <el-cascader
                  ref="addEditFormCascader"
                  v-model="addEditForm.teamId"
                  :options="teamTreeData"
                  :props="{
                    emitPath: false,
                    checkStrictly: true,
                    label: 'name',
                    value: 'id',
                  }"
                  :show-all-levels="false"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="teamIdChange(addEditForm)"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事件发生时间" prop="eventTime">
                <el-date-picker
                  v-model="addEditForm.eventTime"
                  default-time="12:00:00"
                  placeholder="选择日期时间"
                  style="width: 100%"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div
        v-loading="mapLoading"
        class="map-content"
        element-loading-background="rgba(11, 23, 49, 1)"
        element-loading-text="地图加载中.."
      >
        <MineMap
          ref="mineMap"
          :defaultOptions="mapDefaultOptions"
          :markers="markers"
          custom-class="mine-map"
          @onLoad="mapLoad"
        />
      </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"
      @confirm="handleRoadSelect"
    />
    <!-- 救援单信息 -->
    <RescueInfoDialog
      ref="rescueInfoDialog"
      @offPage="offPage"
    ></RescueInfoDialog>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/commandDispatch/eventInquiry'
import {getDictionaryByCode} from '@/utils/dictionary'
import RoadChoiceDialog from './components/RoadChoiceDialog'
import RescueInfoDialog from './components/RescueInfoDialog'
import MineMap from '@/components/MineMap/index.vue'
import {orgTree} from '@/api/systemInterface'

export default {
  name: 'EditAddPage',
  components: {MineMap, RoadChoiceDialog, RescueInfoDialog},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      formLoading: true,
      addEditForm: {
        lng: '',
        lat: '',
        road: {}
      },
      addEditRules: {
        eventTel: [
          {
            required: true,
            message: '报案电话不能为空',
            trigger: ['change', 'blur']
          }
        ],
        eventType: [
          {
            required: true,
            message: '请选择事件类型',
            trigger: ['change']
          }
        ],
        roadId: [
          {
            required: true,
            message: '路段信息不能为空',
            trigger: ['change']
          }
        ],
        teamId: [
          {
            required: true,
            message: '处置队伍不能为空',
            trigger: ['change']
          }
        ],
        eventTime: [
          {
            required: true,
            message: '事件发生时间不能为空',
            trigger: ['change']
          }
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      roadChoiceDialog: false, // 是否展示选择路段弹层
      routerData: [], // 路线数据
      pubSub: null,
      mapLoading: true, // 地图加载loading
      map: null,
      mapDefaultOptions: {
        center: [106.5507, 29.5647] /*地图中心点*/,
        zoom: 9 /*地图默认缩放等级*/
      },
      markers: [],
      teamTreeData: [], // 救援队伍组织树
      eventGradeOptions: [
        //事件等级
        {label: '1级', value: 1},
        {label: '2级', value: 2},
        {label: '3级', value: 3},
        {label: '4级', value: 4}
      ]
    }
  },
  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.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    offPage() {
      this.changePage('TablePage', 'edit')
    },
    handleAppoint() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.$refs.rescueInfoDialog.open(this.addEditForm)
        }
      })
    },
    getDictionaryByCode,
    // 获取公司树
    async getOrgTreeData() {
      let data = await orgTree()
      this.teamTreeData = data
    },
    // 队伍选择
    teamIdChange(type) {
      this[type].teamFullId =
        this.$refs[`${type}Cascader`]?.getCheckedNodes()[0]?.data?.path || ''
      this[type].teamId =
        this.$refs[`${type}Cascader`]?.getCheckedNodes()[0]?.value || ''
    },
    // 地图挂载后
    mapLoad(map) {
      this.mapLoading = false
      map.on('click', ({lngLat}) => {
        let {lng, lat} = lngLat
        this.addEditForm = {...this.addEditForm, lng, lat}
        this.customTagPoints([lng, lat])
      })
    },
    // 自定义标记点
    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
      this.customTagPoints([lng, lat])
    },
    // 打开页面执行
    openPage() {
      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()
      })
    },
    handleRoadSelect(road) {
      this.$set(this.addEditForm, 'roadId', road.roadId)
    },
    // 获取详情
    async getDetail(id) {
      try {
        this.addEditForm = await tableDetail(id)
        const {
          roadCode = '',
          roadId = '',
          roadName = '',
          pegSVal = '',
          pegEVal = '',
          lng = '',
          lat = ''
        } = this.addEditForm
        this.addEditForm.road = {
          roadCode,
          roadId,
          roadName
        }
        if (pegSVal) {
          let startPegArr = pegSVal.split('+')
          this.addEditForm.startPeg = startPegArr[0].slice(1)
          this.addEditForm.startPegAdd = startPegArr[1]
        }
        if (pegEVal) {
          let endPegArr = pegEVal.split('+')
          this.addEditForm.endPeg = endPegArr[0].slice(1)
          this.addEditForm.endPegAdd = endPegArr[1]
        }
        if (lng && lat) {
          this.$nextTick((_) => {
            this.customTagPoints([lng, lat])
            this.$refs.mineMap.map.setCenter([lng, lat])
            this.$refs.mineMap.map.panTo([lng, lat], {
              duration: 6000, // 动画过渡时间
              zoom: 14 // 新的缩放级别
            })
          })
        }
      } finally {
        this.formLoading = false
      }
    },

    // 保存
    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.pegSVal =
            'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          data.pegEVal =
            'k' + (data.endPeg || '') + '+' + (data.endPegAdd || '')
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            let {state, message, value} = await myInterFace({
              ...data,
              ...data.road
            })
            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`保存成功`)
              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";

.number-input {
  ::v-deep .el-input__inner {
    font-size: 14px;
  }
}

.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>
