<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="6">
              <el-form-item label="报案电话" prop="eventTel">
                <el-input
                  v-model="addEditForm.eventTel"
                  clearable
                  placeholder="报案电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属路段" prop="roadId">
                <el-select
                  v-model="addEditForm.roadId"
                  clearable
                  filterable
                  placeholder="请选择所属路段"
                  style="width: 100%"
                  @change="roadChange"
                >
                  <el-option
                    v-for="item in roadOptions"
                    :key="item.id"
                    :label="item.roadName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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-col :span="6">
              <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-row :gutter="24">
            <el-col :span="6">
              <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="6">
              <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="6">
              <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-col :span="6">
              <el-form-item label="开始站" prop="startPatrolId">
                <el-select
                  v-model="addEditForm.startPatrolId"
                  filterable
                  placeholder="请选择开始站"
                  style="width: 100%"
                  @change="siteChange($event, 'startPatrol')"
                >
                  <el-option
                    v-for="item in alongRouteInfoData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="结束站" prop="endPatrolId">
                <!-- <el-input clearable v-model="addEditForm.endPatrolId" placeholder="结束站"></el-input> -->
                <el-select
                  v-model="addEditForm.endPatrolId"
                  filterable
                  placeholder="请选择结束站"
                  style="width: 100%"
                  @change="siteChange($event, 'endPatrol')"
                >
                  <el-option
                    v-for="item in alongRouteInfoData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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,'')"
                  type="number"
                ></el-input>
                <div class="pegVal-text2">+</div>
                <el-input
                  v-model="addEditForm.startPegAdd"
                  clearable
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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="6">
              <el-form-item label="经度" prop="lng">
                <el-input clearable v-model="addEditForm.lng" @blur="updatePoint" placeholder="经度"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <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-row>
          <el-row :gutter="24">
            <!-- <el-col :span="6">
              <el-form-item label="纬度" prop="lat">
                <el-input clearable v-model="addEditForm.lat" @blur="updatePoint" placeholder="纬度"></el-input>
              </el-form-item>
            </el-col> -->

            <el-col :span="6">
              <el-form-item label="滞留人员数量" prop="holdupUserNum">
                <el-input
                  v-model="addEditForm.holdupUserNum"
                  clearable
                  placeholder="滞留人员数量"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="滞留车辆数量" prop="holdupCarNum">
                <el-input
                  v-model="addEditForm.holdupCarNum"
                  clearable
                  placeholder="滞留车辆数量"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="受伤人员数量" prop="hurtUserNum">
                <el-input
                  v-model="addEditForm.hurtUserNum"
                  clearable
                  placeholder="受伤人员数量"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="死亡人数" prop="deadUserNum">
                <el-input
                  v-model="addEditForm.deadUserNum"
                  clearable
                  placeholder="死亡人数"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="损坏车辆数量" prop="brokenCarNum">
                <el-input
                  v-model="addEditForm.brokenCarNum"
                  clearable
                  placeholder="损坏车辆数量"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="肇事方" prop="cause">
                <el-input
                  v-model="addEditForm.cause"
                  clearable
                  placeholder="肇事方"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="肇事车辆" prop="causeCar">
                <el-input
                  v-model="addEditForm.trafficPoliceZ"
                  clearable
                  placeholder="肇事车辆"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="路产损失" prop="loss">
                <el-input
                  v-model="addEditForm.loss"
                  clearable
                  disabled
                  placeholder="路产损失"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="事件概述">
                <el-input
                  v-model="addEditForm.memo"
                  :autosize="{minRows: 2, maxRows: 4}"
                  placeholder="请输入"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <!-- <el-col :span="6">
              <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' }" clearable filterable
                  style="width: 100%" @change="teamIdChange(addEditForm)" :show-all-levels="false"></el-cascader>
              </el-form-item>
            </el-col> -->
          </el-row>
        </el-form>
      </div>
      <!-- <div v-loading="mapLoading" element-loading-text="地图加载中.." element-loading-background="rgba(11, 23, 49, 1)"
        class="map-content">
        <MineMap ref="mineMap" :defaultOptions="mapDefaultOptions" custom-class="mine-map" :markers="markers"
          @onLoad="mapLoad" />
      </div> -->
    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button
        :loading="saveLoading"
        type="primary"
        @click="showAppointDialog('appoint')"
      >
        委派
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
    <!--  所在路段选择弹层  -->
    <AppointDialog
      :eventInfo="addEditForm"
      :is-show.sync="appointDialog"
      :roadOptions="roadOptions"
      :teamOptions="teamOptions"
      @offPage="offPage"
    />
  </div>
</template>

<script>
import moment from 'moment'
import PubSub from 'pubsub-js'
import {refineRequestBody} from '@/utils/requestWrappers'
import {tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/commandDispatch/eventManagement'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import RoadChoiceDialog from './components/RoadChoiceDialog'
import AppointDialog from './components/AppointDialog'
import MineMap from '@/components/MineMap/index.vue'
import {orgTree} from '@/api/systemInterface'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as alongRouteInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'

export default {
  name: 'EditAddPage',
  components: {MineMap, RoadChoiceDialog, AppointDialog},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      formLoading: true,
      appointDialog: false,
      addEditForm: {
        lng: '',
        lat: '',
        eventType: '1',
        eventTime: new Date()
      },
      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}
      ],
      tableData: [],
      roadOptions: [],
      alongRouteInfoData: [],
      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.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
    this.getRoadOptions()
  },
  methods: {
    dictionaryEscape,
    siteChange(e, type) {
      let siteInfo = this.alongRouteInfoData.find((item) => item.id === e)
      this.addEditForm[`${type}Name`] = siteInfo.name
    },
    sendRescueInfo(data) {
      // this.changePage('TablePage', 'edit')
      console.log(data)
      this.tableData.push(data)
    },
    getDictionaryByCode,

    // 路段数据查询
    async getRoadOptions() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map((item) => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      console.log(!this.id)
      if (!this.id) {
        this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
        this.roadChange(this.roadOptions[0].id)
      }
    },

    // 路段选择变化
    async roadChange(value) {
      this.getTeamData(value)
      // 通过路段信息获取沿线设备信息
      this.getAlongRouteInfo(value, (data) => {
        const {startPatrolId, endPatrolId} = this.addEditForm

        /*
         * 巡检开始，结束站
         * */
        if (startPatrolId) {
          if (!data.some((i) => i.id === startPatrolId)) {
            this.addEditForm.startPatrolId = ''
            setTimeout((_) => this.$message.warning('请重新选择巡检开始站..'))
          }
        }

        if (endPatrolId) {
          if (!data.some((i) => i.id === endPatrolId)) {
            this.addEditForm.endPatrolId = ''
            setTimeout((_) => this.$message.warning('请重新选择巡检结束站..'))
          }
        }
      })
    },
    // 通过路段信息获取沿线设备信息
    async getAlongRouteInfo(value, callback) {
      const _wipeData = () => {
        this.alongRouteInfoData = []
        callback && callback(this.alongRouteInfoData)
      }

      try {
        // 获取沿线设施
        const {rows = []} = await alongRouteInfoInter(
          refineRequestBody({
            querys: [{operation: 'IN', property: 'road_segment_id_', value}]
          }),
          'addEdit'
        )

        callback && callback(rows)
        this.alongRouteInfoData = rows
      } catch (error) {
        // 不为请求过快结束的情况下，重置
        if (error.message !== 'canceled') _wipeData()
      }
    },

    // 通过路段信息获取巡查救援队伍信息
    async getTeamData(value) {
      const {rows = []} = await teamData(
        refineRequestBody({
          querys: [
            {operation: 'IN', property: 'r.id_', value},
            {operation: 'EQUAL', property: 't.type_', value: '1'}
          ]
        }),
        'addEdit'
      )
      this.teamOptions = rows
    },

    // 获取公司树
    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.getRoadOptions()
      // if (!this.teamTreeData.length) this.getOrgTreeData()
      // this.$refs.mineMap?.map?.resize()
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    showAppointDialog() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.appointDialog = true
        }
      })
    },
    offPage() {
      this.changePage('TablePage', 'edit')
    },
    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules, roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules,
        roadOptions
      })
      // this.$refs.mineMap?.resetMap(_ => this.mapLoading = false) // 重置地图
      this.$nextTick((_) => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      try {
        this.addEditForm = await tableDetail(id)
        const {roadId = '', pegSVal = '', pegEVal = ''} = this.addEditForm
        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]
        }
        this.roadChange(roadId)
      } 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))
          if (data.startPeg && data.startPegAdd) {
            data.pegSVal =
              'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          if (data.endPeg && data.endPegAdd) {
            data.pegEVal =
              'k' + (data.endPeg || '') + '+' + (data.endPegAdd || '')
          }

          data.eventTime = moment(data.eventTime).format('YYYY-MM-DD HH:mm:ss')
          let roadInfo = this.roadOptions.find(
            (item) => item.id === data.roadId
          )
          data.roadName = roadInfo.name
          data.roadCode = roadInfo.code
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            let {state, message, value} = await myInterFace(data)
            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";

.el-icon-plus {
  cursor: pointer;
  display: block;
  height: 100%;
  font-size: 16px !important;
  font-weight: 900;
  color: #43a1ff;
}

.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: 3;
  }

  .map-content {
    flex: 4;
    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>
