<template>
  <div
    ref="targetSection"
    class="edit-add-detail-new-content"
    data-name="control"
  >
    <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"
        label-position="right"
        label-suffix="："
        label-width="140px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">交通管制</div>
          </div>
        </div>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="路段名称" prop="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">
          <el-col :span="16">
            <el-form-item label="桩号范围" prop="roadId">
              <span
                style="
                  margin-right: 20px;
                  color: #fff;
                  font-size: 14px;
                  font-weight: 100;
                "
              >{{ pileNumberRange }}</span
              >
              <el-radio-group v-model="addEditForm.eventPlace" size="small" @input="eventPlaceChange">
                <el-radio
                  v-for="(item, index) in getDictionaryByCode('sjfsqy')"
                  :key="index"
                  :label="item.value"
                  border
                >{{ item.name }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <ScopeClassify
            ref="scopeClassify"
            :pileNumberRange="pileNumberRange"
            :roadId="addEditForm.roadId"
            :type="addEditForm.eventPlace"
          >
          </ScopeClassify>
        </el-row>
        <el-row v-if="whereTheRoadGoes.length>0" :gutter="24">
          <el-col :span="8">
            <el-form-item label="道路方向" prop="direction">
              <el-radio-group v-model="addEditForm.direction" size="small">
                <el-radio
                  v-for="(item, index) in whereTheRoadGoes"
                  :key="index"
                  :label="item.value"
                  border
                  @click.native.prevent="clickitem(item.value)"
                >{{ item.name }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="管制措施">
              <el-radio-group
                v-model="addEditForm.measureType"
                size="small"
                @input="getOptions"
              >
                <el-radio
                  v-for="(item, index) in  regulatoryMeasures "
                  :key="index"
                  :label="item.value"
                  border
                >{{ item.name }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="gzcsxqOptions.length" :gutter="24">
          <el-col :span="16">
            <el-form-item>
              <el-checkbox-group
                v-model="addEditForm.measureContent"
              >
                <el-checkbox
                  v-for="(item, index) in gzcsxqOptions"
                  :key="index"
                  :label="item.value"
                >{{ item.name }}
                </el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="管制时间" prop="startTime">
              <el-date-picker
                v-model="addEditForm.startTime"
                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-col :span="8">
            <el-form-item label="预计解除时间" prop="controlTime">
              <el-date-picker
                v-model="addEditForm.controlTime"
                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-col :span="8">
            <el-form-item label="" prop="eventLevel">
              <el-button type="primary" @click="handleSave">确认添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="trafficControls" border style="width: 100%">
        <el-table-column align="center" label="序号" type="index" width="60">
        </el-table-column>
        <el-table-column
          align="center"
          label="路段名称"
          min-width="120"
          prop="propertyTypeId"
        >
          <template v-slot="{row}">
            {{ row.roadCode + row.roadName || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="地点"
          min-width="120"
          prop="placeName"
        >
          <template v-slot="{row}">
            {{ row.placeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="起止桩号"
          min-width="120"
          prop="unit"
        >
          <template v-slot="{row}">
            <div v-if="row.pegSVal || row.pegEVal">
              <div>{{ row.pegSVal || '-' }}</div>
              <div>{{ row.pegEVal || '-' }}</div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="方向"
          min-width="80"
          prop="direction"
        >
          <template v-slot="{row}">
            {{ dictionChange(row.direction, row.eventPlace) || '-' }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="price" label="管制措施" width="80">
                    <template v-slot="{ row }">
                        {{ dictionaryEscape('xsfx', row.direction) || '-' }}
                    </template>
                </el-table-column> -->
        <el-table-column
          align="center"
          label="管制开始时间"
          min-width="140"
          prop="startTime"
        >
        </el-table-column>
        <el-table-column
          align="center"
          label="预计解除时间"
          min-width="120"
          prop="controlTime"
        >
        </el-table-column>
        <el-table-column
          align="center"
          label="状态"
          min-width="80"
          prop="totle"
        >
          <template v-slot="{row}">
            <div
              :style="{
                color:
                  row.status < 1
                    ? '#C0C4CC'
                    : row.status < 2
                    ? '#F56C6C'
                    : '#67C23A'
              }"
            >
              {{ dictionaryEscape('gzzt', row.status) || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="totle" width="140">
          <template v-slot="{row, $index}">
            <!-- <el-link :underline="false" type="primary" @click="handleEdit(row, $index)">
                            编辑
                        </el-link> -->
            <el-link
              :underline="false"
              type="danger"
              @click="handleDelete(row, $index)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import PubSub from 'pubsub-js'
import {tableDetail} from '@/api/patrolAndRescue/commandDispatch/eventRegistration'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import ScopeClassify from '../ScopeClassify'

export default {
  name: 'TrafficControl',
  components: {ScopeClassify},
  props: {
    roadOptions: {
      default: () => [],
      type: Array
    }
  },
  data() {
    return {
      addEditForm: {
        startTime: '',
        controlTime: '',
        direction: '',
        eventPlace: '1',
        measureType: '1',
        measureContent: []
      },
      addEditRules: {
        eventTel: [
          {
            required: true,
            message: '报案电话不能为空',
            trigger: ['change', 'blur']
          }
        ],
        roadId: [
          {
            required: true,
            message: '路段信息不能为空',
            trigger: ['change']
          }
        ],
        teamId: [
          {
            required: true,
            message: '处置队伍不能为空',
            trigger: ['change']
          }
        ],
        eventTime: [
          {
            required: true,
            message: '事件发生时间不能为空',
            trigger: ['change']
          }
        ]
      },
      id: '', // id标识符
      trafficControls: [],
      // 管制措施详情
      gzcsxqOptions: [],
      pileNumberRange: '',
      formType: 'add',
      editIndex: 0,
      whereTheRoadGoes: [],
      regulatoryMeasures: []
    }
  },
  watch: {
    roadOptions: {
      handler(newVal, oldVal) {
        if (newVal.length) {
          this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
          let roadInfo = this.roadOptions.find(
            item => item.id === this.roadOptions[0].id
          )
          if (roadInfo.startPegK && roadInfo.endPegK) {
            this.pileNumberRange = roadInfo.startPegK + '~' + roadInfo.endPegK
          } else {
            this.pileNumberRange = ''
          }
        }
      },
      deep: true
    }
  },
  created() {
    this.getControlChange()
    this.eventPlaceChange('1')
    this.getOptions('1')
    this.addEditForm.startTime = moment().format('YYYY-MM-DD HH:mm:ss')
  },
  mounted() {
    this.$bus.$on('synchronousData', data => {
      this.$set(this.addEditForm, 'roadId', data.roadId)
      this.pileNumberRange = data.pileNumberRange
      this.addEditForm.eventPlace = data.eventPlace
      this.addEditForm.roadName = data.roadName
      this.addEditForm.roadCode = data.roadCode
      this.eventPlaceChange(data.eventPlace)
      if (this.$refs.scopeClassify) {
        this.$refs.scopeClassify.getDetail({
          ...data,
          placeDetail: data.placeDetail ? data.placeDetail : []
        })
      }
    })
  },
  methods: {
    dictionaryEscape,
    getDictionaryByCode,
    dictionChange(value, eventPlace) {
      if (!value || !eventPlace) return '-'
      const placeItem = this.getDictionaryByCode('sjfsqy')
        .find(item => item.value === eventPlace)
      if (!placeItem?.lowerDic?.['jtgz-fx']) return '-'
      const matchedItem = placeItem.lowerDic['jtgz-fx']
        .find(item => item.value === value)
      return matchedItem?.name || '-'
      // let data = this.getDictionaryByCode('sjfsqy')
      // let array = data.filter(item => item.value === eventPlace)[0].lowerDic['jtgz-fx']
      // if (array.filter(item => item.value === value).length > 0) {
      //   return array.filter(item => item.value === value)[0].name
      // } else {
      //   return '-'
      // }
    },
    getControlChange() {
      let array = getDictionaryByCode('gzcs')
      const {array1, array2} = array.reduce((acc, item) => {
        if (['2', '6', '7', '8'].includes(item.value)) {
          acc.array1.push(item)
        } else {
          acc.array2.push(item)
        }
        if (item.value === '2') {
          acc.array2.push(item)
        }
        return acc
      }, {array1: [], array2: []})
      if (this.addEditForm.eventPlace === '2') {
        this.regulatoryMeasures = array1
      } else {
        this.regulatoryMeasures = array2
      }
    },
    eventPlaceChange(val) {
      let data = this.getDictionaryByCode('sjfsqy')
      data.forEach(item => {
        if (item.value == val) {
          this.whereTheRoadGoes = item.lowerDic ? item.lowerDic['jtgz-fx'] : []
        }
      })
      this.getControlChange()
      if (val === '2' || val === '6' || val === '7' || val === '8') {
        this.addEditForm.measureType = '2'
      } else {
        this.addEditForm.measureType = '1'
      }
      this.addEditForm.measureContent = []
      this.getOptions(val)
    },

    clickitem(e) {
      if (e === this.addEditForm.direction) {
        this.addEditForm.direction = ''
      } else {
        this.addEditForm.direction = e
      }
    },

    roadChange(e) {
      let roadInfo = this.roadOptions.find(item => item.id === e)
      if (roadInfo.startPegK && roadInfo.endPegK) {
        this.pileNumberRange = roadInfo.startPegK + '~' + roadInfo.endPegK
      } else {
        this.pileNumberRange = ''
      }
    },

    // 获取详情
    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]
        }
      } finally {
        this.formLoading = false
      }
    },

    // 获取管制措施详情
    getOptions(val) {
      let data = this.getDictionaryByCode('gzcs')
      data.forEach(item => {
        if (item.value == val) {
          this.gzcsxqOptions = item.lowerDic ? item.lowerDic.gzcsxq : []
        }
      })
    },

    // 保存
    handleSave() {
      this.$confirm('确认新增交通管制信息数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        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.startTime) {
              data.startTime = moment(data.startTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }
            if (data.controlTime) {
              data.controlTime = moment(data.controlTime).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
            if (data.measureContent.length) {
              data.measureContent = data.measureContent.join(',')
            } else {
              data.measureContent = ''
            }
            let roadData = this.$refs.scopeClassify.sendData()
            this.$refs.scopeClassify.clearChange()
            if (this.addEditForm.eventPlace !== '1') {
              let array = roadData.map(item => {
                return {
                  ...data,
                  ...item,
                  status: '0'
                }
              })
              this.trafficControls = [...this.trafficControls, ...array]
            } else {
              data = {...data, ...roadData}
              data.status = '0'
              data.placeName = data.startPatrolName && data.endPatrolName ? `${data.startPatrolName}-${data.endPatrolName}` : (data.startPatrolName || data.endPatrolName ? (data.startPatrolName || data.endPatrolName) : '')
              this.trafficControls.push(data)
            }
            this.addEditForm.eventPlace = '1'
            this.eventPlaceChange('1')
            this.$emit('sendTrafficData', this.trafficControls)
          }
        })
      })
    },

    handleEdit(row, index) {
      this.formType = 'edit'
      this.editIndex = index
      this.addEditForm = row
      this.$refs.scopeClassify.getDetail(row)
    },
    handleDelete(row, index) {
      this.$confirm('确认删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.trafficControls.splice(index, 1)
        this.$emit('sendTrafficData', this.trafficControls)
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

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

.rows-title {
  position: relative;
  width: 500px;

  .btn-action {
    position: absolute;
    top: 50%;
    left: 90px;
    transform: translateY(-50%);
  }
}

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

  .name-check {
    display: flex;
    width: fit-content;
  }
}

::v-deep .el-tabs {
  overflow: hidden;

  .el-tabs__nav {
    transform: translateX(20px) !important;

    .el-tabs__item {
      letter-spacing: 1px;
      font-size: 15px;
      font-weight: 600;
    }
  }

  height: calc(100% - 93px);
  background: #114066;
  border-radius: 5px;

  .el-tabs__content {
    height: 92%;

    div#pane-first {
      height: 100%;

      .edit-add-detail-new-content {
        // overflow: hidden;
        height: 100%;
      }
    }
  }
}

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