<template>
  <BaseDialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" :loading="loading">
    <el-form class="form" ref="form" v-bind="{ labelWidth: '6em', size: 'small' }" :model="formData" :rules="rules">
      <el-form-item label="分组名称" prop="groupByName">
        <el-input v-model="formData.groupByName" placeholder="请输入分组名称" clearable />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          placeholder="请输入备注"
          clearable
          rows="3"
          maxlength="255"
        />
      </el-form-item>
      <el-form-item label="关联监测点" prop="siteIds">
        <el-select v-model="formData.siteIds" filterable placeholder="关联监测点" clearable multiple style="width:100%">
          <el-option v-for="item in points" :key="item.id" :label="item.siteName" :value="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 { IPoint, ITeam } from '../api/common'

@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<ITeam> = {}

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

  rules = {
    groupByName: [
      { required: true, message: '分组名称不能为空！', trigger: 'blur' },
      { max: 50, message: '分组名称不超过50个字符', trigger: 'blur' }
    ],
    remarks: [{ required: false, message: '请输入备注', max: 255, trigger: 'blur' }]
  }

  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>
