<template>
  <div class="page-container">
    <div class="actions">
      <QueryForm
        :selected="selected"
        :loading="loading"
        @query="onQuery"
        @add="onAdd"
        @update="onUpdate"
        @enable="onEnable"
        @delete="onDel"
        @export="onExport"
        @dismount="onDismount"
        :types="types"
        :sections="sections"
        :teams="teams"
      />
    </div>
    <BaseTable
      :columns="pointCols"
      :data="points"
      :pagination="pagination"
      v-loading="loading.query"
      @row-dblclick="onDblClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
    >
      <template v-slot:siteState="{ row }">
        <el-switch :active-value="1" :inactive-value="0" :value="row.siteState" size="small" style="user-select:none" />
      </template>
    </BaseTable>
    <PointForm
      :visible.sync="visible.point"
      :title="`${current.id ? '修改' : '新增'}监测点`"
      :data="current"
      :types="types"
      :levels="levels"
      @submit="onSubmit"
    />

    <EnableForm
      title="监测点状态"
      :visible.sync="visible.enable"
      :loading="loading.enable"
      :selected="selected"
      :data="current"
      @submit="onEnableSubmit"
    />

    <DismountForm
      title="监测点拆除"
      :visible.sync="visible.dismount"
      :loading="loading.dismount"
      :selected="selected"
      @submit="onDismountSubmit"
    />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import BaseTable from '@/components/BaseTable/index.vue'
import QueryForm, { ILoading, IQuery } from './QueryForm.vue'
import PointForm from './PointForm/index.vue'
import EnableForm from './EnableForm.vue'
import DismountForm from './DismountForm.vue'
import { updatePoint, addPoint, deletePointBatch, pointPage, enablePointBatch, dismountPoint } from '../api/point'

import { getDefaultPagination } from '@/utils/constant'
import { pointCols } from '../utils'
import {
  IPoint,
  IDeviceType,
  ISection,
  ITeam,
  IPointDetail,
  IPointEnableParams,
  IPointDismountParams
} from '../api/common'
import { fetchDictionary, IDictionary, IPagination } from '@/api/common'
import { deviceTypePage } from '../api/deviceType'
import { sectionPage } from '../api/section'
import { teamPage } from '../api/team'

@Component({ name: 'Point', components: { BaseTable, QueryForm, PointForm, EnableForm, DismountForm } })
export default class Point extends Vue {
  @Prop({ type: Boolean, default: false }) isActive!: boolean
  pointCols = pointCols

  visible = { point: false, enable: false, dismount: false }

  current: Partial<IPoint> = {}

  selected: IPoint[] = []

  points: IPoint[] = []

  types: IDeviceType[] = []
  sections: ISection[] = []
  teams: ITeam[] = []

  loading: ILoading = {
    query: false,
    add: false,
    update: false,
    delete: false,
    enable: false,
    dismount: false,
    export: false
  }

  pagination: IPagination = getDefaultPagination()

  query: IQuery = {}
  levels: IDictionary[] = []
  onQuery(query) {
    this.query = { ...query }
    this.doQuery({ current: 1 })
  }

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

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

  async onSubmit(data: IPointDetail) {
    this.loading[data.id ? 'update' : 'add'] = true
    try {
      const { result } = await (data.id ? updatePoint(data) : addPoint(data))
      this.$message[result ? 'success' : 'error'](`${data.id ? '修改' : '新增'}监测点${result ? '成功!' : '失败!'}`)
      if (result) {
        this.visible.point = false
        this.doQuery()
      }
    } catch (error) {
      console.log(error)
    }
    this.loading[data.id ? 'update' : 'add'] = false
  }

  async onEnableSubmit(data: IPointEnableParams) {
    this.loading.enable = true
    try {
      const { result } = await enablePointBatch(data)
      this.$message[result ? 'success' : 'error'](
        `监测点${{ '1': '开启', '0': '关闭' }[String(data.runState)]}${result ? '成功!' : '失败!'}`
      )
      this.visible.enable = false
      result && this.doQuery()
    } catch (error) {
      console.log(error)
    }
    this.loading.enable = false
  }

  async onDismountSubmit(data: IPointDismountParams) {
    this.loading.dismount = true
    try {
      const { result } = await dismountPoint(data)
      this.$message[result ? 'success' : 'error'](`监测点拆卸${result ? '成功!' : '失败!'}`)
      this.visible.dismount = false
      result && this.doQuery()
    } catch (error) {
      console.log(error)
    }
    this.loading.dismount = false
  }

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

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

  onEnable() {
    this.current = {}
    this.visible.enable = true
  }

  onDismount() {
    this.current = {}
    this.visible.dismount = true
  }

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

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

  onDblClick(row) {
    this.current = { ...row }
    this.visible.point = 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)
    }
  }

  async getAllSections() {
    try {
      const {
        result: { records }
      } = await sectionPage({ current: 1, size: 9999 })
      this.sections = records || []
    } catch (error) {
      console.log(error)
    }
  }
  async getAllTeams() {
    try {
      const {
        result: { records }
      } = await teamPage({ current: 1, size: 9999 })
      this.teams = records || []
    } catch (error) {
      console.log(error)
    }
  }

  async getLevels() {
    try {
      const { result } = await fetchDictionary('0101')
      this.levels = result || []
    } catch (error) {
      console.log(error)
    }
  }

  preparing() {
    this.doQuery()
    this.getAllTypes()
    this.getAllSections()
    this.getAllTeams()
    this.getLevels()
  }

  mounted() {
    this.preparing()
  }

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