<template>
  <tf-dialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" width="676px" top="7vh" v-if="$attrs.visible">
    <el-row :gutter="15">
      <el-col>
        <el-form
          class="form"
          ref="form"
          v-bind="{ labelWidth: 'auto', size: 'medium' }"
          :model="formData"
          :rules="rules"
        >
          <el-form-item
            v-for="{ name, label, type, required, options, disabled, ...rest } of formItems"
            :style="{ width: '50%', float: 'left' }"
            :key="name"
            :required="required"
            :label="label"
            :prop="name"
            :class="{
              fullWidth: fwList.includes(name),
              isAdaptive: adaptList.includes(name)
            }"
          >
            <el-time-picker
              v-if="type === 'date'"
              v-model="formData[name]"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              value-format="HH:mm:ss"
              placeholder="任意时间点"
            >
            </el-time-picker>
            <!-- <el-date-picker
              v-if="type === 'date'"
              v-model="formData[name]"
              value-format="HH:mm:ss"
              format="HH:mm:ss"
              :disabled="disabled"
              :placeholder="`请选择${label}`"
              clearable
              size="medium"
              v-bind="rest"
            /> -->
            <el-select
              v-else-if="type === 'select'"
              v-model="formData[name]"
              filterable
              :placeholder="`请选择${label}`"
              size="medium"
              clearable
              v-bind="rest"
              style="width: 100%"
              :value-key="rest.valueKey"
            >
              <template v-if="name == 'warningIndexName'"
                ><el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.warningIndexName + '-' + item.warningIndexCode"
                  :value="item"
              /></template>
              <template v-else-if="name == 'indexParam'"
                ><el-option v-for="item in options" :key="item.id" :label="item.codeValue" :value="item.codeValue"
              /></template>
              <template v-else
                ><el-option v-for="item in options" :key="item.id" :label="item.notes" :value="item.notes"
              /></template>
            </el-select>
            <template v-else-if="type === 'switch'">
              <el-radio v-model="formData[name]" label="是">是</el-radio>
              <el-radio v-model="formData[name]" label="否">否</el-radio>
            </template>
            <el-input
              v-else
              v-model="formData[name]"
              :type="type || 'text'"
              :rows="2"
              :disabled="disabled"
              :placeholder="name === 'no' ? '系统自动添加' : `请输入${label}`"
              size="medium"
              clearable
              v-bind="rest"
            />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </tf-dialog>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { ElForm } from 'element-ui/types/form'
import { IFWIndexThreshold, IKeyCode, IFWIndex } from '../../commonAPI/common'
import { getByKeys, getWarnIndexList } from '../../commonAPI/request'

const getDefaultValue = (): Partial<IFWIndexThreshold> => ({
  warningIndexName: undefined,
  indexParam: undefined,
  thresholdCode: undefined,
  unit: undefined,
  specialValue: undefined,
  flowe: undefined,
  upper: undefined,
  effectiveTime: undefined,
  effectiveTimeStart: "00:00:00",
  effectiveTimeEnd: "23:59:59",
  concernExtent: undefined,
  warningLevel: undefined,
  warningTipInfo: undefined,
  detailInfo: undefined,
  explain: undefined,
  isEnable: undefined
})

@Component({ name: 'EditForm' })
export default class EditForm extends Vue {
  @Prop({ type: Object, default: () => ({}) }) data!: object
  $refs!: { form: ElForm }
  formData: Partial<IFWIndexThreshold> = {
    ...getDefaultValue()
  }

  indicators: Partial<IFWIndex>[] = []

  indicatorsOriginal: Partial<IFWIndex>[] = []

  indexParams: IKeyCode[] = []

  attention: IKeyCode[] = []

  fwList = ['warningIndexName', 'effectiveTime', 'warningTipInfo', 'detailInfo', 'explain']

  adaptList = ['effectiveTimeStart', 'effectiveTimeEnd']

  mounted() {
    this.getDictionaryValue()
  }
  //
  @Watch('formData.warningIndexName')
  async onChangeMethod(val) {
    if (this.indicatorsOriginal.length == 0) return
    let res = this.indicatorsOriginal.filter(
      (e) => e.warningIndexName == val || e.warningIndexName == val.warningIndexName
    )
    const key = res[0].dataSources
    let ds = await getByKeys({ keys: key })
    this.indexParams = ds.result[key]
    //
    if (!this.formData.id) this.formData['indexParam'] = undefined
  }
  get listeners() {
    const { submit, ...rest } = this.$listeners
    return rest
  }

  get formItems() {
    return [
      {
        label: '预警指标名称',
        name: 'warningIndexName',
        type: 'select',
        required: true,
        options: this.indicators,
        valueKey: 'warningIndexName'
      },
      { label: '指标参数', name: 'indexParam', required: true, type: 'select', options: this.indexParams },
      { label: '预警阈值编码', name: 'thresholdCode' },
      { label: '单位', name: 'unit' },
      { label: '特定值', name: 'specialValue' },
      { label: '下限', name: 'flowe' },
      { label: '上限', name: 'upper' },
      { label: '有效时段(开始)', name: 'effectiveTimeStart', type: 'date' },
      { label: '有效时段(结束)', name: 'effectiveTimeEnd', type: 'date' },
      { label: '关注程度', name: 'concernExtent', type: 'select', required: true, options: this.attention },
      { label: '预警等级', name: 'warningLevel' },
      { label: '预警提示信息', name: 'warningTipInfo', type: 'textarea', required: true },
      { label: '详细信息', name: 'detailInfo', type: 'textarea' },
      { label: '说明', name: 'explain', type: 'textarea' },
      { label: '是否启用', name: 'isEnable', type: 'switch', required: true }
    ]
  }

  rules = {
    warningIndexName: [{ required: true, message: '请选择预警指标名称' }],
    indexParam: [{ required: true, message: '请输入指标参数' }],
    concernExtent: [{ required: true, message: '请选择关注程度' }],
    warningTipInfo: [{ required: true, message: '请输入预警提示信息' }],
    isEnable: [{ required: true, message: '请选择是否启用' }]
  }

  onSubmit() {
    this.$refs.form.validate((valid) => {
      if (valid) {
        if (this.formData.warningIndexName.constructor === Object) {
          let data = this.formData.warningIndexName
          Object.keys(data).forEach((key) => {
            this.formData[key] = data[key]
          })
        }
        this.formData.effectiveTime = this.formData.effectiveTimeStart + '~' + this.formData.effectiveTimeEnd
        this.$emit('submit', this.formData)
      }
    })
  }

  @Watch('data', { immediate: true })
  setDefaultData(val: IFWIndexThreshold) {
    for (const key in val) {
      if (val[key] == '/') {
        val[key] = ''
      }
    }
    this.formData = val.id
      ? {
          ...val,
          effectiveTimeStart: val.effectiveTime.split('~')[0],
          effectiveTimeEnd: val.effectiveTime.split('~')[1]
        }
      : { ...getDefaultValue() }
  }

  async getDictionaryValue() {
    let pT = await getByKeys({ keys: 'CONCERN_EXTENT' })
    this.attention = pT.result.CONCERN_EXTENT
    let res = await getWarnIndexList({})
    this.indicatorsOriginal = res.result
    this.indicators = res.result.map((item) => {
      return {
        warningIndexName: item.warningIndexName,
        warningIndexCode: item.warningIndexCode,
        warningType: item.warningType,
        warningGroup: item.warningGroup
      }
    })
  }
}
</script>
<style lang="scss" scoped>
.fullWidth {
  width: 100% !important;
}
.isAdaptive {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
</style>
