<template>
  <div>
    <el-form
      ref="addEditForm"
      :model="addEditForm"
      :rules="rules"
      label-position="top"
      label-suffix="："
      label-width="100px"
    >
      <el-col v-if="type == '1'" :span="24">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item :key="type" class="stake-mark" label="起点桩号" prop="startPeg">
              <div class="pegVal-text1">K</div>
              <el-input
                v-model="addEditForm.startPeg"
                clearable
                oninput="value=value.replace(/[^0-9]/g,'')"
                type="text"
              ></el-input>
              <div class="pegVal-text2">+</div>
              <el-input
                v-model="addEditForm.startPegAdd"
                clearable
                oninput="value=value.replace(/[^0-9]/g,'')"
                type="text"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :key="type" class="stake-mark" label="终点桩号" prop="endPeg">
              <div class="pegVal-text1">K</div>
              <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"
                        type="text"></el-input>
              <div class="pegVal-text2">+</div>
              <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"
                        type="text"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="开始站" prop="startPatrolId">
              <el-select
                v-model="addEditForm.startPatrolId"
                filterable
                placeholder="请选择开始站"
                style="width: 100%"
                @change="numberChange($event, 'startPatrol')"
              >
                <el-option
                  v-for="item in numberStationData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结束站" prop="endPatrolId">
              <el-select
                v-model="addEditForm.endPatrolId"
                filterable
                placeholder="请选择结束站"
                style="width: 100%"
                @change="numberChange($event, 'endPatrol')"
              >
                <el-option
                  v-for="item in numberStationData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
      <el-col v-if="type == '2'" :span="24">
        <el-row :gutter="24" style="padding:0 12px">
          <el-form-item label="" prop="placeDetail">
            <el-checkbox-group
              v-model="addEditForm.swzPlaceDetail"
            >
              <el-checkbox
                v-for="(item, index) in tollStationData"
                :key="index"
                :label="item.name"
              >{{ item.name }}
              </el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <!--        <el-row :gutter="24">-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="起点桩号" prop="startPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPeg"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPegAdd"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="终点桩号" prop="endPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-col>
      <el-col v-if="type == '3'" :span="24">
        <el-row :gutter="24" style="padding:0 12px">
          <el-form-item label="" prop="placeDetail">
            <el-checkbox-group
              v-model="addEditForm.sdPlaceDetail"
              :disabled="disabled"
            >
              <el-checkbox
                v-for="(item, index) in tunnelData"
                :key="index"
                :label="item.name"
              >{{ item.name }}
              </el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <!--        <el-row :gutter="24">-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="起点桩号" prop="startPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPeg"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPegAdd"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="终点桩号" prop="endPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-col>
      <el-col v-if="type == '4'" :span="24">
        <el-row :gutter="24" style="padding:0 12px">
          <el-form-item label="" prop="placeDetail">
            <el-checkbox-group
              v-model="addEditForm.ljPlaceDetail"
              :disabled="disabled"
            >
              <el-checkbox
                v-for="(item, index) in gradeOverData"
                :key="index"
                :label="item.name"
              >{{ item.name }}
              </el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <!--        <el-row :gutter="24">-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="起点桩号" prop="startPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPeg"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPegAdd"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="终点桩号" prop="endPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-col>
      <el-col v-if="type == '5'" :span="24">
        <el-row :gutter="24" style="padding:0 12px">
          <el-form-item label="" prop="placeDetail">
            <el-checkbox-group
              v-model="addEditForm.fwqPlaceDetail"
              :disabled="disabled"
            >
              <el-checkbox
                v-for="(item, index) in serviceAreaData"
                :key="index"
                :label="item.name"
              >{{ item.name }}
              </el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <!--        <el-row :gutter="24">-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="起点桩号" prop="startPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPeg"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.startPegAdd"-->
        <!--                clearable-->
        <!--                oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                type="text"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="8">-->
        <!--            <el-form-item :key="type" class="stake-mark" label="终点桩号" prop="endPeg">-->
        <!--              <div class="pegVal-text1">K</div>-->
        <!--              <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--              <div class="pegVal-text2">+</div>-->
        <!--              <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"-->
        <!--                        type="text"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {getDictionaryByCode} from '@/utils/dictionary'
import {refineRequestBody} from '@/utils/requestWrappers'
import {tableData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import {tableData as tunnelData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/tunnelInfo'

export default {
  name: 'ScopeClassify',
  props: {
    type: {
      default: '1',
      type: String
    },
    roadId: {
      default: '',
      type: String
    },
    placeData: {
      default: () => {
      },
      type: Object
    },
    disabled: {
      default: false,
      type: Boolean
    },
    pileNumberRange: {
      default: '',
      type: String
    }
  },
  data() {
    // 自定义验证规则：有值时必须在范围内
    const validateRange1 = () => {
      return (rule, value, callback) => {
        if (this.addEditForm.startPeg === undefined && this.addEditForm.startPegAdd === undefined) {
          callback()
        } else if (!this.isValueInRange(this.combinedValue1, this.startValue, this.endValue)) {
          this.addEditForm.startPeg = undefined
          this.addEditForm.startPegAdd = undefined
          callback(new Error(`所填写的桩号不在${this.startValue}-${this.endValue}范围内`))
        } else {
          callback()
        }
      }
    }
    const validateRange2 = () => {
      return (rule, value, callback) => {
        if (this.addEditForm.endPeg === undefined && this.addEditForm.endPegAdd === undefined) {
          callback()
        } else if (!this.isValueInRange(this.combinedValue2, this.startValue, this.endValue)) {
          this.addEditForm.endPeg = undefined
          this.addEditForm.endPegAdd = undefined
          callback(new Error(`所填写的桩号不在${this.startValue}-${this.endValue}范围内`))
        } else {
          callback()
        }
      }
    }
    return {
      numberStationData: [],
      // 收费站
      tollStationData: [],
      // 隧道
      tunnelData: [],
      // 互通立交
      gradeOverData: [],
      // 服务区
      serviceAreaData: [],
      addEditForm: {
        startPeg: undefined,
        startPegAdd: undefined,
        endPeg: undefined,
        endPegAdd: undefined,
        startPatrolId: '',
        endPatrolId: '',
        placeDetail: [],
        swzPlaceDetail: [],
        ljPlaceDetail: [],
        sdPlaceDetail: [],
        fwqPlaceDetail: []
      },
      rules: {
        startPeg: [{validator: validateRange1(), trigger: 'blur'}],
        endPeg: [{validator: validateRange2(), trigger: 'blur'}]
      },
      startValue: 0,
      endValue: 0
    }
  },
  computed: {
    combinedValue1() {
      return parseFloat(`${this.addEditForm.startPeg}.${String(this.addEditForm.startPegAdd).padStart(3, '0')}`) || 0
    },
    combinedValue2() {
      return parseFloat(`${this.addEditForm.endPeg}.${String(this.addEditForm.endPegAdd).padStart(3, '0')}`) || 0
    }
  },
  watch: {
    type: {
      handler(newVal, oldVal) {
        this.addEditForm.startPeg = undefined
        this.addEditForm.startPegAdd = undefined
        this.addEditForm.endPeg = undefined
        this.addEditForm.endPegAdd = undefined
        this.addEditForm.startPatrolId = ''
        this.addEditForm.endPatrolId = ''
        this.addEditForm.placeDetail = []
        this.addEditForm.swzPlaceDetail = []
        this.addEditForm.ljPlaceDetail = []
        this.addEditForm.sdPlaceDetail = []
        this.addEditForm.fwqPlaceDetail = []
      },
      immediate: true
    },
    roadId: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.addEditForm.placeDetail = []
          this.addEditForm.swzPlaceDetail = []
          this.addEditForm.ljPlaceDetail = []
          this.addEditForm.sdPlaceDetail = []
          this.addEditForm.fwqPlaceDetail = []
          this.getAlongRouteInfo(newVal)
          this.getTunnelData(newVal)
          this.handleDataShow()
          this.parseString()
        }
      },
      deep: true, // 开启深度监听
      immediate: true
    }
  },
  methods: {
    getDictionaryByCode,
    parseString() {
      if (this.pileNumberRange) {
        const match = this.pileNumberRange.match(/^[kK](\d+)(?:\+(\d{1,3}))?~[kK](\d+)(?:\+(\d{1,3}))?$/)
        this.startValue = parseFloat(`${match[1]}.${String(match[2]).padStart(3, '0')}`) || 0
        this.endValue = parseFloat(`${match[3]}.${String(match[4]).padStart(3, '0')}`) || 0
      } else {
        this.startValue = 0
        this.endValue = Number.MAX_VALUE
      }
    },
    isValueInRange(value, bound1, bound2) {
      if (typeof value !== 'number' || isNaN(value)) return false
      if (!String(value).includes('.')) return true
      const [min, max] = [Math.min(bound1, bound2), Math.max(bound1, bound2)]
      return value >= min && value <= max
    },
    async handleDataShow() {
      const {
        id,
        eventPlace,
        placeName
      } = this.placeData
      if (id) {
        this.addEditForm = {...this.addEditForm, ...this.placeData}
        if (eventPlace !== '1') {
          let name = eventPlace == '3' ? 'sd' : eventPlace == '4' ? 'lj' : eventPlace == '2' ? 'swz' : 'fwq'
          this.$set(this.addEditForm, `${name}PlaceDetail`, [placeName])
        }
      }
    },
    // 根据路段查询沿线信息
    async getAlongRouteInfo(roadId) {
      try {
        const data = {
          pageBean: {pageSize: -1, page: 1, total: 0},
          querys: [
            {
              operation: 'IN',
              property: 'roadSegmentId',
              value: roadId
            }
          ]
        }
        const {total = 0, rows = []} = await tableData(refineRequestBody(data))
        this.numberStationData = rows.filter(item => item.type === '3' || item.type === '1' || item.type === '11')
        this.tollStationData = rows.filter(item => item.type === '3' || item.type === '1')
        this.gradeOverData = rows.filter(item => item.type < 3)
        this.serviceAreaData = rows.filter(item => item.type === '4')
      } catch (error) {
      }
    },
    // 根据路段查询隧道信息
    async getTunnelData(roadId) {
      try {
        const data = {
          pageBean: {pageSize: -1, page: 1, total: 0},
          querys: [
            {
              operation: 'IN',
              property: 'roadSegmentId',
              value: roadId
            }
          ]
        }
        const {total = 0, rows = []} = await tunnelData(refineRequestBody(data))
        this.tunnelData = rows
        // 根据name去重
        this.tunnelData = this.tunnelData.reduce((accumulator, current) => {
          const x = accumulator.find(item => item.name === current.name)
          if (!x) {
            return accumulator.concat([current])
          } else {
            return accumulator
          }
        }, [])
      } finally {
      }
    },
    numberChange(e, type) {
      let siteInfo = this.numberStationData.find(item => item.id === e)
      this.addEditForm[`${type}Name`] = siteInfo.name
    },
    siteChange(e, type) {
      let siteInfo = this.tollStationData.find(item => item.id === e)
      this.addEditForm[`${type}Name`] = siteInfo.name
    },
    sendData(flag = true) {
      const {
        placeName,
        placeDetail,
        ljPlaceDetail,
        startPeg,
        startPegAdd,
        endPeg,
        endPegAdd,
        startPatrolId,
        startPatrolName,
        endPatrolId,
        endPatrolName
      } = this.addEditForm
      let pegSVal = ''
      let pegEVal = ''
      if ((startPeg !== '' && startPeg !== undefined) && (startPegAdd !== '' && startPegAdd !== undefined)) {
        pegSVal = 'k' + (startPeg !== '' ? startPeg : '') + '+' + (startPegAdd !== '' ? startPegAdd : '')
      }
      if ((endPeg !== '' && endPeg !== undefined) && (endPegAdd !== '' && endPegAdd !== undefined)) {
        pegEVal = 'k' + (endPeg !== '' ? endPeg : '') + '+' + (endPegAdd !== '' ? endPegAdd : '')
      }
      if (this.type == '1') {
        return {
          pegSVal,
          pegEVal,
          startPatrolId,
          startPatrolName,
          endPatrolId,
          endPatrolName
        }
      } else {
        let name = this.type == '3' ? 'sd' : this.type == '4' ? 'lj' : this.type == '2' ? 'swz' : 'fwq'
        let array = []
        if (this.addEditForm[`${name}PlaceDetail`].length > 0) {
          const dataSourceMap = {
            '2': {source: 'tollStationData', field: 'swzPlaceDetail'},
            '3': {source: 'tunnelData', field: 'sdPlaceDetail'},
            '4': {source: 'gradeOverData', field: 'ljPlaceDetail'},
            '5': {source: 'serviceAreaData', field: 'fwqPlaceDetail'}
          }
          const {source, field} = dataSourceMap[this.type]
          array = this.addEditForm[field].map(item => {
            const matchedItems = this[source].filter(bItem => bItem.name === String(item))
            return {
              placeName: item,
              pegSVal,
              pegEVal,
              lat: matchedItems[0]?.lat,
              lng: matchedItems[0]?.lng,
              direction: matchedItems[0]?.direction
            }
          })
        }
        return array
      }
    },
    //清空数据
    clearChange() {
      this.addEditForm.startPeg = undefined
      this.addEditForm.startPegAdd = undefined
      this.addEditForm.endPeg = undefined
      this.addEditForm.endPegAdd = undefined
      this.addEditForm.startPatrolId = ''
      this.addEditForm.startPatrolName = ''
      this.addEditForm.endPatrolId = ''
      this.addEditForm.endPatrolName = ''
      this.addEditForm.placeDetail = []
      this.addEditForm.swzPlaceDetail = []
      this.addEditForm.ljPlaceDetail = []
      this.addEditForm.sdPlaceDetail = []
      this.addEditForm.fwqPlaceDetail = []
    },
    // 详情赋值e
    getDetail(row) {
      console.log(row, '6666')
      const {
        placeName,
        placeDetail,
        pegSVal,
        pegEVal,
        startPatrolId,
        startPatrolName,
        endPatrolId,
        endPatrolName
      } = row

      this.$nextTick(() => {
        if (this.type == '1') {
          let data = {
            startPatrolId,
            startPatrolName,
            endPatrolId,
            endPatrolName
          }
          if (pegSVal) {
            let startPegArr = pegSVal.split('+')
            data.startPeg = startPegArr[0].slice(1)
            data.startPegAdd = startPegArr[1]
          }
          if (pegEVal) {
            let endPegArr = pegEVal.split('+')
            data.endPeg = endPegArr[0].slice(1)
            data.endPegAdd = endPegArr[1]
          }
          this.addEditForm = data
        } else {
          // 提取 pegSVal 和 pegEVal
          row.placeDetail = JSON.parse(row.placeDetail)
          const pegSVals = row.placeDetail[0].pegSVal
          const pegEVals = row.placeDetail[0].pegEVal
          if (pegSVals) {
            let startPegArr = pegSVals.split('+')
            this.addEditForm.startPeg = startPegArr[0].slice(1)
            this.addEditForm.startPegAdd = startPegArr[1]
          }
          if (pegEVals) {
            let endPegArr = pegEVals.split('+')
            this.addEditForm.endPeg = endPegArr[0].slice(1)
            this.addEditForm.endPegAdd = endPegArr[1]
          }
          let name = this.type == '3' ? 'sd' : this.type == '4' ? 'lj' : this.type == '2' ? 'swz' : 'fwq'
          // 将 placeDetail 转换为地点名称数组
          this.addEditForm[`${name}PlaceDetail`] = row.placeDetail.map(place => place.placeName)
        }
      })
    }
  }
}
</script>

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

.name-check-box {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;

  .name-check {
    display: flex;
    width: fit-content;
    border: 1px dashed rgba(67, 161, 255, 0.3);
    padding: 0 14px;
    align-items: center;
    height: 42px;
    box-sizing: border-box;
  }

  .name {
    color: #fff;
    font-size: 12px;
  }
}

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

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

    .pegVal-text2 {
      padding-left: 10px;
      font-size: 24px;
    }
  }
}

::v-deep .el-checkbox .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #43a1ff !important;
}
</style>
