<template>
  <BaseDialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" @closed="onClosed" :loading="loading">
    <el-form class="form" ref="form" v-bind="{ labelWidth: '8em', size: 'small' }" :model="formData" :rules="rules">
      <el-form-item label="监测站点" prop="siteId">
        <el-select v-model="formData.siteId" filterable placeholder="请选择监测站点" clearable>
          <el-option
            v-for="item in points"
            :key="item.id"
            :label="item.siteName"
            :value="item.id"
            :disabled="formData.upperSiteId === item.id"
          >
            {{ `${item.siteName}${item.sectionId ? ' | ' + item.sectionId : ''}` }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上游监测站点" prop="upperSiteId">
        <el-select v-model="formData.upperSiteId" filterable placeholder="请选择上游监测站点" clearable>
          <el-option
            v-for="item in points"
            :key="item.id"
            :label="item.siteName"
            :value="item.id"
            :disabled="formData.siteId === item.id"
          >
            {{ `${item.siteName}${item.sectionId ? ' | ' + item.sectionId : ''}` }}
          </el-option>
        </el-select>
      </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 { INeighbor, IPoint } from '../api/common'

const getDefaultValue = (): Partial<INeighbor> => ({ siteId: undefined, upperSiteId: undefined })

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

  formData: Partial<INeighbor> = getDefaultValue()

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

  rules = {
    siteId: [{ required: true, message: '请选择监测站点', trigger: 'blur' }],
    upperSiteId: [{ required: true, message: '请选择上游监测站点', trigger: 'blur' }]
  }

  onSubmit() {
    this.$refs.form.validate((valid) => {
      if (valid) {
        this.$emit('submit', this.formData)
      }
    })
  }
  onClosed() {
    this.formData = getDefaultValue()
    this.$emit('closed')
  }

  @Watch('data', { immediate: true })
  setDefaultData(val) {
    this.formData = val.id ? { ...val } : {}
  }
}
</script>
