<template>
  <div class="edit-add-detail">
    <div v-loading="false" class="edit-add-detail-new-content" element-loading-background="rgba(10 ,38 ,61, 0.95)"
         element-loading-text="数据加载中...">
      <div class="form-content" style="flex: 4">
        <el-form ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-position="left" label-suffix="："
                 label-width="170px">
          <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="20">
              <el-form-item label="报案电话" prop="rescueTel">
                <el-input v-model="addEditForm.rescueTel" 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="20">
              <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="20">
              <el-form-item label="救援类型" prop="rescueType">
                <!--                <el-select v-model="addEditForm.rescueType" style="width: 100%" placeholder="救援类型" clearable>-->
                <!--                  <el-option v-for="(item, index) in getDictionaryByCode(-->
                <!--                    'jylx'-->
                <!--                  )" :key="index" :label="item.name" :value="Number(item.value)" />-->
                <!--                </el-select>-->
                <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="20">
              <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-row>
          <el-row :gutter="24" style="flex-wrap: wrap; margin-left: 80px" type="flex">
            <el-col :span="20">
              <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="20">
              <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="20">
              <el-form-item label="行驶方向" prop="direction">
                <!--                <el-select v-model="addEditForm.direction" style="width: 100%" placeholder="行驶方向" clearable>-->
                <!--                  <el-option v-for="(item, index) in getDictionaryByCode(-->
                <!--                    'xsfx'-->
                <!--                  )" :key="index" :label="item.name" :value="item.value" />-->
                <!--                </el-select>-->

                <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="20">
              <el-form-item class="stake-mark" label="事件开始点位桩号全值">
                <div class="pegVal-text1">K</div>
                <el-input v-model="addEditForm.startPeg" clearable></el-input>
                <div class="pegVal-text2">+</div>
                <el-input v-model="addEditForm.startPegAdd" clearable></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="20">
              <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-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap; margin-left: 80px" type="flex">
            <el-col :span="20">
              <el-form-item label="事发天气" prop="weather">
                <el-input v-model="addEditForm.weather" clearable placeholder="事发天气"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">故障车信息</div>
            </div>
          </div>
          <el-row :gutter="24" style="flex-wrap: wrap; margin-left: 80px" type="flex">
            <el-col :span="20">
              <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="20">
              <el-form-item label="故障车类" prop="carClass">
                <!--                <el-select v-model="addEditForm.carCalss" style="width: 100%" 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-select v-model="addEditForm.carType" style="width: 100%" placeholder="故障车型" clearable>-->
                <!--                  <el-option v-for="(item, index) in getDictionaryByCode(-->
                <!--                    'gzcx'-->
                <!--                  )" :key="index" :label="item.name" :value="item.value" />-->
                <!--                </el-select>-->

                <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="20">
              <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="20">
              <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="20">
              <el-form-item label="车主电话" prop="carUserTel">
                <el-input v-model="addEditForm.carUserTel" clearable placeholder="车主电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="form-content" style="flex: 3">
        <el-form ref="formInfo" :model="addEditForm" class="detail-form" label-position="right" label-suffix="：">
          <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-timeline class="flow-box">
            <el-timeline-item v-for="item in addEditForm.handles" :key="item.id" :timestamp="item.createTime"
                              placement="top">
              <el-card>
                <div class="header">
                  <div class="title">
                    事件处置环节：{{
                      dictionaryEscape('jy_czlc', item.rescueNode + '') || '-'
                    }}
                  </div>
                  <div class="title">事件处置人：{{ item.handleUserName }}</div>
                </div>
                <div class="header">
                  <div class="title">
                    事件处置人所属队伍：{{ item.handleTeamName }}
                  </div>
                  <div class="title">事件处置时间：{{ item.handleTime }}</div>
                </div>
                <div class="event-detail">
                  事件处置情况：{{ item.handleInfo }}
                </div>
                <div class="dispose-img">
                  <el-image v-for="file in item.files" :key="file.id" :preview-src-list="getFilePreviewUrlList(item.files)"
                            :src="file.filePreviewUrl" style="width: 100px; height: 100px">
                  </el-image>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-form>
        <el-button circle class="add-btn-fixed" icon="el-icon-plus" title="添加处置环节"
                   type="warning"
                   @click="handleAddDisposal"></el-button>
      </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>
    <disposalProcess :eventInfo="addEditForm" :is-show.sync="disposalProcess" @updataHandles="handleUpdataHandles">
    </disposalProcess>
    <!--  所在路段选择弹层  -->
    <!--    <RoadChoiceDialog :is-show.sync="roadChoiceDialog" :selected-content.sync="addEditForm.road"-->
    <!--      @confirm="handleRoadSelect" />-->
    <!-- 救援单信息 -->
    <!--    <AppointDialog :is-show.sync="appointDialog" :baseInfo="addEditForm" :teamTreeData="teamTreeData"-->
    <!--      @offPage="offPage" />-->
  </div>
</template>

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

export default {
  name: 'EditAddPage',
  components: {MineMap, RoadChoiceDialog, AppointDialog, disposalProcess},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      appointDialog: false,
      formLoading: true,
      addEditForm: {
        occupy: [],
        rescueType: 1,
        carClass: 1,
        rescueTime: new Date()
      },
      addEditRules: {
        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']
          }
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      roadChoiceDialog: false, // 是否展示选择路段弹层
      pubSub: null,
      alongRouteInfoData: [],
      roadOptions: [],
      disposalProcess: false
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
      this.getRoadData()
    })
  },
  methods: {
    getDictionaryByCode,
    dictionaryEscape,
    // 添加处置环节
    handleAddDisposal() {
      this.disposalProcess = true
    },
    handleUpdataHandles() {
      this.getDetail(this.addEditForm.id)
    },
    // 附件预览list
    getFilePreviewUrlList(files) {
      let srcList = files.map((item) => {
        return item.filePreviewUrl
      })
      return srcList
    },
    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'] : []
    },
    offPage() {
      this.changePage('TablePage', 'edit')
    },
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map((item) => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      if (!this.id) {
        this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
        this.roadChange(this.roadOptions[0].id)
      }
    },
    // 队伍选择
    teamIdChange() {
      this.addEditForm.teamFullId =
        this.$refs[`addEditFormCascader`]?.getCheckedNodes()[0]?.data?.path ||
        ''
      this.addEditForm.teamId =
        this.$refs[`addEditFormCascader`]?.getCheckedNodes()[0]?.value || ''
    },
    // 打开页面执行
    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.$nextTick((_) => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      try {
        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', '')
          this.$set(this.addEditForm, 'startPegAdd', '')
        }
        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))
          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
          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})
      })
    },

    // 通过路段信息获取沿线设备信息
    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()
      }
    },
    roadChange(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('请重新选择结束站..'))
          }
        }
      })
    }
  },
  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;
      }
    }
  }
}

.flow-box {
  ::v-deep.el-timeline-item__timestamp {
    font-size: 16px;
    color: #fff;
  }

  .el-card {
    background-color: #144871;
    border-radius: 5px;
  }

  .header {
    display: flex;

    .title {
      width: 50%;
    }

    margin-bottom: 10px;
  }

  .event-detail {
    // padding: 10px 0;
    margin-bottom: 10px;
  }

  .dispose-img {
    display: flex;
    gap: 10px;

    .el-image {
      border-radius: 5px;
      box-sizing: border-box;
    }
  }

}

.add-btn-fixed {
  position: fixed;
  bottom: 160px;
  right: 40px;
  z-index: 999;
}
</style>

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