<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        class="edit-add-form"
        label-position="left"
        label-width="110px"
      >
        <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="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="所属路段" prop="roadName">
              <el-input
                v-model="addEditForm.roadName"
                clearable
                disabled
                placeholder="请输入所属路段"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="所属区域" prop="regionalCode">
              <el-select
                v-model="addEditForm.regionalCode"
                filterable
                placeholder="请选择所属区域"
                style="width: 100%"
                @change="regionChange"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.adcode"
                  :label="item.adname"
                  :value="item.adcode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="6">
            <el-form-item
              class="stake-mark"
              label="开始桩号"
              prop="locationStationNumberStart"
            >
              <div class="pegVal-text1">K</div>
              <el-input
                v-model="addEditForm.startPeg"
                clearable
                type="number"
              ></el-input>
              <div class="pegVal-text2">+</div>
              <el-input
                v-model="addEditForm.startPegAdd"
                clearable
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 20px">
            <el-form-item
              class="stake-mark"
              label="结束桩号"
              prop="locationStationNumberEnd"
            >
              <div class="pegVal-text1">K</div>
              <el-input
                v-model="addEditForm.endPeg"
                clearable
                type="number"
              ></el-input>
              <div class="pegVal-text2">+</div>
              <el-input
                v-model="addEditForm.endPegAdd"
                clearable
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="24">
            <el-form-item label="方向" prop="direction">
              <el-radio-group v-model="addEditForm.direction">
                <el-radio
                  v-for="item in getDictionaryByCode('yxjc-fx')"
                  :key="item.value"
                  :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="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="位置描述" prop="locationCatUncle">
              <el-input
                v-model="addEditForm.locationCatUncle"
                :autosize="{minRows: 2, maxRows: 4}"
                clearable
                maxlength="100"
                placeholder="请输入位置描述"
                show-word-limit
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        <el-row :gutter="24" style="margin-left: 80px">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="预警范围" prop="warnRange">-->
        <!--              <el-input-->
        <!--                v-model="addEditForm.warnRange"-->
        <!--                :autosize="{minRows: 2, maxRows: 4}"-->
        <!--                clearable-->
        <!--                maxlength="100"-->
        <!--                placeholder="请输入预警范围"-->
        <!--                show-word-limit-->
        <!--                type="textarea"-->
        <!--              ></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="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="预警信息来源" prop="publishDeviceName">
              <el-input
                v-model="addEditForm.publishDeviceName"
                clearable
                placeholder="请输入预警信息来源"
                type="text"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left:80px">
          <el-col :span="24">
            <el-form-item label="发布设备类型" prop="publishDeviceType">
              <el-radio-group
                v-model="addEditForm.publishDeviceType"
                size="medium"
              >
                <el-radio
                  v-for="item in getDictionaryByCode('yxjc-fbsblx')"
                  :key="item.value"
                  :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="margin-left: 80px">
          <el-col :span="24">
            <el-form-item label="预警类型" prop="warningType">
              <el-radio-group
                v-model="addEditForm.warningType"
                border
                size="medium"
                @change="warnTypeChange"
              >
                <el-radio
                  v-for="item in getDictionaryByCode('yxjc-yjlx')"
                  :key="item.value"
                  :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="margin-left: 80px">
          <el-col :span="24">
            <el-form-item
              :rules="[
                {
                  required: addEditForm.warningType === 1,
                  message: '请选择预警等级',
                  trigger: 'change'
                }
              ]"
              label="预警等级"
              prop="warningLevel"
            >
              <el-radio-group
                v-model="addEditForm.warningLevel"
                border
                size="medium"
              >
                <el-radio
                  v-for="item in getDictionaryByCode('yxjc-yjdj')"
                  :key="item.value"
                  :label="Number(item.value)"
                  :value="Number(item.value)"
                  @click.native.stop.prevent="handleChange(item.value)"
                >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          v-if="addEditForm.warningType === 1"
          :gutter="24"
          style="margin-left: 80px"
        >
          <el-col :span="8">
            <el-form-item label="预警灾害类型" prop="warningValue">
              <el-select
                v-model="addEditForm.warningValue"
                clearable
                placeholder="请选择预警灾害类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in getDictionaryByCode('yjlxdm')"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="6">
            <el-form-item label="预警时间" prop="warningTime">
              <el-date-picker
                v-model="addEditForm.warningTime"
                default-time="12:00:00"
                format="yyyy-MM-dd HH:mm:ss"
                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" style="margin-left: 20px">
            <el-form-item label="预警解除时间" prop="relieveWarningTime">
              <el-date-picker
                v-model="addEditForm.relieveWarningTime"
                default-time="12:00:00"
                format="yyyy-MM-dd HH:mm:ss"
                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="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="预警内容" prop="warningContent">
              <el-input
                v-model="addEditForm.warningContent"
                :autosize="{minRows: 2, maxRows: 4}"
                clearable
                placeholder="请输入预警内容"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="转发对象" prop="forwardObject">
              <el-input
                v-model="addEditForm.forwardObject"
                clearable
                placeholder="请输入转发对象"
                type="text"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="国标编码" prop="nationalStandardCode">
              <el-input
                v-model="addEditForm.nationalStandardCode"
                clearable
                placeholder="请输入国标编码"
                type="text"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button
        v-if="!addEditForm.pubStatus"
        :loading="saveLoading"
        type="primary"
        @click="handleSave()"
      >
        确认发布
      </el-button>
      <el-button
        v-if="addEditForm.pubStatus"
        :loading="saveLoading"
        type="primary"
        @click="handleSave()"
      >
        保存
      </el-button>
      <el-button
        v-if="id"
        :loading="saveLoading"
        type="danger"
        @click="handleDelete()"
      >
        删除
      </el-button>
      <el-button @click="changePage('TablePage')" v-if="!singlePublish">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  getRegionalData,
  tableAdd,
  tableDelete,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/operationalMonitoring/informatiOnForAttention'
import {getDictionaryByCode} from '@/utils/dictionary'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {mapState} from 'vuex'

export default {
  name: 'EditAddPage',
  components: {},
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  computed: {
    ...mapState({currentUser: state => state.user.currentUserDetail})
  },
  data() {
    const validatePegValStart = (_, __, callback) => {
      const {startPeg, startPegAdd} = this.addEditForm
      if (!startPeg || !startPegAdd) {
        callback(new Error('请输入开始桩号'))
      } else {
        callback()
      }
    }
    const validatePegValEnd = (_, __, callback) => {
      const {endPeg, endPegAdd} = this.addEditForm
      if (!endPeg || !endPegAdd) {
        callback(new Error('请输入结束桩号'))
      } else {
        callback()
      }
    }
    return {
      id: '', // id标识符
      addEditForm: {
        regionalCode: '',
        regionalName: '',
        roadId: '',
        roadName: '',
        roadCode: '',
        direction: '0',
        nationalStandardCode: '',
        locationCatUncle: '',
        publishDeviceName: '',
        publishDeviceType: '',
        warningType: 1,
        warningValue: '',
        relieveWarningTime: '',
        warningTime: this.formatDate(new Date()),
        warningContent: '',
        warnRange: '',
        forwardObject: ''
      },
      addEditRules: {
        regionalCode: [
          {required: true, message: '请选择所属区域', trigger: 'change'}
        ],
        roadName: [
          {required: true, message: '请输入所属路段', trigger: 'blur'}
        ],
        direction: [{required: true, message: '请选择方向', trigger: 'change'}],
        locationStationNumberStart: [
          {
            required: true,
            validator: validatePegValStart,
            message: '请输入开始桩号',
            trigger: ['change', 'blur']
          }
        ],
        locationStationNumberEnd: [
          {
            required: true,
            validator: validatePegValEnd,
            message: '请输入结束桩号',
            trigger: ['change', 'blur']
          }
        ],
        locationCatUncle: [
          {required: true, message: '请输入位置描述', trigger: 'blur'}
        ],
        publishDeviceName: [
          {required: true, message: '请输入预警信息来源', trigger: 'blur'}
        ],
        // publishDeviceType: [
        //   {required: true, message: '请选择发布设备类型', trigger: 'change'}
        // ],
        // warningLevel: [
        //   {required: true, message: '请选择预警等级', trigger: 'change'}
        // ],
        warningType: [
          {required: true, message: '请选择预警类型', trigger: 'change'}
        ],
        warningValue: [
          {required: true, message: '请选择预警灾害类型', trigger: 'change'}
        ],
        warningTime: [
          {required: true, message: '请选择预警时间', trigger: 'change'}
        ],
        warningContent: [
          {required: true, message: '请输入预警内容', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      pubSub: null,
      roadOptions: [],
      regionList: [],
      singlePublish: 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.roadName !== '') {
        this.addEditForm.roadName = data?.roadName || ''
        this.addEditForm.roadId = data?.roadId || ''
      }
      this.getRoadData()
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
      this.getRegionalChange()
      this.warnTypeChange(1)
    })
    if (this.$route.query && this.$route.query.publishId) {
      this.singlePublish = true
      this.id = this.$route.query.publishId
      this.getDetail(this.id)
      this.getRegionalChange()
      this.warnTypeChange(1)
    } else {
      this.singlePublish = false
    }
  },
  methods: {
    getDictionaryByCode,
    handleChange(val) {
      if (this.addEditForm.warningLevel === Number(val)) {
        this.$set(this.addEditForm, 'warningLevel', null)
      } else {
        this.$set(this.addEditForm, 'warningLevel', Number(val))
      }
    },
    warnTypeChange(val) {
      this.addEditForm.warningValue =
        val === 1 ? getDictionaryByCode('yjlxdm')[0].value : ''
    },
    regionChange(val) {
      const {adname, pegEVal, pegSVal} = this.regionList.filter(
        item => item.adcode === val
      )[0]
      this.addEditForm.regionalName = adname
      if (pegSVal) {
        let startPegArr = pegSVal.split('+')
        this.$set(this.addEditForm, 'startPeg', startPegArr[0].slice(1))
        this.$set(this.addEditForm, 'startPegAdd', startPegArr[1])
      }
      if (pegEVal) {
        let endPegArr = pegEVal.split('+')
        this.$set(this.addEditForm, 'endPeg', endPegArr[0].slice(1))
        this.$set(this.addEditForm, 'endPegAdd', endPegArr[1])
      }
    },
    async getRegionalChange() {
      const {value = {}} = (this.regionList = await getRegionalData(
        this.addEditForm.roadId
      ))
      this.regionList = value.regional
      if (this.regionList.length > 0 && !this.id) {
        this.addEditForm.regionalCode = this.regionList[0].adcode
        this.addEditForm.regionalName = this.regionList[0].adname
        if (this.regionList[0].pegSVal) {
          let startPegArr = this.regionList[0].pegSVal.split('+')
          this.$set(this.addEditForm, 'startPeg', startPegArr[0].slice(1))
          this.$set(this.addEditForm, 'startPegAdd', startPegArr[1])
        }
        if (this.regionList[0].pegEVal) {
          let endPegArr = this.regionList[0].pegEVal.split('+')
          this.$set(this.addEditForm, 'endPeg', endPegArr[0].slice(1))
          this.$set(this.addEditForm, 'endPegAdd', endPegArr[1])
        }
      }
    },
    formatDate(date) {
      const pad = num => String(num).padStart(2, '0') // 补零函数
      const year = date.getFullYear()
      const month = pad(date.getMonth() + 1)
      const day = pad(date.getDate())
      const hours = pad(date.getHours())
      const minutes = pad(date.getMinutes())
      const seconds = pad(date.getSeconds())
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    //获取所在路段列表数据
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map(item => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      this.addEditForm.roadCode = this.roadOptions.filter(
        item => item.id === this.addEditForm.roadId
      )[0].code
    },
    // 打开页面执行
    openPage() {},
    // 关闭页面执行
    closePage() {
      const {roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub: this.pubSub,
        roadOptions
      })
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      this.addEditForm = await tableDetail(id)
      this.addEditForm.direction = '0'
      const {pegSVal, pegEVal} = this.addEditForm
      if (pegSVal) {
        let startPegArr = pegSVal.split('+')
        this.$set(this.addEditForm, 'startPeg', startPegArr[0].slice(1))
        this.$set(this.addEditForm, 'startPegAdd', startPegArr[1])
      }
      if (pegEVal) {
        let endPegArr = pegEVal.split('+')
        this.$set(this.addEditForm, 'endPeg', endPegArr[0].slice(1))
        this.$set(this.addEditForm, 'endPegAdd', endPegArr[1])
      }
    },
    // 删除
    handleDelete() {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let {state, message} = await tableDelete(this.id)
          if (state) {
            this.$message.success(`删除成功`)
            if (!this.singlePublish) {
              PubSub.publish('TablePage', {type: 'add'})
              this.changePage('TablePage', 'add')
            }
          } else {
            this.$message.error(message)
          }
        })
        .catch(_ => _)
    },
    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const {startPeg, startPegAdd, endPeg, endPegAdd} = this.addEditForm
          let pegSVal = ''
          let pegEVal = ''
          if (
            startPeg !== '' &&
            startPeg !== undefined &&
            startPegAdd !== '' &&
            startPegAdd !== undefined
          ) {
            pegSVal =
              'k' +
              (startPeg !== '' ? startPeg : '') +
              '+' +
              (startPegAdd !== '' ? startPegAdd : '')
          }
          if (
            endPeg !== '' &&
            endPeg !== undefined &&
            endPegAdd !== '' &&
            endPegAdd !== undefined
          ) {
            pegEVal =
              'k' +
              (endPeg !== '' ? endPeg : '') +
              '+' +
              (endPegAdd !== '' ? endPegAdd : '')
          }
          const myInterFace = this.addEditForm.pubStatus ? tableEdit : tableAdd
          try {
            const response = await myInterFace({
              ...this.addEditForm,
              pegSVal,
              pegEVal,
              pubStatus: 1
            })
            const {state, message} = response
            if (state) {
              const action = this.id ? '发布' : '新增'
              this.$message.success(`${action}成功`)
              // PubSub.publish('TablePage', {type: this.id ? 'edit' : 'add'})
              if (!this.singlePublish) {
                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})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

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

::v-deep .el-textarea .el-input__count {
  background: transparent;
}

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