<template>
  <tf-page>
    <template v-slot:action>
      <ForewarningHeader
        :kplaceholder="'支持预警分组、名称搜索'"
        :selected="selected"
        :actived="isActive"
        :loading="loading"
        :term="term"
        @search="onSearch"
        @add="onAdd"
        @del="onDelete"
        @import="onImport"
        @export="onExport"
      />
    </template>
    <tf-table
      :columns="tableCols"
      :data="tableData"
      :pagination="pagination"
      v-loading="loading.search"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
    >
      <template v-slot:operation="{ row }">
        <el-button type="text" style="padding: 0" @click="editor(row)">编辑</el-button>
        <el-button type="text" style="padding: 0" @click="remove(row)">删除</el-button>
      </template>
    </tf-table>
    <EditForm
      :visible.sync="visible"
      :loading="loading.add || loading.update"
      :data="current"
      :title="`${current.id ? '编辑' : '新增'}`"
      @submit="onSubmit"
    />
  </tf-page>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { getDefaultPagination } from '@/utils/constant'
import { IPagination } from '@/api/common'
import {
  getWarnIndexThresholdPage,
  addWarnIndexThreshold,
  editWarnIndexThreshold,
  deleteWarningIndexThresholdById,
  deleteWarningIndexThreshold
} from '../../commonAPI/request'
import ForewarningHeader from '../../components/ForewarningHeader.vue'
import { IFWITTableColumns } from '../../commonAPI/settings'
import { ILoading, IForewarningSearchTerm } from '../../commonAPI/common'
import EditForm from './EditForm.vue'
import axios from '@/utils/request'
const exporUrl = '/tofly-sxgk/indexThreshold/exportExcel'
const importUrl = '/tofly-sxgk/indexThreshold/importExcel'
//预警指标阈值管理
@Component({
  name: 'ForewarningIndexThreshold',
  components: { ForewarningHeader, EditForm }
})
export default class ForewarningIndexThreshold extends Vue {
  visible: boolean = false

  isActive: boolean = false

  loading: ILoading = { search: false, add: false, update: false, delete: false, import: false, export: false }

  pagination: IPagination = getDefaultPagination()

  term: IForewarningSearchTerm = { method: false, type: true, attention: true, edit: true }

  tableCols = IFWITTableColumns

  tableData: any = []

  current: any = {}

  selected: any = []

  mounted() {
    this.isActive = true
  }
  onSearch(data?) {
    this.loading.search = true
    let params = {}
    if (data) {
      params = {
        keyword: data.keyword,
        warningType: data.type,
        concernExtent: data.attention
      }
    }
    params = { ...params, ...this.pagination }
    getWarnIndexThresholdPage(params).then((res) => {
      try {
        const { records, size, total, current } = res.result
        this.tableData = records.map((item) => {
          Object.keys(item).forEach((val) => (item[val] = item[val] || '/'))
          return { ...item }
        })
        this.pagination = { current, size, total }
      } catch (error) {
        console.log(error)
      }
      this.loading.search = false
    })
  }
  onPageChange(pagination) {
    this.pagination = { ...this.pagination, ...pagination }
    this.onSearch()
  }
  onAdd() {
    this.current = {}
    this.visible = true
  }
  editor(row) {
    this.current = { ...row }
    this.visible = true
  }
  async remove(row) {
    await this.$confirm(`是否确认删除此项指标？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    this.loading.delete = true
    try {
      const { result } = await deleteWarningIndexThresholdById({ id: row.id })
      this.$message[result ? 'success' : 'error'](`删除指标${result ? '成功!' : '失败!'}`)
      result && this.onSearch()
    } catch (error) {
      console.log(error)
    }
    this.loading.delete = false
  }

  async onSubmit(data) {
    this.loading[data.id ? 'update' : 'add'] = true
    try {
      const { result } = await (data.id ? editWarnIndexThreshold({ ...data }) : addWarnIndexThreshold({ ...data }))
      this.$message[result ? 'success' : 'error'](`${data.id ? '修改' : '新增'}指标阈值${result ? '成功!' : '失败!'}`)
      if (result) {
        this.visible = false
        this.onSearch()
      }
    } catch (error) {
      console.log(error)
    }
    this.loading[data.id ? 'update' : 'add'] = false
  }

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

  onImport(data) {
    this.loading.import = true
    axios
      .request({
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'bearer ' + sessionStorage.getItem('token')
        },
        method: 'post',
        url: importUrl,
        data: { file: data.file }
      })
      .then((res) => {
        this.$message[res.code === 1 ? 'success' : 'error'](`数据导入${res.code === 1 ? '成功!' : '失败!'}`)
        this.onSearch()
        this.loading.import = false
      })
      .catch((err) => {
        console.log(err)
      })
  }

  onExport(data) {
    this.loading.export = true
    axios
      .request({
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          Authorization: 'bearer ' + sessionStorage.getItem('token')
        },
        method: 'get',
        url: exporUrl,
        params: {
          keyword: data.keyword,
          warningType: data.type,
          concernExtent: data.attention
        },
        responseType: 'blob'
      })
      .then((res) => {
        var blob = res
        let binaryData = []
        binaryData.push(blob)
        const href = window.URL.createObjectURL(new Blob(binaryData)) // 创建新的URL表示指定的blob对象
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = href // 指定下载链接
        a.download = '预警指标阈值数据.xls' // 指定下载文件名
        a.click()
        this.loading.export = false
      })
      .catch((err) => {
        console.log(err)
        this.loading.export = false
      })
  }

  onSelectionChange(selections) {
    this.selected = [...selections]
  }
}
</script>

<style lang='scss' scoped>
/deep/ .el-table__fixed-right-patch {
  background-color: transparent;
}
</style>