<template>
  <BaseDialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" :loading="loading">
    <el-form class="form" ref="form" v-bind="{ labelWidth: '8em', size: 'medium' }" :model="formData" :rules="rules">
      <el-form-item required label="设备类型" prop="typeId">
        <el-select
          v-model="formData.typeId"
          filterable
          placeholder="请选择设备类型"
          size="small"
          :disabled="!!formData.id"
          clearable
          style="width:100%"
        >
          <el-option v-for="item in types" :key="item.id" :label="item.deviceTypeName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item required label="指标标准名称" prop="standardName">
        <el-input v-model="formData.standardName" placeholder="请输入指标标准名称" clearable />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import BaseDialog from '@/components/BaseDialog/index.vue'
import { ElForm } from 'element-ui/types/form'
import { IDeviceType, IStandard } from '../api/common'

@Component({ name: 'StandardForm', components: { BaseDialog } })
export default class StandardForm extends Vue {
  @Prop({ type: Object, default: () => ({}) }) data!: object
  @Prop({ type: Array, default: () => [] }) types!: IDeviceType[]
  @Prop({ type: Boolean, default: false }) loading!: boolean
  $refs!: { form: ElForm }

  formData: Partial<IStandard> = {}

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

  rules = {
    typeId: [{ required: true, message: '请选择设备类型' }],
    standardName: [
      { required: true, message: '指标标准名称不能为空！' },
      { max: 50, message: '指标标准名称不超过50个字符' }
    ]
  }

  onSubmit() {
    this.$refs.form.validate((valid) => {
      if (valid) {
        this.$emit('submit', this.formData)
      }
    })
  }
  @Watch('data', { immediate: true })
  setDefaultData(val) {
    this.formData = val.id ? { ...val } : {}
  }
}
</script>
