<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="left"
          label-suffix="："
          label-width="180px"
        >
          <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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="关联事件" prop="carWeight">
                <el-input
                  v-model="addEditForm.eventNo"
                  class="el-click-input"
                  clearable
                  placeholder="点击选择关联事件"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('eventChoice')"
                >
                  <template v-if="addEditForm.eventNo" v-slot:prepend>
                    NO.
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="报案电话" prop="rescueTel">
                <el-input
                  v-model="addEditForm.rescueTel"
                  clearable
                  placeholder="报案电话"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="报案时间" prop="rescueTime">
                <el-date-picker
                  v-model="addEditForm.rescueTime"
                  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"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="救援类型" prop="rescueType">
                <el-radio-group v-model="addEditForm.rescueType" size="medium">
                  <el-radio
                    v-for="(item, index) in getDictionaryByCode('jylx')"
                    :key="index"
                    :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="8">
              <el-form-item label="所属路段" prop="roadId">
                <div style="display:flex;">

                  <el-select
                    v-model="addEditForm.roadId"
                    filterable
                    placeholder="请选择所属路段"
                    @change="roadChange"
                  >
                    <el-option
                      v-for="item in roadOptions"
                      :key="item.id"
                      :label="item.roadName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </div>

              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="路段桩号范围">
              <span style="
                  margin-right: 20px;
                  color: #fff;
                  font-size: 14px;
                  font-weight: 100;
                ">{{ pileNumberRange }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item 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-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <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"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="结束站" prop="endPatrolId">
                <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-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="12">
              <el-form-item label="行驶方向" prop="direction">
                <el-radio-group v-model="addEditForm.direction" size="medium">
                  <el-radio
                    v-for="(item, index) in getDictionaryByCode('xsfx')"
                    :key="index"
                    :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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="报案来源" prop="rescueSrc">
                <el-select
                  v-model="addEditForm.rescueSrc"
                  clearable
                  placeholder="报案来源"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('baly')"
                    :key="index"
                    :label="item.name"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="24">
              <el-form-item label="占道情况" prop="occupy">
                <!--                <el-checkbox-group v-model="addEditForm.occupy">-->
                <!--                  <el-checkbox v-for="(item, index) in getDictionaryByCode('zdqk')"-->
                <!--                      :key="index" :label="item.value" :value="item.value">{{item.name}}</el-checkbox>-->
                <!--                </el-checkbox-group>-->
                <el-checkbox-group v-model="addEditForm.occupy" size="medium">
                  <el-checkbox
                    v-for="(item, index) in getDictionaryByCode('zdqk')"
                    :key="index"
                    :disabled="item.value > 0 && checkDisabled()"
                    :label="item.value"
                    :value="item.value"
                    @change="chaeckChange"
                  >{{ item.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="事发天气" prop="weather">
                <el-select
                  v-model="addEditForm.weather"
                  allow-create
                  clearable
                  default-first-option
                  filterable
                  placeholder="事发天气"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('tq')"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="故障车牌" prop="carCode">
                <el-input
                  v-model="addEditForm.carCode"
                  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="24">
              <el-form-item label="故障车类" prop="carClass">
                <!--                <el-select v-model="addEditForm.carClass" style="width: 100%" @change="clearCarType" placeholder="故障车类"-->
                <!--                           clearable>-->
                <!--                  <el-option v-for="(item, index) in getDictionaryByCode(-->
                <!--                    'gzcl'-->
                <!--                  )" :key="index" :label="item.name" :value="item.value" />-->
                <!--                </el-select>-->

                <el-radio-group
                  v-model="addEditForm.carClass"
                  size="medium"
                  @change="clearCarType"
                >
                  <el-radio
                    v-for="(item, index) in getDictionaryByCode('gzcl')"
                    :key="index"
                    :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="24">
              <el-form-item label="故障车型" prop="carType">
                <el-radio-group v-model="addEditForm.carType" size="medium">
                  <el-radio
                    v-for="(item, index) in getCarClassify(
                      addEditForm.carClass
                    )"
                    :key="index"
                    :label="Number(item.value)"
                    :value="Number(item.value)"
                  >{{ 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="8">
              <el-form-item label="车载重量（吨）" prop="carWeight">
                <el-input
                  v-model="addEditForm.carWeight"
                  class="number-input"
                  placeholder="请输入内容"
                  type="number"
                >
                  <template slot="append">吨</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="车主姓名" prop="carUser">
                <el-input
                  v-model="addEditForm.carUser"
                  clearable
                  placeholder="车主姓名"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="车主电话" prop="carUserTel">
                <el-input
                  v-model="addEditForm.carUserTel"
                  clearable
                  placeholder="车主电话"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="是否委派" prop="isDelegates">
                <el-switch v-model="addEditForm.isDelegates" @change="isDelegatesChange"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="addEditForm.isDelegates" 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
            v-if="addEditForm.isDelegates"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="委派时间" prop="appointTime">
                <el-date-picker
                  v-model="addEditForm.appointTime"
                  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
            v-if="addEditForm.isDelegates"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <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 teamDataList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="addEditForm.isDelegates"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="派遣人员" prop="person">
                <el-input
                  v-model="addEditForm.person"
                  class="el-click-input"
                  clearable
                  placeholder="点击选择派遣人员"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('userChoice')"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="addEditForm.isDelegates"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="派遣车辆" prop="dispatchCarCode">
                <el-input
                  v-model="addEditForm.dispatchCarCode"
                  class="el-click-input"
                  clearable
                  placeholder="点击选择派遣车辆"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('carChoice')"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="addEditForm.isDelegates"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="派遣车型">
                <el-select
                  v-model="addEditForm.dispatchCarType"
                  clearable
                  disabled
                  placeholder="派遣车型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('jycl-cllx')"
                    :key="index"
                    :label="item.name"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div slot="footer" class="footer">
      <el-button
        v-if="!addEditForm.isDelegates"
        :loading="saveLoading"
        type="primary"
        @click="handleSave"
      >
        {{ $t('domestic.save') }}
      </el-button>
      <el-button
        v-if="addEditForm.isDelegates"
        :loading="saveLoading"
        type="primary"
        @click="handleAppoint"
      >
        委派
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <!-- 车辆选择 -->
    <CarChoiceDialog
      :carData="carData"
      :is-show.sync="carChoiceDialog"
      :selected-content.sync="addEditForm.car"
      @confirm="handleCarSelect"
    />
    <!-- 人员选择 -->
    <UserChoiceDialog
      :is-show.sync="userChoiceDialog"
      :personOptions="personOptions"
      :selected-content.sync="addEditForm.user"
      @confirm="handleUserSelect"
    />
    <!-- 事件选择 -->
    <EventChoiceDialog
      :is-show.sync="eventChoiceDialog"
      :roadId="addEditForm.roadId"
      :selected-content.sync="addEditForm.event"
      @confirm="handleEventSelect"
    />
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import moment from 'moment'
import {refineRequestBody} from '@/utils/requestWrappers'
import {
  appoint,
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/obstacleClearingRescue/rescueRegistration'
import {getDictionaryByCode} from '@/utils/dictionary'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {tableData as alongRouteInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'

import UserChoiceDialog from './components/AppointDialog/components/UserChoiceDialog/index.vue'
import EventChoiceDialog from './components/AppointDialog/components/EventChoiceDialog/index.vue'
import CarChoiceDialog from './components/AppointDialog/components/CarChoiceDialog/index.vue'
import {personAndCarInfo} from '@/api/patrolAndRescue/commandDispatch/eventRegistration'

export default {
  name: 'EditAddPage',
  components: {CarChoiceDialog, EventChoiceDialog, UserChoiceDialog},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    // 自定义验证规则：有值时必须在范围内
    const validateRange1 = () => {
      return (rule, value, callback) => {
        if (this.addEditForm.startPeg === undefined || this.addEditForm.startPegAdd === undefined) {
          callback(new Error('请输入救援点位桩号全值'))
        } 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()
        }
      }
    }
    return {
      pubSub: null,
      formLoading: true,
      addEditForm: {
        rescueTel: '',
        roadId: '',
        occupy: ['0'],
        rescueType: 1,
        carClass: 1,
        carType: 1,
        rescueTime: new Date(),
        car: {},
        person: '',
        dispatchCarCode: '',
        isDelegates: false,
        startPeg: undefined,
        startPegAdd: undefined,
        appointTime: ''
      },
      addEditRules: {
        appointTime: [
          {
            required: true,
            message: '委派时间不能为空',
            trigger: ['change', 'blur']
          }
        ],
        rescueTel: [
          {
            required: true,
            message: '报案电话不能为空',
            trigger: ['change', 'blur']
          }
        ],
        rescueTime: [
          {
            required: true,
            message: '报案时间不能为空',
            trigger: ['change', 'blur']
          }
        ],
        eventType: [
          {
            required: true,
            message: '请选择事件类型',
            trigger: ['change']
          }
        ],
        rescueType: [
          {
            required: true,
            message: '救援类型不能为空',
            trigger: ['change']
          }
        ],
        roadId: [
          {
            required: true,
            message: '路段信息不能为空',
            trigger: ['change']
          }
        ],
        teamId: [
          {
            required: true,
            message: '派遣队伍不能为空',
            trigger: ['change']
          }
        ],
        eventTime: [
          {
            required: true,
            message: '事件发生时间不能为空',
            trigger: ['change']
          }
        ],
        // carUserTel: [
        //   {
        //     pattern: /^1(3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\d{8}$/,
        //     message: '车主电话输入有误',
        //     trigger: 'blur'
        //   }
        // ],
        // person: [
        //   {
        //     required: true,
        //     message: '派遣人员不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // dispatchCarCode: [
        //   {
        //     required: true,
        //     message: '派遣车辆不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        rescueStatus: [
          {
            required: true,
            message: '请选择救援状态',
            trigger: ['change']
          }
        ],
        startPeg: [
          {required: true, validator: validateRange1(), trigger: 'blur'}
        ],
        carUser: [
          {
            required: true,
            message: '车主姓名不能为空',
            trigger: ['change', 'blur']
          }
        ],
        carUserTel: [
          {
            required: true,
            message: '车主电话不能为空',
            trigger: ['change', 'blur']
          }
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      roadOptions: [],
      alongRouteInfoData: [],
      teamOptions: [],
      carData: [],
      carChoiceDialog: false,
      userChoiceDialog: false,
      personOptions: [],
      eventChoiceDialog: false,
      teamDataList: [],
      dispatches: [],
      pileNumberRange: '',
      startValue: 0,
      endValue: 0,
      isclear: false
    }
  },
  computed: {
    combinedValue1() {
      return parseFloat(`${this.addEditForm.startPeg}.${String(this.addEditForm.startPegAdd).padStart(3, '0')}`) || 0
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {

  },
  mounted() {

    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.roadId) {
        this.addEditForm.roadId = data.roadId
      }
      this.getRoadData()
      this.isclear = false
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    getDictionaryByCode,
    isDelegatesChange(val) {
      if (val) {
        this.$set(this.addEditForm, 'appointTime', new Date())
      } else {
        this.$set(this.addEditForm, 'appointTime', '')
      }
    },
    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
      }
    },
    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
    },
    // 占到情况禁用
    checkDisabled() {
      return this.addEditForm.occupy.includes('0')
    },
    chaeckChange(e) {
      if (this.addEditForm.occupy.includes('0')) {
        this.addEditForm.occupy = ['0']
      }
    },
    // 巡查救援点击事件
    teamIdChange(value) {
      this.getPersonAndCarInfo(value)
      let teamInfo = this.teamOptions.find((item) => item.id === value)
      this.addEditForm.teamName = teamInfo.name
      this.$set(this.addEditForm, 'person', '')
      this.$set(this.addEditForm, 'dispatchCarCode', '')
      this.addEditForm.user = []
      this.dispatches = []
    },
    // 根据队伍id查询人员信息及车辆信息
    getPersonAndCarInfo(id) {
      personAndCarInfo(id).then((res) => {
        const {members = [], cars = []} = res.value
        this.personOptions = members.map((person) => {
          person.label = person.tel + ' ' + person.name
          return person
        })
        this.carData = cars
      })
    },
    handleEventSelect(data) {
      let obj = {
        eventId: data.id,
        eventNo: data.eventNo,
        rescueTel: data.eventTel || '',
        rescueTime: data.eventTime || '',
        roadId: data.roadId || '',
        roadName: data.roadName || '',
        roadCode: data.roadCode || '',
        startPatrolId: data.startPatrolId || '',
        startPatrolName: data.startPatrolName || '',
        endPatrolId: data.endPatrolId || '',
        endPatrolName: data.endPatrolName || '',
        direction: data.direction || ''
      }
      this.addEditForm = {...this.addEditForm, ...obj}
      if (data.pegSVal) {
        let startPegArr = data.pegSVal.split('+')
        this.addEditForm.startPeg = startPegArr[0].slice(1)
        this.addEditForm.startPegAdd = startPegArr[1]
      }
    },
    handleCarSelect({carNumber, carClass}) {
      this.$set(this.addEditForm, 'dispatchCarCode', carNumber)
      this.$set(this.addEditForm, 'dispatchCarType', carClass)
      this.dispatches.forEach((item) => {
        item.dispatchCarCode = carNumber
        item.dispatchCarType = carClass
      })
    },
    handleUserSelect(user) {
      const {dispatchCarCode = '', dispatchCarType = ''} = this.addEditForm
      if (user.length > 0) {
        this.addEditForm.user = user
        this.addEditForm.person = user.map((item) => item.name).join(',')
        this.dispatches = user.map((item) => {
          return {
            dispatchCarCode,
            dispatchCarType,
            dispatchUserId: item.id,
            dispatchUserName: item.name,
            dispatchUserTel: item.tel
          }
        })
      }
      // this.addEditForm.person = user.name
      // this.dispatches = [
      //   {
      //     dispatchCarCode,
      //     dispatchCarType,
      //     dispatchUserId: user.id,
      //     dispatchUserName: user.name,
      //     dispatchUserTel: user.tel,
      //   }
      // ]
    },
    siteChange(e, type) {
      let siteInfo = this.alongRouteInfoData.find((item) => item.id === e)
      this.addEditForm[`${type}Name`] = siteInfo.name
    },
    clearCarType() {
      this.$set(this.addEditForm, 'carType', '')
    },
    getCarClassify(value) {
      const dict_arr = getDictionaryByCode('gzcl')
      const dict = dict_arr.filter((item) => item.value == value)
      return dict.length ? dict[0]?.lowerDic?.['gzcx'] : []
    },
    handleAppoint() {
      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.occupy = data.occupy.join(',')
          if (data.startPeg && data.startPegAdd) {
            data.pegVal =
              'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          data.rescueTime = moment(data.rescueTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          data.appointTime = moment(data.appointTime).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
          data.car = {
            dispatchCarCode: data.dispatchCarCode || '',
            dispatchCarType: data.dispatchCarType
          }
          data.dispatches = JSON.parse(JSON.stringify(this.dispatches))
          this.$confirm('确认委派救援单吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              let {state, message, value} = await appoint({...data})
              if (state) {
                this.$message.success(`委派成功`)
                this.changePage('TablePage', 'edit')
              }
            } finally {
              this.saveLoading = false
            }
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    //获取所在路段列表数据
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map((item) => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      this.roadChange(this.addEditForm.roadId)
    },

    roadChange(value) {
      let roadInfo = this.roadOptions.find((item) => item.id === value)
      // console.log(roadInfo, 'roadInfo', value, 'this.roadOptions', this.roadOptions)
      if (roadInfo.startPegK && roadInfo.endPegK) {
        this.pileNumberRange = roadInfo.startPegK + '~' + roadInfo.endPegK
      } else {
        this.pileNumberRange = ''
      }
      if (!this.isclear) {
        this.addEditForm.startPeg = undefined
        this.addEditForm.startPegAdd = undefined
      }
      this.addEditForm.teamId = ''
      this.parseString()
      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 getTeamData(value) {
      const {rows = []} = await teamData(
        refineRequestBody({
          querys: [{operation: 'IN', property: 'r.id_', value}]
        }),
        'addEdit'
      )
      this.teamOptions = rows
      this.teamDataList = rows.filter((item) => item.type === '2')
      if (this.teamDataList.length > 0) {
        this.addEditForm.teamId = this.teamDataList[0].id
        this.teamIdChange(this.teamDataList[0].id)
      }
    },

    // 通过路段信息获取沿线设备信息
    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()
      }
    },

    // 打开页面执行
    openPage() {
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      if (dialogName === 'userChoice') {
        if (!this.addEditForm.teamId) {
          this.$message.error('请先选择救援派遣队伍')
        } else {
          this[dialogName + 'Dialog'] = true
        }
      } else {
        this[dialogName + 'Dialog'] = true
      }
    },

    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules, roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules,
        roadOptions
      })
      this.$nextTick((_) => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      try {
        this.isclear = true
        this.addEditForm = await tableDetail(id)
        const {roadId = '', pegVal = '', occupy = ''} = this.addEditForm
        this.addEditForm.occupy = occupy.split(',')
        if (pegVal) {
          let startPegArr = pegVal.split('+')
          this.$set(this.addEditForm, 'startPeg', startPegArr[0].slice(1))
          this.$set(this.addEditForm, 'startPegAdd', startPegArr[1])
        } else {
          this.$set(this.addEditForm, 'startPeg', undefined)
          this.$set(this.addEditForm, 'startPegAdd', undefined)
        }
        this.roadChange(roadId)
      } finally {
        this.formLoading = false
      }
    },

    // 保存
    handleSave() {
      console.log(this.addEditForm, 'addEditForm')
      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.occupy = data.occupy.join(',')
          if (data.startPeg && data.startPegAdd) {
            data.pegVal =
              'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          data.rescueTime = moment(data.rescueTime).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
          data.car = {
            dispatchCarCode: data.dispatchCarCode || '',
            dispatchCarType: data.dispatchCarType
          }
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            let {state, message, value} = await myInterFace({...data})
            if (state) {
              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;
  }
}

.corporate-customers .edit-add-detail .form-content .el-form {
  //overflow: visible;
}

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

  .form-content {
    overflow-y: auto;
    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>
