<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, placeholder, ...rest } of formItems"
            :style="{ width: '50%', float: 'left' }"
            :key="name"
            :required="required"
            :label="label"
            :prop="name"
            :class="{
              fullWidth: name == 'linkedData' || name == 'explan'
            }"
          >
            <el-date-picker
              v-if="type === 'date'"
              v-model="formData[name]"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd"
              :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%"
            >
              <el-option v-for="item in options" :key="item.id" :label="item.notes" :value="item.codeValue" />
            </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="placeholder ? placeholder : `请输入${label}`"
              size="medium"
              clearable
              v-bind="rest"
            />
          </el-form-item>
          <el-collapse v-model="activeName">
            <el-collapse-item title="原始数据配置" name="original">
              <el-form-item
                v-for="{ name, label, type, required, disabled, placeholder, ...rest } of configItems"
                :style="{ width: '50%', float: 'left' }"
                :key="name"
                :required="required"
                :label="label"
                :prop="name"
                :class="{
                  fullWidth: name == 'dataSourceField'
                }"
              >
                <el-input
                  v-model="formData[name]"
                  :type="type || 'text'"
                  :rows="2"
                  :disabled="disabled"
                  :placeholder="placeholder ? placeholder : `请输入${label}`"
                  size="medium"
                  clearable
                  v-bind="rest"
                />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </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 { IFWIndex, IKeyCode } from '../../commonAPI/common'
import { getByKeys } from '../../commonAPI/request'

const getDefaultValue = (): Partial<IFWIndex> => ({
  warningMethod: undefined,
  warningType: undefined,
  warningGroup: undefined,
  warningIndexCode: undefined,
  warningIndexName: undefined,
  warningIndexShortName: undefined,
  dataSources: undefined,
  linkedData: undefined,
  explan: undefined,
  isEnable: undefined,
  findDate: undefined,
  dataSourceField: undefined,
  dataSourceParam: undefined,
  handleDate: undefined,
  handleStatus: undefined,
  handleStatusDetail: undefined
})

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

  types: IKeyCode[] = []

  dataSources: IKeyCode[] = []

  activeName = 'original'

  mounted() {
    this.getDictionaryValue()
  }
  get listeners() {
    const { submit, ...rest } = this.$listeners
    return rest
  }

  get formItems() {
    return [
      { label: '预警方式', name: 'warningMethod', type: 'select', required: true, options: this.methods },
      { label: '预警类型', name: 'warningType', type: 'select', required: true, options: this.types },
      { label: '预警分组', name: 'warningGroup', required: true },
      { label: '预警指标代码', name: 'warningIndexCode', required: true },
      { label: '预警指标名称', name: 'warningIndexName', required: true },
      { label: '预警指标简称', name: 'warningIndexShortName', required: true },
      { label: '数据来源', name: 'dataSources', type: 'select', options: this.dataSources },
      { label: '预警时间', name: 'findDate', required: true, placeholder: '例如 warning_tm' },
      { label: '关联数据接口', name: 'linkedData', placeholder: '填写地址，例如 https://xxx/xxx/xx' },
      { label: '说明', name: 'explan', type: 'textarea' },
      { label: '是否启用', name: 'isEnable', type: 'switch', required: true }
    ]
  }

  get configItems() {
    return [
      { label: '返回数据结构', name: 'dataSourceField', placeholder: '例如 equipment_name,lat,lon', required: true },
      { label: '查询参数', name: 'dataSourceParam', placeholder: '例如 id:device_id', required: true },
      { label: '处理时间', name: 'handleDate', placeholder: '例如 warning_tm' },
      { label: '处理状态', name: 'handleStatus' },
      { label: '处理状态详情', name: 'handleStatusDetail' }
    ]
  }

  rules = {
    warningMethod: [{ required: true, message: '请选择预警方式' }],
    warningType: [{ required: true, message: '请选择预警类型' }],
    warningGroup: [{ required: true, message: '请输入预警分组' }],
    warningIndexCode: [{ required: true, message: '请输入预警指标代码' }],
    warningIndexName: [{ required: true, message: '请输入预警指标名称' }],
    warningIndexShortName: [{ required: true, message: '请输入预警指标简称' }],
    isEnable: [{ required: true, message: '请选择是否启用' }],
    findDate: [{ required: true, message: '请输入预警时间字段' }],
    dataSourceField: [{ required: true, message: '请输入原始数据返回数据结构' }],
    dataSourceParam: [{ required: true, message: '请输入原始数据查询参数' }]
  }

  onSubmit() {
    this.$refs.form.validate((valid) => {
      if (valid) {
        this.formData.warningMethod = this.methods.find((e) => e.codeValue == this.formData.warningMethod)
          ? this.methods.find((e) => e.codeValue == this.formData.warningMethod).codeValue
          : this.methods.find((e) => e.notes == this.formData.warningMethod).codeValue
        this.formData.warningType = this.types.find((e) => e.codeValue == this.formData.warningType)
          ? this.types.find((e) => e.codeValue == this.formData.warningType).codeValue
          : this.types.find((e) => e.notes == this.formData.warningType).codeValue
        const { ...rest } = this.formData
        this.$emit('submit', { ...rest })
      }
    })
  }

  @Watch('data', { immediate: true })
  setDefaultData(val: IFWIndex) {
    for (const key in val) {
      if (val[key] == '/') {
        val[key] = ''
      }
    }
    this.formData = val.id ? { ...val } : { ...getDefaultValue() }
  }

  async getDictionaryValue() {
    let pM = await getByKeys({ keys: 'WARNING_METHOD' })
    let pT = await getByKeys({ keys: 'WARNING_TYPE' })
    let pD = await getByKeys({ keys: 'DATA_SOURCE_CONFIG' })
    this.methods = pM.result.WARNING_METHOD
    this.types = pT.result.WARNING_TYPE
    this.dataSources = pD.result.DATA_SOURCE_CONFIG
  }
}
</script>
<style lang="scss" scoped>
.fullWidth {
  width: 100% !important;
}
/deep/ .el-collapse {
  float: left;
  width: 100%;
  border: none;
  .el-collapse-item__header {
    height: 36px;
    font-size: 14px;
    color: #606266;
    border: none;
  }
}
</style>
