<template>
  <div ref="targetSection" class="edit-add-detail-new-content" data-name="jam">
    <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="rules" 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-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">
          <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-row :gutter="24">
          <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-col :span="8">
            <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="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-row :gutter="24">
          <el-col :span="8">
            <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="8">
            <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-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="trafficCongestions" 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="unit">
          <template v-slot="{ row }">
            <!--            {{ row.pegSVal ? row.pegSVal + ',' + row.pegEVal : '-' }}-->
            <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="120" 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="remarks">
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="140" prop="totle">
          <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 {getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'TrafficJam',
  props: {
    roadOptions: {
      default: () => [],
      type: Array
    }
  },
  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'}]
      },
      id: '', // id标识符
      trafficCongestions: [],
      pileNumberRange: '',
      formType: 'add',
      editIndex: 0,
      startValue: 0,
      endValue: 0
    }
  },
  computed: {
    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
    }
  },
  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 = ''
          }
          this.parseString()
        }
      },
      deep: true
    }
  },
  created() {
  },
  mounted() {
  },
  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
    },
    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 = ''
      }
      this.addEditForm.startPeg = undefined
      this.addEditForm.startPegAdd = undefined
      this.addEditForm.endPeg = undefined
      this.addEditForm.endPegAdd = undefined
      this.parseString()
    },
    // 获取详情
    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
      }
    },

    // 保存
    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.startPeg !== undefined && data.startPegAdd !== undefined) {
              data.pegSVal =
                'k' + (data.startPeg !== undefined ? data.startPeg : '') + '+' + (data.startPegAdd !== undefined ? data.startPegAdd : '')
            }
            if (data.endPeg !== undefined && data.endPegAdd !== undefined) {
              data.pegEVal =
                'k' + (data.endPeg !== undefined ? data.endPeg : '') + '+' + (data.endPegAdd !== undefined ? data.endPegAdd : '')
            }
            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 (this.formType === 'edit') {
              this.trafficCongestions[this.editIndex] = data
            } else {
              this.trafficCongestions.push(data)
            }
            this.$emit('sendJamData', this.trafficCongestions)
            this.formType = 'add'

            //清空除road之外的字段
            Object.keys(this.addEditForm).forEach(key => {
              if (key !== 'roadId') {
                this.addEditForm[key] = undefined
              }
            })
            console.log(this.addEditForm, '0000')
            // this.addEditForm.startTime = ''
            // this.addEditForm.controlTime = ''
            // this.addEditForm.remarks = ''
            // this.addEditForm.cause = ''
            // this.addEditForm.measure = ''
            // this.addEditForm.startPeg = undefined
            // this.addEditForm.startPegAdd = undefined
            // this.addEditForm.endPeg = undefined
            // this.addEditForm.endPegAdd = undefined
          }
        })
      })
    },
    handleEdit(row, index) {
      this.formType = 'edit'
      this.editIndex = index
      this.addEditForm = row
    },
    handleDelete(row, index) {
      this.$confirm('确认删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.trafficCongestions.splice(index, 1)
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

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

.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 {
        color: #fff;
        padding-right: 10px;
        font-size: 16px;
        width: fit-content;
      }

      .pegVal-text2 {
        padding-left: 10px;
        font-size: 24px;
      }
    }
  }
}
</style>
