<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="6">
              <el-form-item label="路段桩号范围">
                <div class="pegVal-text">{{ pileNumberRange }}</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="9">
              <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-col :span="9">
              <el-form-item class="stake-mark" label="终点桩号" prop="endPeg">
                <div class="pegVal-text1">K</div>
                <el-input v-model="addEditForm.endPeg" clearable oninput="value=value.replace(/[^0-9]/g,'')"
                          type="text"></el-input>
                <div class="pegVal-text2">+</div>
                <el-input v-model="addEditForm.endPegAdd" clearable oninput="value=value.replace(/[^0-9]/g,'')"
                          type="text"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="拥堵原因" prop="cause">
                <el-select
                  v-model="addEditForm.cause"
                  clearable
                  placeholder="请选择拥堵原因"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('ydyy')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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="6">
              <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="6">
              <el-form-item label="处置措施">
                <el-select
                  v-model="addEditForm.measure"
                  clearable
                  placeholder="请选择处置措施"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('czcs')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="addEditForm.remarks"
                  :autosize="{minRows: 2, maxRows: 4}"
                  placeholder="请输入"
                  type="textarea"
                >
                </el-input>
              </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 {trafficJamAdd, trafficJamEdit} from '@/api/patrolAndRescue/commandDispatch/eventManagement/eventEdit'

export default {
  name: 'trafficJamDialog',
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    top: {
      default: '14vh',
      type: String
    },
    width: {
      default: '60%',
      type: String
    },
    height: {
      default: '65vh',
      type: String
    },
    confirmCloseDialog: {
      default: true,
      type: Boolean
    },
    roadOptions: {
      default: () => [],
      type: Array
    },
    itemDetail: {
      default: () => {
      },
      type: Object
    }
  },
  components: {
    SuperDialog
  },
  data() {
    // 自定义验证规则：有值时必须在范围内
    const validateRange1 = () => {
      return (rule, value, callback) => {
        if (this.addEditForm.startPeg === undefined && this.addEditForm.startPegAdd === undefined) {
          callback()
        } else if (!this.isValueInRange(this.combinedValue1, this.startValue, this.endValue)) {
          this.addEditForm.startPeg = undefined
          this.addEditForm.startPegAdd = undefined
          callback(new Error(`所填写的桩号不在${this.startValue}-${this.endValue}范围内`))
        } else {
          callback()
        }
      }
    }
    const validateRange2 = () => {
      return (rule, value, callback) => {
        if (this.addEditForm.endPeg === undefined && this.addEditForm.endPegAdd === undefined) {
          callback()
        } else if (!this.isValueInRange(this.combinedValue2, this.startValue, this.endValue)) {
          this.addEditForm.endPeg = undefined
          this.addEditForm.endPegAdd = undefined
          callback(new Error(`所填写的桩号不在${this.startValue}-${this.endValue}范围内`))
        } else {
          callback()
        }
      }
    }
    return {
      addEditForm: {
        startPeg: undefined,
        startPegAdd: undefined,
        endPeg: undefined,
        endPegAdd: undefined
      },
      rules: {
        startPeg: [{validator: validateRange1(), trigger: 'blur'}],
        endPeg: [{validator: validateRange2(), trigger: 'blur'}],
        cause: [{required: true, message: '请选择拥堵原因', trigger: 'blur'}],
        startTime: [
          {required: true, message: '请选择拥堵时间', trigger: 'blur'}
        ],
        controlTime: [
          {required: true, message: '请选择预计解除时间', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      pileNumberRange: '',
      startValue: 0,
      endValue: 0
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    },
    combinedValue1() {
      return parseFloat(`${this.addEditForm.startPeg}.${String(this.addEditForm.startPegAdd).padStart(3, '0')}`) || 0
    },
    combinedValue2() {
      return parseFloat(`${this.addEditForm.endPeg}.${String(this.addEditForm.endPegAdd).padStart(3, '0')}`) || 0
    }
  },
  methods: {
    getDictionaryByCode,
    parseString() {
      if (this.pileNumberRange) {
        const match = this.pileNumberRange.match(/^[kK](\d+)(?:\+(\d{1,3}))?~[kK](\d+)(?:\+(\d{1,3}))?$/)
        this.startValue = parseFloat(`${match[1]}.${String(match[2]).padStart(3, '0')}`) || 0
        this.endValue = parseFloat(`${match[3]}.${String(match[4]).padStart(3, '0')}`) || 0
      } else {
        this.startValue = 0
        this.endValue = Number.MAX_VALUE
      }
    },
    isValueInRange(value, bound1, bound2) {
      if (typeof value !== 'number' || isNaN(value)) return false
      if (!String(value).includes('.')) return true
      const [min, max] = [Math.min(bound1, bound2), Math.max(bound1, bound2)]
      return value >= min && value <= max
    },
    // 打开弹层时触发
    open() {
      const {roadId, eventId, id, pegEVal, pegSVal, ...rest} = this.itemDetail
      if (id) {
        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]
        }

        this.addEditForm = {
          id,
          roadId,
          eventId,
          startPeg,
          startPegAdd,
          endPeg,
          endPegAdd,
          ...rest
        }
      } else {
        this.addEditForm = {
          roadId,
          eventId,
          startTime: new Date(),
          controlTime: new Date(),
          cause: getDictionaryByCode('ydyy')[0].value,
          measure: getDictionaryByCode('czcs')[0].value,
          startPeg: undefined,
          startPegAdd: undefined,
          endPeg: undefined,
          endPegAdd: undefined
        }
      }
      this.roadChange(roadId)
      this.parseString()
    },
    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 = ''
      }
    },
    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))
          if (data.startPeg && data.startPegAdd) {
            data.pegSVal =
              'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          if (data.endPeg && data.endPegAdd) {
            data.pegEVal =
              'k' + (data.endPeg || '') + '+' + (data.endPegAdd || '')
          }
          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
          const api = data.id ? trafficJamEdit : trafficJamAdd
          const type = data.id ? '编辑' : '新增'
          try {
            const {state, value, message} = await api(data)
            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() {
      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;
}
</style>
