<template>
  <div class="ele-body">
    <a-card style="width: 100%" :bordered="false">
      <template #title>
        <a-select
          ref="select"
          v-model:value="regionLevel"
          style="width: 120px"
        >
          <a-select-option value="city">市</a-select-option>
          <a-select-option value="county">县</a-select-option>
        </a-select>
        <a-space>
          <a-upload
            :before-upload="importFileCity"
            :showUploadList="false"
            accept=".xls,.xlsx,.csv"
          >
            <a-button>数据导入</a-button>
          </a-upload>
          <a-button @click="download">模板下载</a-button>
        </a-space>
      </template>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane tab="降水信息" key="rain">
          <rain-bill ref="rain"></rain-bill>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script>
import XLSX from "xlsx";
import utils from "./utils";
import {Modal} from "ant-design-vue";
import RainBill from "./rain-bill.vue";
import {saveAcidRainBill} from "@/api/ecology/atmosphere/acid"
import {downloadTemplate} from "@/utils/excel-util";

export default {
  name: "RainCollectIndex",
  components: {
    RainBill,
  },
  data() {
    return {
      activeKey: "rain",
      regionLevel: "city",
    };
  },
  methods: {
    download() {
      let filename = "酸雨-"
      if (this.regionLevel == "city") {
        filename += "市"
      } else if (this.regionLevel == "county") {
        filename += "县"
      } else {
        filename += "站点"
      }
      downloadTemplate(filename)
    },
    /* 导入本地excel文件 */
    async importFileCity(file) {
      const hide = this.$message.loading("导入中..", 0);

      let reader = new FileReader();
      reader.onload = async (e) => {
        try {

          let data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, {
            type: "array",
          });
          let sheetNames = workbook.SheetNames;
          // 解析成二维数组
          let aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
            header: 1,
          });


          const acidList = aoa.filter((item) => {
            if (this.regionLevel == "city") {
              return item.length >= 20 && item[0] && !item[0].includes("编号");
            } else if (this.regionLevel == "county") {
              console.log(item.length,item[0])
              return item.length >= 27 && item[0] && item[0] != "行政代码";
            }
          });
          // 解析成对象数组
          const billName =file.name;
          let billData = undefined
          if (this.regionLevel == "city") {
            const reportDate = aoa[2][0].replace(/[^\d]+/g, "-");

            billData = await utils.toObjData(acidList, new Date(reportDate).getFullYear());
          } else if (this.regionLevel == "county") {
            billData = utils.toCountyObjData(acidList);
          }

          if (
            !billData ||
            billData.length == 0
            // (!billData2 || billData2.length == 0)
          ) {
            hide();
            Modal.error({
              title: "导入失败",
              content: "找不到数据",
            });
            return;
          }

          const tasks = [];
          if (billData.length > 0) {
            tasks.push(
              saveAcidRainBill({
                // reportTime: new Date(reportDate).getTime(),
                billName: billName,
                regionLevel: this.regionLevel == "city"?"市级":"县级",
                acidRainList: billData,
              })
            );
          }

          // 上传到服务器
          Promise.all(tasks)
            .then((res) => {
              if (res[0].data.code == 0) {
                Modal.success({
                  title: "导入成功",
                  content: `成功导入${billData.length}条数据`,
                });
                this.$refs.rain && this.$refs.rain.reload();
              } else {
                Modal.error({
                  title: "导入失败",
                  content: "数据上传出错",
                });
              }
            })
            .catch(() => {
              Modal.error({
                title: "导入失败",
                content: "数据上传出错",
              });
            })
            .finally(() => {
              hide();
            });
        } catch (error) {
          hide();
          Modal.error({
            title: "导入失败",
            content: error.message,
          });
        }
        // console.log(billData);
      };
      reader.readAsArrayBuffer(file);

      return false;
    },
  },
};
</script>

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