<template>
  <div class="page-container">
    <div class="actions">
      <QueryForm
        :selected="selected"
        :types="types"
        :loading="loading"
        @query="onQuery"
        @add="onAdd"
        @update="onUpdate"
        @del="onDel"
        @export="onExport"
      />
    </div>
    <BaseTable
      :columns="deviceCols"
      :data="archives"
      :pagination="pagination"
      v-loading="loading.query"
      @row-dblclick="onDblClick"
      @selection-change="onSelectionChange"
      @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>
    </BaseTable>
    <DeviceForm
      :visible.sync="visible"
      :title="`${current.id ? '修改' : '新增'}设备档案`"
      :data="current"
      :types="types"
      @submit="onSubmit"
      :loading="loading.add || loading.update"
    />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import BaseTable from '@/components/BaseTable/index.vue'
import QueryForm, { ILoading } from './QueryForm.vue'
import DeviceForm from './DeviceForm.vue'
import { updateDevice, addDevice, deleteDeviceBatch, devicePage } from '../api/device'

import { getDefaultPagination } from '@/utils/constant'
import { deviceCols } from '../utils'
import { IDevice, IDeviceType } from '../api/common'
import { IPagination } from '@/api/common'
import { deviceTypePage } from '../api/deviceType'

@Component({ name: 'Device', components: { BaseTable, QueryForm, DeviceForm } })
export default class Device extends Vue {
  @Prop({ type: Boolean, default: false }) isActive!: boolean
  deviceCols = deviceCols

  visible = false

  current: Partial<IDevice> = {}

  selected: IDevice[] = []

  types: IDeviceType[] = []

  archives: IDevice[] = []

  loading: ILoading = { query: false, add: false, update: false, del: false, export: false }

  pagination: IPagination = getDefaultPagination()

  query: Partial<IDevice> = {}

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

  async doQuery(query = {}) {
    this.loading.query = true
    try {
      const {
        result: { records, size, total, current }
      } = await devicePage({ ...this.pagination, ...this.query, ...query, ...this.$store.getters['project/id'] })
      this.pagination = { current, size, total }
      this.archives = records || []
    } catch (error) {
      console.log(error)
    }
    this.loading.query = false
  }

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

  async onSubmit(data: IDevice) {
    this.loading[data.id ? 'update' : 'add'] = true
    try {
      const { result } = await (data.id
        ? updateDevice({ ...data, fileTypeID: 803 })
        : addDevice({ ...data, ...this.$store.getters['project/info'], fileTypeID: 803 }))
      this.$message[result ? 'success' : 'error'](`${data.id ? '修改' : '新增'}设备档案${result ? '成功!' : '失败!'}`)
      if (result) {
        this.visible = false
        this.doQuery()
      }
    } catch (error) {
      console.log(error)
    }
    this.loading[data.id ? 'update' : 'add'] = false
  }

  onAdd() {
    this.current = {}
    this.visible = true
  }

  onUpdate(row) {
    this.current = { ...row }
    this.visible = true
  }

  async onDel(ids) {
    await this.$confirm(`是否确认删除这${this.selected.length}项设备档案？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    this.loading.del = true
    try {
      const { result } = await deleteDeviceBatch(ids)
      this.$message[result ? 'success' : 'error'](`删除设备档案${result ? '成功!' : '失败!'}`)
      result && this.doQuery()
    } catch (error) {
      console.log(error)
    }
    this.loading.del = false
  }

  onExport(ids) {
    console.log(ids)
  }

  onDblClick(row) {
    this.current = { ...row }
    this.visible = true
  }

  onSelectionChange(selections) {
    this.selected = [...selections]
  }

  async getAllTypes() {
    try {
      const {
        result: { records }
      } = await deviceTypePage({ current: 1, size: 9999 })
      this.types = records || []
    } catch (error) {
      console.log(error)
    }
  }

  mounted() {
    this.doQuery()
    this.getAllTypes()
  }

  @Watch('isActive')
  refetchData(active: boolean) {
    if (active) {
      this.getAllTypes()
    }
  }
}
</script>
