<template>
  <el-form class="form" ref="form" v-bind="{ labelWidth: 'auto', size: 'small' }" :model="formData" inline>
    <el-form-item label="监测站点">
      <el-select
        v-model="formData.siteId"
        @change="onPintChange"
        filterable
        :disabled="loading.query"
        :loading="fetchingPoint"
      >
        <el-option v-for="item in points" :key="item.id" :label="item.siteName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="监测指标">
      <el-select v-model="formData.checkCode" collapse-tags :disabled="fetchingPoint" multiple>
        <el-option v-for="item of standards" :key="item.targetCode" :label="item.targetName" :value="item.targetCode" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        size="small"
        :loading="loading.query"
        :disabled="loading.query || !formData.siteId || !formData.checkCode"
        @click="onQuery"
        icon="el-icon-search"
      >
        查询
      </el-button>
      <!-- <el-button
        type="primary"
        size="small"
        :loading="loading.export"
        :disabled="loading.export"
        @click="$emit('export')"
        icon="el-icon-download"
      >
        导出
      </el-button> -->
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'
  import { IPoint, IPointTarget } from '../../configuration/api/common'
  import { getTargets } from '../../configuration/api/point'

  export interface ILoading {
    query: boolean
    export: boolean
  }

  @Component({ name: 'QueryForm' })
  export default class QueryForm extends Vue {
    @Prop({ type: Object, default: () => ({}) }) loading!: ILoading
    formData: { siteId: number; checkCode: number[] } = { siteId: undefined, checkCode: [] }
    @Prop({ type: Array, default: () => [] }) points!: IPoint[]
    @Prop({ type: Boolean, default: false }) fetchingPoint!: ILoading
    standards: IPointTarget['showVos'] = []
    fetchingStandard: boolean = false
    onQuery() {
      this.$emit('query', { ...this.formData, checkCode: this.formData.checkCode.join() })
    }

    onPintChange(id) {
      const point = this.points.find((item) => item.id === id)
      const { sectionId } = point || {}
      if (sectionId) {
        this.fetchStandard(sectionId)
      }
      this.formData = { ...this.formData, checkCode: undefined }
    }

    async fetchStandard(sectionId) {
      this.standards = []
      this.fetchingStandard = true
      try {
        const { result } = await getTargets({ sectionId })
        this.standards = result.showVos
        this.$emit('standard-change', this.standards)
      } catch (error) {
        console.log(error)
      }
      this.fetchingStandard = false
    }
  }
</script>
