<template>
  <tf-dialog
    v-bind="$attrs"
    v-on="listeners"
    @submit="onSubmit"
    :loading="loading"
    :width="formData.defectinfo.interfaceCode ? '1280px' : '768px'"
  >
    <el-form class="form" ref="form" v-bind="{ labelWidth: 'auto', size: 'small' }" :model="formData" :rules="rules">
      <el-row type="flex" :gutter="15">
        <el-col :span="formData.defectinfo.interfaceCode ? 12 : 24">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="排水类型" prop="defectinfo.type">
                <el-select v-model="formData.defectinfo.type" style="wdith: 100%">
                  <el-option v-for="item of types" :key="item.codeValue" :label="item.notes" :value="item.notes" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="缺陷名称" prop="defectinfo.name">
                <el-input v-model="formData.defectinfo.name" placeholder="请输入缺陷名称" maxlength="51" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="缺陷描述" prop="defectinfo.description">
            <el-input
              v-model="formData.defectinfo.description"
              type="textarea"
              placeholder="请输入缺陷描述"
              clearable
              rows="3"
              maxlength="1001"
            />
          </el-form-item>
          <el-form-item label="分析依据" prop="defectinfo.according">
            <el-input
              v-model="formData.defectinfo.according"
              type="textarea"
              placeholder="请输入分析依据"
              clearable
              rows="3"
              maxlength="1001"
            />
          </el-form-item>
          <el-form-item label="监测点" prop="defectinfo.monitorIds">
            <el-select
              v-model="formData.defectinfo.monitorIds"
              placeholder="请选择监测点"
              style="width: 100%"
              multiple
              clearable
              filterable
              :collapse-tags="formData.defectinfo.monitorIds.length > 3"
            >
              <el-option v-for="item of points" :key="item.id" :value="item.id" :label="item.siteName" />
            </el-select>
          </el-form-item>
          <el-form-item label="接口名称" prop="defectinfo.interfaceName">
            <el-select
              v-model="formData.defectinfo.interfaceCode"
              placeholder="请选择接口名称"
              @change="onInterfaceChange"
              style="width: 100%"
            >
              <el-option
                v-for="item of interfaces"
                :key="item.id"
                :value="item.interfaceCode"
                :label="item.interfaceName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="接口说明" prop="defectinfo.interfaceDescription">
            <el-input
              v-model="formData.defectinfo.interfaceDescription"
              type="textarea"
              placeholder="请输入接口说明"
              clearable
              rows="3"
              maxlength="1001"
              disabled
            />
          </el-form-item>
          <el-form-item label="算法说明" prop="defectinfo.algorithmNote">
            <el-input
              v-model="formData.defectinfo.algorithmNote"
              type="textarea"
              placeholder="请输入算法说明"
              clearable
              rows="3"
              maxlength="1001"
              disabled
            />
          </el-form-item>
          <el-form-item label="备注" prop="defectinfo.note">
            <el-input
              v-model="formData.defectinfo.note"
              type="textarea"
              placeholder="请输入备注"
              clearable
              rows="3"
              maxlength="1001"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!!formData.defectinfo.interfaceCode">
          <div>
            <tf-title>参数设置</tf-title>
            <tf-table
              :columns="columns"
              :data="formData.defectinfoParmSet"
              v-loading="fetchingParams"
              auto-height
              style="padding: 0"
            >
              <template v-slot:paramValue="{ $index }">
                <el-form-item
                  :show-message="false"
                  label-width="0"
                  style="margin-bottom: 0"
                  :rules="[{ required: true, message: '' }]"
                  :prop="`defectinfoParmSet[${$index}].paramValue`"
                >
                  <el-input v-model="formData.defectinfoParmSet[$index].paramValue" class="input" />
                </el-form-item>
              </template>
            </tf-table>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </tf-dialog>
</template>

<script lang="ts">
  import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
  import { ElForm } from 'element-ui/types/form'
  import { IFlaw, IFlawParam, IInterface, IParam } from '../api/common'
  import { IDictionary } from '@/api/common'
  import { fetchParams } from '../api/flaw'
  import { IPoint } from '../../configuration/api/common'
  import { flawPointParamCols } from '../utils'

  const getDefaultFormData = () => ({
    defectinfo: {
      according: '',
      algorithmNote: '',
      description: '',
      id: undefined,
      interfaceDescription: '',
      interfaceName: '',
      name: '',
      note: '',
      type: '',
      monitorIds: []
    },
    defectinfoParmSet: []
  })

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

    formData: IFlawParam = getDefaultFormData()

    currentInterface: Partial<IInterface> = {}

    params: IParam[] = []

    columns = flawPointParamCols

    fetchingParams: boolean = false

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

    rules = {
      'defectinfo.type': [{ required: true, message: '请选择排水类型', trigger: 'blur' }],
      'defectinfo.name': [
        { required: true, message: '请输入缺陷名称', trigger: 'blur' },
        { max: 50, message: '缺陷名称不能超过50个字符', trigger: 'blur' }
      ],
      'defectinfo.description': [
        { required: true, message: '请输入缺陷描述', trigger: 'blur' },
        { max: 1000, message: '缺陷描述不能超过1000字符', trigger: 'blur' }
      ],
      'defectinfo.according': [
        { required: true, message: '请输入分析依据', trigger: 'blur' },
        { max: 1000, message: '分析依据不能超过1000字符', trigger: 'blur' }
      ],
      'defectinfo.interfaceName': [
        { required: false, max: 1000, message: '接口名称不能超过1000字符', trigger: 'blur' }
      ],
      'defectinfo.interfaceDescription': [
        { required: false, max: 1000, message: '接口说明不能超过1000字符', trigger: 'blur' }
      ],
      'defectinfo.algorithmNote': [
        { required: false, max: 1000, message: '算法说明不能超过1000字符', trigger: 'blur' }
      ],
      'defectinfo.note': [{ required: false, max: 1000, message: '备注不能超过1000字符', trigger: 'blur' }],
      'defectinfo.monitorIds': [
        {
          type: 'array',
          required: true,
          message: '请选择监测点',
          fields: {
            0: { type: 'number', required: true, message: '请选择监测点' }
          }
        }
      ]
    }

    onInterfaceChange(code: string) {
      const current = this.interfaces.find((item) => item.interfaceCode === code)
      this.currentInterface = current
      const { interfaceName, interfaceCode, interfaceDescription, algorithmNote } = current || {}
      this.formData = {
        ...this.formData,
        defectinfo: { ...this.formData.defectinfo, interfaceName, interfaceDescription, algorithmNote }
      }
      this.fetchParams(interfaceCode)
    }

    async fetchParams(code: string) {
      this.fetchingParams = true
      try {
        const { result } = await fetchParams(code)
        this.formData.defectinfoParmSet = result || []
      } catch (error) {
        console.log(error)
      }
      this.fetchingParams = false
    }

    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const {
            defectinfo: { monitorIds, ...rest },
            defectinfoParmSet
          } = this.formData
          this.$emit('submit', { defectinfo: { ...rest, monitorIds: monitorIds.join() }, defectinfoParmSet })
        }
      })
    }

    @Watch('data', { immediate: true })
    setDefaultData(val: IFlaw) {
      const { id, interfaceCode, monitorIds } = val || {}
      this.formData = id
        ? {
            defectinfo: {
              ...val,
              monitorIds: String(monitorIds || '')
                .split(',')
                .filter((item) => !!item)
                .map((num) => Number(num))
            },
            defectinfoParmSet: []
          }
        : getDefaultFormData()
      this.currentInterface = {}
      if (interfaceCode) {
        this.onInterfaceChange(interfaceCode)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .form {
    /deep/ .input input {
      text-align: center;
    }
  }
</style>
