<template>
  <super-dialog
    v-model="isShowDialog"
    :modal="false"
    :top="top"
    :width="width"
    title="交通管制信息"
    v-bind="$attrs"
    @closed="closed"
    @open="open"
  >
    <div :style="{height}" class="eventInfo-dialog">
      <div class="form-module">
        <el-form
          ref="addEditForm"
          :model="addEditForm"
          :rules="rules"
          label-position="top"
          label-suffix="："
          label-width="100px"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="路段名称" prop="roadId">
                <el-select
                  v-model="addEditForm.roadId"
                  disabled
                  filterable
                  placeholder="路段名称"
                  style="width: 100%"
                  @change="roadChange"
                >
                  <el-option
                    v-for="(item, index) in roadOptions"
                    :key="index"
                    :label="item.roadName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="路段桩号范围">
                <div class="pegVal-text">
                  {{ pileNumberRange }}
                  <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>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <ScopeClassify
              ref="scopeClassify"
              :pileNumberRange="pileNumberRange"
              :placeData="addEditForm"
              :roadId="addEditForm.roadId"
              :type="addEditForm.eventPlace"
            >
            </ScopeClassify>
          </el-row>
          <el-row v-if="whereTheRoadGoes.length>0" :gutter="24">
            <el-col :span="24">
              <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="24">
              <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="24">
              <el-form-item>
                <el-checkbox-group v-model="addEditForm.measureContent">
                  <el-checkbox
                    v-for="item in gzcsxqOptions"
                    :key="item.value"
                    :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-row>
        </el-form>
        <div class="content-bottom">
          <el-button size="small" @click="isShowDialog = false">
            取 消
          </el-button>
          <el-button
            :disabled="saveLoading"
            size="small"
            type="primary"
            @click="handleAppoint"
          >
            确 定
          </el-button>
        </div>
      </div>
    </div>
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {getDictionaryByCode} from '@/utils/dictionary'
import moment from 'moment'
import {trafficControlAdd} from '@/api/patrolAndRescue/commandDispatch/eventManagement/eventEdit'
import ScopeClassify from '../ScopeClassify/index.vue'

export default {
  name: 'trafficControlDialog',
  components: {SuperDialog, ScopeClassify},
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    top: {
      default: '10vh',
      type: String
    },
    width: {
      default: '60%',
      type: String
    },
    height: {
      default: '68vh',
      type: String
    },
    confirmCloseDialog: {
      default: true,
      type: Boolean
    },
    roadOptions: {
      default: () => [],
      type: Array
    },
    itemDetail: {
      default: () => {
      },
      type: Object
    }
  },
  data() {
    return {
      addEditForm: {
        eventPlace: '1',
        measureType: '', // 管制措施
        measureContent: [] // 管制措施详情
      },
      rules: {
        startTime: [
          {required: true, message: '请选择管制时间', trigger: 'blur'}
        ],
        controlTime: [
          {required: true, message: '请选择预计解除时间', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      pileNumberRange: '', // 桩号范围
      gzcsxqOptions: [], // 管制措施详情
      whereTheRoadGoes: [],
      regulatoryMeasures: []
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  created() {
    this.getControlChange()
  },
  methods: {
    getDictionaryByCode,
    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
      }
    },
    // 打开弹层时触发
    open() {
      console.log(this.itemDetail, 'this.itemDetail')
      const {
        eventPlace,
        roadId,
        eventId,
        id,
        pegEVal,
        pegSVal,
        measureContent: measureContentStr,
        ...rest
      } = this.itemDetail
      if (id) {
        this.eventPlaceChange(eventPlace)
        let startPeg, startPegAdd, endPeg, endPegAdd
        if (pegSVal) {
          const partArr = pegSVal.split('+')
          startPeg = partArr[0].replace('k', '')
          startPegAdd = partArr[1]
        }
        if (pegEVal) {
          const partArr = pegEVal.split('+')
          endPeg = partArr[0].replace('k', '')
          endPegAdd = partArr[1]
        }
        let measureContent = measureContentStr
          ? measureContentStr.split(',')
          : []
        this.addEditForm = {
          id,
          roadId,
          eventId,
          startPeg,
          startPegAdd,
          endPeg,
          endPegAdd,
          measureContent,
          eventPlace,
          ...rest
        }
      } else {
        this.eventPlaceChange(getDictionaryByCode('sjfsqy')[0].value)
        this.addEditForm = {
          roadId,
          eventId,
          startTime: new Date(),
          controlTime: new Date(),
          eventPlace: getDictionaryByCode('sjfsqy')[0].value,
          measureType: getDictionaryByCode('gzcs')[0].value,
          direction: '',
          measureContent: [], // 管制措施详情
          status: '0'
        }
      }
      this.getOptions(this.addEditForm.measureType, 'init')
      this.roadChange(roadId)
    },
    roadChange(val) {
      let roadInfo = this.roadOptions.find(item => item.id === val)
      if (roadInfo.startPegK && roadInfo.endPegK) {
        this.pileNumberRange = roadInfo.startPegK + '~' + roadInfo.endPegK
      } else {
        this.pileNumberRange = ''
      }
    },
    // 获取管制措施详情
    getOptions(val, type) {
      if (!type) {
        this.addEditForm.measureContent = []
      }
      let data = getDictionaryByCode('gzcs')
      data.forEach(item => {
        if (item.value == val) {
          this.gzcsxqOptions = item.lowerDic ? item.lowerDic.gzcsxq : []
        }
      })
    },
    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.startTime = moment(data.startTime).format('YYYY-MM-DD HH:mm:ss')
          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()
          let query
          if (data.eventPlace > 1) {
            query = roadData.map(item => {
              item.id ? delete item.id : null
              item.status = '1'
              return {...data, ...item}
            })
          } else {
            let obj = {
              ...data, ...roadData
            }
            obj.placeName = obj.startPatrolName && obj.endPatrolName ? `${obj.startPatrolName}-${obj.endPatrolName}` : (obj.startPatrolName || obj.endPatrolName ? (obj.startPatrolName || obj.endPatrolName) : '')
            query = [obj]
          }
          console.log(query, 'queryqueryqueryquery')
          // const api = data.id ? trafficControlEdit : trafficControlAdd
          const api = trafficControlAdd
          try {
            const type = data.id ? '编辑' : '添加'
            const {state, value, message} = await api(query)
            if (state) {
              this.$message.success('管制' + type + '成功')
              this.$emit('reload')
              this.isShowDialog = false
            } else {
              this.$message.error(message || '管制' + type + '失败')
            }
          } catch (error) {
            this.$message.error(err || '管制' + type + '失败')
          } finally {
            this.saveLoading = false
          }
        }
      })
    },
    // 关闭弹层触发
    closed() {
      this.$refs.scopeClassify.clearChange()
      const {orgData} = this
      // 重置data中的数据

      Object.assign(this.$data, this.$options.data.call(this), {orgData})
      this.$nextTick(() => {
        this.$refs.addEditForm?.clearValidate()
      })
      if (this.confirmCloseDialog) this.isShowDialog = false
    }
  }
}
</script>

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

.eventInfo-dialog {
  width: 100%;
  display: flex;
  flex-direction: column;
  column-gap: 16px;
  min-height: 50vh;

  .form-module {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    row-gap: 16px;
    background-color: $--system-module-color1;
    padding: 16px;
    box-sizing: border-box;
    border-radius: 8px;

    .el-form {
      height: calc(100% - 40px);
      overflow-y: scroll;
    }

    .content-bottom {
      display: flex;
      justify-content: flex-end;
      height: 40px;
    }
  }
}

::v-deep::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
  display: none;
}

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

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

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

.pegVal-text {
  color: #f0f0f0;
  padding-right: 10px;
  font-size: 16px;
  width: fit-content;
  display: flex;
  gap: 20px;
}

.el-form-item__content {
  line-height: normal !important;
}
</style>
