<template>
  <tf-page>
    <template v-slot:action>
      <ForewarningHeader
        :kplaceholder="'支持编号、名称搜索'"
        :selected="selected"
        :actived="isActive"
        :loading="loading"
        :term="term"
        @search="onSearch"
        @import="onImport"
        @export="onExport"
      />
    </template>
    <tf-table :columns="tableCols" :data="tableData" v-loading="loading.search" @selection-change="onSelectionChange">
      <template v-slot:isShow="{ row }">
        <el-switch v-model="row.isShow" @change="changeInfo(row)"></el-switch>
      </template>
      <template v-slot:isValid="{ row }">
        <el-switch v-model="row.isValid" @change="changeInfo(row)"></el-switch>
      </template>
    </tf-table>
  </tf-page>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { getWarnInfoPage, editWarnInfo } from '../../commonAPI/request'
import ForewarningHeader from '../../components/ForewarningHeader.vue'
import { IFWIFTableColumns } from '../../commonAPI/settings'
import { ILoading, IForewarningSearchTerm } from '../../commonAPI/common'
import axios from '@/utils/request'
const exporUrl = '/tofly-sxgk/warningInfo/exportExcel'
const importUrl = '/tofly-sxgk/warningInfo/importExcel'
//预警指标管理
@Component({
  name: 'ForewarningInformation',
  components: { ForewarningHeader }
})
export default class ForewarningInformation extends Vue {
  visible: boolean = false

  isActive: boolean = false

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

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

  tableCols = IFWIFTableColumns

  tableData: any = []

  current: any = {}

  selected: any = []

  mounted() {
    this.isActive = true
  }
  onSearch(data?) {
    this.loading.search = true
    let params = {}
    if (data) {
      params = {
        keyword: data.keyword,
        concernExtent: data.attention
      }
    }
    getWarnInfoPage(params).then((res) => {
      try {
        this.tableData = res.result.records.map((item) => {
          Object.keys(item).forEach((val) => (item[val] = item[val] || '/'))
          return { ...item, isShow: item.isShow == '0' ? true : false, isValid: item.isValid == '0' ? true : false }
        })
      } catch (error) {
        console.log(error)
      }
      this.loading.search = false
    })
  }

  changeInfo(row) {
    for (const key in row) {
      if (row[key] == '/') {
        row[key] = ''
      }
    }
    this.onSubmit(row)
  }

  async onSubmit(data) {
    this.loading[data.id ? 'update' : 'add'] = true
    data['isShow'] = data['isShow'] ? '0' : '1'
    data['isValid'] = data['isValid'] ? '0' : '1'
    try {
      const { result } = await (data.id ? editWarnInfo({ ...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
  }

  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,
          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>