<template>
  <el-button @click="onDownload" :disabled="props.disabled" class="mr5" v-loading="loading">{{ props.label }}
  </el-button>
</template>

<script setup>
import { nextTick, ref, getCurrentInstance } from "vue"
import FileSaver from "file-saver"
import * as XLSX from "xlsx"
import * as XLSXStyle from "xlsx-style"
import { getApi, postApi, uploadExcel } from "@/api/tobAcco_api.js"
import axios from "axios"
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const { D_BZ_CLYT_ZH, D_BZ_CLYT_ZK } = proxy.$dict("D_BZ_CLYT_ZH", "D_BZ_CLYT_ZK")
const props = defineProps({
  debug: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  options: {
    type: Object,
    default: {
      url: "",
      name: ""
    }
  },
  label: {
    type: String,
    default: "导出数据"
  }
})
const loading = ref(false)
const onDownload = () => {
  // console.log(8888, props.options)
  loading.value = true
  const s2ab = s => {
    var buf = new ArrayBuffer(s.length)
    var view = new Uint8Array(buf)
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  }
  postApi(props.options.params, `/mosty-jcgl${props.options.url}`).then(res => {
    let tables = []

    // if (props.debug) {
    console.log("data", res)
    console.log("columns", props.options.columns)
    console.log(D_BZ_CLYT_ZH.value.find(item => item.value == '1').label, 'D_BZ_CLYT_ZH')
    // }
    if (props.options.url === "/data/Car/getAllList") {
      res.forEach(item => {
        if (item.cdMotorCarTypeCode.charAt(0) == '1') {
          item.cdMotorCarUsageName = D_BZ_CLYT_ZH.value.find(i => i.value == item.cdMotorCarUsageCode).label
        } else {
          item.cdMotorCarUsageName = D_BZ_CLYT_ZK.value.find(i => i.value == item.cdMotorCarUsageCode).label
        }
      })
    }
    let tableData = ref([])
    if (props.options.url === "/data/rpInfo/getAllList") {
      res.forEach(item => {
        item.rpTypeList.forEach(list => {
          list.rpName = item.rpName
          tableData.value.push(list)
        })
        if (item.rpTypeList.length === 0) {
          tableData.value.push(item)
        }
      })
      res = tableData.value
    }
    if (props.options.url === "/data/hazardPlace/getAllList") {
      res.forEach(item => {
        item.detectionLedgerList.forEach(list => {
          list.placeName = item.placeName
          list.status = item.status
          tableData.value.push(list)
        })
        if (item.detectionLedgerList.length === 0) {
          tableData.value.push(item)
        }
      })
      res = tableData.value
    }
    if (props.options.url === "/data/emergencyPlanInfo/getAllList" && props.options.name === "应急演练") {
      res.forEach(item => {
        item.drills.forEach(list => {
          list.accidentCategoryName = item.accidentCategoryName
          list.emergencyPlanCategoryName = item.emergencyPlanCategoryName
          list.sourceId = item.sourceId
          tableData.value.push(list)
        })
        item.actualDrillQty = item.actualDrillQty || 0
        item.actualDrillPersonQty = item.actualDrillPersonQty || 0
        item.desktopDeducQty = item.desktopDeducQty || 0
        item.desktopDeducPersonQty = item.desktopDeducPersonQty || 0
        item.emergencyDrillEvaluationQty = item.emergencyDrillEvaluationQty || 0
        if (item.drills.length === 0) {
          tableData.value.push(item)
        }
      })
      res = tableData.value
    }

    let isBooleans = [
      "secProtocolFlag",
      "qualificationFlag",
      "permanenFlag",
      "involveHazardQpsFlag",
      "riskEnterpriseHeadFlag",
      "cmHighlyToxicFlag",
      "cmEasyMakeToxicFlag",
      "cmEasyMakeExplosiveFlag",
      "cmMajorHazardFlag",
      "cmHazchemListFlag",
      "cmHazardProcessFlag",
      "cdMotorCarNewEnergyCarFlag",
      "safetyMemberFlag",
      "seFlag"
    ]

    // return
    if (res.length > 0) {
      res.forEach(item => {
        // item.baOrgName = "庆阳市烟草专卖局（公司）" //debug
        let arr = []
        props.options.columns.forEach(key => {
          if (isBooleans.includes(key)) {
            item[key] = item[key] === 1 ? "是" : "否"
          }
          // if (key === "cdMotorCarUseStateCode") {
          //   item[key] = item[key] === '1' ? "在用" : "已废弃"
          // }

          arr.push(item[key])
        })
        tables.push(arr)
      })
    }
    loading.value = false
    if (tables.length > 0) exportAsExcel(tables)
    else
      ElMessage({
        message: "暂无数据",
        type: "warning"
      })
  })

  const exportAsExcel = tables => {
    axios({
      method: "get",
      url: `./reportTemplate/${props.options.name}.xlsx`,
      responseType: "arraybuffer"
    }).then(res => {
      const workbook = XLSX.read(Buffer.from(res.data), { type: "buffer" })
      const worksheet = workbook.Sheets[workbook.SheetNames[1]]
      // console.log(999, worksheet)
      const jsonData = XLSX.utils.sheet_to_json(worksheet)

      let keys = Object.keys(jsonData[0]).filter(item => item.includes("__"))

      // let tables = [
      //   ["庆阳市烟草专卖局（公司）", "a", "2024-10-09", "物体打击", "责任事故", "1", "2", "3", "4"],
      //   ["庆阳市烟草专卖局（公司）", "b", "2024-10-10", "物体打击", "责任事故", "11", "22", "33", "44"],
      //   ["庆阳市烟草专卖局（公司）", "c", "2024-10-11", "物体打击", "责任事故", "111", "222", "333", "444"]
      // ]
      tables.forEach(table => {
        let obj = {}

        for (let i = 0; i < keys.length; i++) {
          // obj[keys[i]] = table[i] && table[i] !== 0 ? table[i] : ""
          obj[keys[i]] = table[i] === 0 ? 0 : table[i] === null ? "" : table[i]
        }

        jsonData.push(obj)
      })

      workbook.Sheets[workbook.SheetNames[1]] = XLSX.utils.json_to_sheet(jsonData)
      workbook.Sheets[workbook.SheetNames[1]]["!merges"] = worksheet["!merges"]
      if (props.debug) {
        console.log("jsonData", jsonData)
        return
      }

      let wbout = XLSXStyle.write(workbook, {
        bookType: "xlsx",
        bookSST: true,
        type: "binary"
      })
      try {
        FileSaver.saveAs(
          new Blob([s2ab(wbout)], {
            type: 'application/octet-stream;charset=utf-8"'
          }),
          props.options.name + ".xlsx"
        )
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout)
      }
    })
  }
}
</script>

<style lang="scss" scoped></style>
