<template>
  <tf-page>
    <template v-slot:action>
      <ActionHeader
        :kplaceholder="'支持指标名称搜索'"
        :selected="selected"
        :actived="isActive"
        :loading="loading"
        @search="onSearch"
        @add="onAdd"
        @del="onDelete"
        @import="onImport"
        @export="onExport"
      />
    </template>
    <tf-table :columns="tableCols" :data="tableData" v-loading="loading.search" @selection-change="onSelectionChange">
      <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>
    <IndexForm
      :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 { getIndexList, addIndexData, editIndexData, deleteIndexDataById, deleteIndexData } from '../commonAPI/request'
import ActionHeader from '../components/ActionHeader.vue'
import { IMTableColumns } from '../commonAPI/settings'
import { ILoading } from '../commonAPI/common'
import IndexForm from './IndexForm.vue'
import axios from '@/utils/request'
const exporUrl = '/tofly-sxgk/bigScreenData/exportExcel'
const importUrl = '/tofly-sxgk/bigScreenData/importExcel'
//指标管理
@Component({
  name: 'IndexManagement',
  components: { ActionHeader, IndexForm }
})
export default class IndexManagement extends Vue {
  visible: boolean = false

  isActive: boolean = false

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

  tableCols = IMTableColumns

  tableData: any = []

  current: any = {}

  selected: any = []

  mounted() {
    this.isActive = true
  }
  onSearch(data?) {
    this.loading.search = true
    let params = {}
    if (data) {
      params = {
        indexName: data ? data.keyword : ''
      }
      params['isNew'] = data.islatest ? 1 : 0
      // if (data.latest) {
      //   params['isNew'] = 1
      // }
      // if (data.notlatest) {
      //   params['isNew'] = 0
      // }
      // if (data.latest && data.notlatest) {
      //   delete params['isNew']
      // }
    }
    getIndexList(params).then((res) => {
      try {
        this.tableData = res.result.map((item) => {
          Object.keys(item).forEach((val) => (item[val] = item[val] || '/'))
          return { ...item, source: item.source == '1' ? '本地导入' : '人工', isNew: item.isNew == '1' ? '是' : '否' }
        })
      } catch (error) {
        console.log(error)
      }
      this.loading.search = false
    })
  }
  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 deleteIndexDataById({ 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
    data['isNew'] = data['isNew'] == '是' ? 1 : 0
    data['source'] = '人工'
    try {
      const { result } = await (data.id ? editIndexData({ ...data }) : addIndexData({ ...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 deleteIndexData({ 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: { isNew: 1, indexName: data ? data.keyword : '' },
        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>