<template>
  <div class="table-wrapper">
    <header ref="tableWrapperHeader" class="table-header-wrapper">
      <SecurityCheckHeader
        title="航线货物关联统计"
        @change="changeHandler"
        @search="searchHandler"
        mode="combobox"
        selectPlaceholder="目的地"
        :optionLists="destination"
        @exportex="exportex"
      />
    </header>
    <main>
      <SecurityCheckTable
        id="1"
        :footerDate="footerDate"
        :table-cols="tableCols"
        :table-data="tableData"
        row-key="index"
        :height="tableHeight"
        show-summary
        :pagination="false"
        :loading="loading"
      />
    </main>
  </div>
</template>

<script>
import SecurityCheckHeader from '../components/securityCheckHeader.vue'
import SecurityCheckTable from '../components/securityCheckTable.vue'
import { agent, routeall } from '@/api/statistics/statistics.js'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  components: { SecurityCheckHeader, SecurityCheckTable },
  data() {
    return {
      destination: [],
      loading: false,
      tableHeight: '550',
      tableCols: [
        {
          title: '目的地',
          dataIndex: 'flightLine',
          key: 'flightLine',
        },
        {
          dataIndex: 'count',
          key: 'count',
          title: '总件数',
          clickHandler: (row, rowIndex) => {
            this.$router.push({
              path: '/securityCheck/waybillTable',
              query: {
                startTime: this.FormData.beginDate,
                endTime: this.FormData.endDate,
                destination: row.flightLine,
                agentCode: this.FormData.proxyId,
                riskRating: '',
                openResult: '',
              },
            })
          },
        },
        {
          dataIndex: 'highRisk',
          key: 'highRisk',
          title: '普通',
          children: [
            {
              dataIndex: 'highRiskcount',
              key: 'highRiskcount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: '/securityCheck/waybillTable',
                  query: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '普通',
                  },
                })
              },
            },
            {
              dataIndex: 'mix',
              key: 'mix',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'lowRisk',
          key: 'lowRisk',
          title: '严控',
          children: [
            {
              dataIndex: 'lowRiskCount',
              key: 'lowRiskCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: '/securityCheck/waybillTable',
                  query: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '严控',
                  },
                })
              },
            },
            {
              dataIndex: 'lowRiskRatio',
              key: 'lowRiskRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'priority',
          key: 'priority',
          prop: 'priority',
          title: '低风险',
          children: [
            {
              dataIndex: 'priorityCount',
              key: 'priorityCount',
              prop: 'priorityCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: '/securityCheck/waybillTable',
                  query: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '低风险',
                  },
                })
              },
            },
            {
              dataIndex: 'priorityRatio',
              key: 'priorityRatio',
              prop: 'priorityRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'normal',
          key: 'normal',
          prop: 'normal',
          title: '优先',
          children: [
            {
              dataIndex: 'normalCount',
              key: 'normalCount',
              prop: 'normalCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: '/securityCheck/waybillTable',
                  query: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '优先',
                  },
                })
              },
            },
            {
              dataIndex: 'normalRatio',
              key: 'normalRatio',
              prop: 'normalRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'strict',
          key: 'strict',
          prop: 'strict',
          title: '高风险',
          children: [
            {
              dataIndex: 'strictCount',
              key: 'strictCount',
              prop: 'strictCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: '/securityCheck/waybillTable',
                  query: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '高风险',
                  },
                })
              },
            },
            {
              dataIndex: 'strictRatio',
              key: 'strictRatio',
              prop: 'strictRatio',
              title: '占比',
            },
          ],
        },
      ],
      tableData: [],
      footerDate: [
        {
          flightLine: '合计',
          highRiskcount: '',
          lowRiskCount: '',
          priorityCount: '',
          normalCount: '',
          strictCount: '',
        },
      ],
      FormData: {
        beginDate: '',
        endDate: '',
        places: [],
        proxyId: '',
      },
    }
  },
  created() {
    this.formatDate()
  },
  mounted() {
    if (Object.keys(this.$route.query).length !== 0) {
      const { beginDate, endDate, places, proxyId } = this.$route.query
      this.FormData.beginDate = beginDate
      this.FormData.endDate = endDate
      if (typeof places == 'string') {
        this.FormData.places = [places]
      } else {
        this.FormData.places = places
      }
      this.FormData.proxyId = proxyId
    }
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
    this.routdata()
    this.getData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight)
  },
  methods: {
    async exportex() {
      // let that = this;
      // this.$confirm({
      //   title: "是否确认导出",
      //   content: "此操作将导出当前条件下所有数据而非选中数据",
      //   onOk() {
      //     return agentexcl(this.FormData).then((response) => {
      //       that.download(response.msg);
      //       that.$message.success("导出成功", 3);
      //     });
      //   },
      // });
      this.downFile()
    },
    //导出
    downlodTable() {
      this.$confirm('是否需要导出xlsx文档, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.downFile()
          this.$message({
            type: 'success',
            message: '导出成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出',
          })
        })
    },
    downFile() {
      var wb = XLSX.utils.table_to_book(document.querySelector('#table1'))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream',
          }),
          '航线货物关联统计.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    formatDate() {
      let date = new Date()
      let myyear = date.getFullYear()
      let mymonth = date.getMonth() + 1
      let myweekday = date.getDate()
      mymonth < 10 ? (mymonth = '0' + mymonth) : mymonth
      myweekday < 10 ? (myweekday = '0' + myweekday) : myweekday
      this.FormData.beginDate = `${myyear}-${mymonth}-${myweekday}`
      this.FormData.endDate = `${myyear}-${mymonth}-${myweekday}`
    },
    async routdata() {
      try {
        const result = await routeall({})
        if (result.status == 200) {
          this.destination = []
          result.data.forEach((element) => {
            let obj = {
              name: element,
              lable: element,
            }
            this.destination.push(obj)
          })
          this.destination.sort(this.up)
        }
      } catch (error) {
        console.log(error)
      }
    },
    up(x, y) {
      return x.lable.charCodeAt(0) - y.lable.charCodeAt(0)
    },
    //接口数据
    async getData() {
      try {
        this.loading = true
        const result = await agent(this.FormData)
        if (result.status === 200) {
          this.tableData = result.data
          this.tableData.forEach((item) => {
            let arr = [{}, {}, {}, {}, {}]
            item.datas.forEach((data) => {
              data['mix'] = Math.floor((data.count / item.count) * 100) + '%'
              if (data.level == '普通') {
                arr[3] = data
              }
              if (data.level == '严控') {
                arr[1] = data
              }
              if (data.level == '低风险') {
                arr[2] = data
              }
              if (data.level == '优先') {
                arr[4] = data
              }
              if (data.level == '高风险') {
                arr[0] = data
              }
            })
            item.datas = arr
          })
          if (this.tableData.length > 0) {
            for (let i = 0; i < this.tableData[0].datas.length; i++) {
              this.tableCols.forEach((item) => {
                if (item.title == this.tableData[0].datas[i].level) {
                  item.prop = 'datas'
                  item.children[0].dataIndex = 'datas[' + i + '].count'
                  item.children[0].prop = 'datas[' + i + '].count'
                  item.children[1].dataIndex = 'datas[' + i + '].mix'
                }
              })
            }
          }
          let count = []
          let highRiskcount = []
          let lowRiskCount = []
          let priorityCount = []
          let normalCount = []
          let strictCount = []
          result.data.forEach((res) => {
            res.count ? count.push(res.count) : count.push(0)
            res.datas.forEach((re) => {
              if (re.level == '普通') {
                highRiskcount.push(re.count)
              } else if (re.level == '严控') {
                lowRiskCount.push(re.count)
              } else if (re.level == '低风险') {
                priorityCount.push(re.count)
              } else if (re.level == '优先') {
                normalCount.push(re.count)
              } else if (re.level == '高风险') {
                strictCount.push(re.count)
              }
            })
          })
          console.log(this.tableCols)
          this.footerDate[0] = {
            flightLine: '合计',
            count: eval(count.join('+')),
            'datas[3].count': eval(highRiskcount.join('+')),
            'datas[1].count': eval(lowRiskCount.join('+')),
            'datas[2].count': eval(priorityCount.join('+')),
            'datas[4].count': eval(normalCount.join('+')),
            'datas[0].count': eval(strictCount.join('+')),
          }
          this.loading = false
        }
      } catch (error) {
        console.log(error)
      }
    },
    changeHandler() {
      let param = JSON.parse(JSON.stringify(this.FormData))
      param.places = param.places[0]
      this.$router.push({
        path: './cargoCharts',
        query: this.FormData,
      })
    },
    searchHandler(arr) {
      if (typeof arr[1] == 'string' && arr[1] == '') {
        arr[1] = []
      }
      if (typeof arr[1] == 'string' && arr[1] != '') {
        arr[1] = [arr[1]]
      }
      this.FormData.beginDate = arr[0][0]
      this.FormData.endDate = arr[0][1]
      this.FormData.places = arr[1]
      this.FormData.proxyId = arr[2]
      this.getData()
    },
    setTableHeight() {
      const topBarHeight = 80
      const headerHeight = this.$refs['tableWrapperHeader'].offsetHeight
      const footerBlackHeight = 24
      this.tableHeight = `calc(100vh - ${topBarHeight + headerHeight + footerBlackHeight}px)`
    },
  },
}
</script>

<style lang="scss" scoped>
.table-wrapper {
  padding: 0 24px;
  background: #dfe3ea;
  .table-header-wrapper {
    // padding-top: 24px;
  }
}
</style>
