<template>
  <tf-page :isActive="isActive">
    <template v-slot:action>
      <QueryForm :selected="selected" :loading="loading" @query="onQuery" @upload="onUpload" />
    </template>
    <tf-table
      :columns="teamCols"
      :data="rainfallHistories"
      :pagination="pagination"
      v-loading="loading.query"
      @page-change="onPageChange"
    >
      <template v-slot:deviceState="{ row }">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          :value="row.deviceState"
          size="small"
          style="user-select: none"
        />
      </template>
    </tf-table>
    <ImportForm :visible.sync="visible" title="导入" :data="current" :loading="loading.upload" @submit="onSubmit" />
  </tf-page>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'
  import QueryForm from './QueryForm.vue'
  import ImportForm from './ImportForm.vue'
  import { getDefaultPagination } from '@/utils/constant'
  import { rainfallCols } from '../utils'
  import { IPagination } from '@/api/common'
  import { importRainfall, rainFallPage } from '../api/rainfall'
  import { IRainfall } from '../api/common'
  import { ElUploadInternalRawFile } from 'element-ui/types/upload'

  @Component({ name: 'Rainfall', components: { QueryForm, ImportForm } })
  export default class Rainfall extends Vue {
    @Prop({ type: Boolean, default: false }) isActive!: boolean
    teamCols = rainfallCols

    visible = false

    current: Partial<IRainfall> = {}

    selected: IRainfall[] = []

    rainfallHistories: IRainfall[] = []

    loading = { query: false, upload: false }

    pagination: IPagination = getDefaultPagination()

    query = {}

    onQuery(query) {
      this.query = { ...query }
      this.doQuery({ current: 1 })
    }

    onUpload() {
      this.visible = true
    }

    async doQuery(query = {}) {
      this.loading.query = true
      try {
        const {
          result: { records, size, total, current }
        } = await rainFallPage({ ...this.pagination, ...this.query, ...query })
        this.pagination = { current, size, total }
        this.rainfallHistories = records || []
      } catch (error) {
        console.log(error)
      }
      this.loading.query = false
    }

    onPageChange(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
      this.doQuery()
    }

    async onSubmit(file: ElUploadInternalRawFile) {
      this.loading.upload = true
      try {
        const { result } = await importRainfall({ file })
        this.$message[result ? 'success' : 'error'](`导入${result ? '成功!' : '失败!'}`)
        this.visible = false
        this.doQuery()
      } catch (error) {
        console.log(error)
      }
      this.loading.upload = false
    }

    preparing() {
      this.doQuery()
    }

    mounted() {
      this.preparing()
    }
  }
</script>
