<template>
  <div class="ele-body">
    <a-card style="width: 100%" :bordered="false">
      <template #title>
        <a-space>
          <a-upload
            :before-upload="importFileCity"
            :showUploadList="false"
            accept=".xls,.xlsx,.csv"
          >
            <a-button>市级地表水导入</a-button>
          </a-upload>
          <a-upload
            :before-upload="importFileCountyTop"
            :showUploadList="false"
            accept=".xls,.xlsx,.csv"
          >
            <a-button>县级地表水导入</a-button>
          </a-upload>
          <a-upload
            :before-upload="importFileCountyBottom"
            :showUploadList="false"
            accept=".xls,.xlsx,.csv"
          >
            <a-button>县级地下水导入</a-button>
          </a-upload>
        </a-space>
      </template>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane tab="噪声信息" key="water">
          <water-bill ref="water"></water-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 WaterBill from "./water-bill.vue";
import { saveWaterFunctionAreaBill } from "@/api/ecology/water-function-area";
export default {
  name: "RiverFunctionCollectIndex",
  components: {
    WaterBill,
  },
  data() {
    return {
      activeKey: "water",
    };
  },
  methods: {
    /* 导入本地excel文件 */
    importFileCity(file) {
      const hide = this.$message.loading("导入中..", 0);

      let reader = new FileReader();
      reader.onload = (e) => {
        try {
          let data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, {
            type: "array",
          });
          //0.昼间数据 1.地表水 2.备用水
          let sheetNames = workbook.SheetNames;
          // 解析成二维数组
          let aoa1 = XLSX.utils.sheet_to_json(
            workbook.Sheets["地表水数据录入表"],
            {
              header: 1,
            }
          );
          let aoa2 = XLSX.utils.sheet_to_json(
            workbook.Sheets["备用水源数据录入表"],
            {
              header: 1,
            }
          );
          console.log(sheetNames);
          const reportDate1 = aoa1[2][0].replace(/[^\d]+/g, "-");
          const reportDate2 = aoa2[2][0].replace(/[^\d]+/g, "-");

          const waterFunctionAreaList = aoa1.filter((item) => {
            return (
              item.length >= 100 && item[0] && !item[0].includes("点位名称")
            );
          });
          const waterFunctionAreaList2 = aoa2.filter((item) => {
            return (
              item.length >= 100 && item[0] && !item[0].includes("点位名称")
            );
          });

          // 解析成对象数组
          const billName1 = aoa1[0][0] + aoa1[1][0];
          const billData1 = utils.toCityUseTopWaterObjData(waterFunctionAreaList);
          const billName2 = aoa2[0][0] + aoa2[1][0];
          const billData2 =
            utils.toCitySpareTopWaterObjData(waterFunctionAreaList2);

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

          const tasks = [];
          if (billData1.length > 0) {
            tasks.push(
              saveWaterFunctionAreaBill({
                reportTime: new Date(reportDate1).getTime(),
                billName: billName1,
                regionLevel: "市级",
                waterSourceType: 1,
                waterFunctionAreaType: 1,
                waterFunctionAreaList: billData1,
              })
            );
          }

          if (billData2.length > 0) {
            tasks.push(
              saveWaterFunctionAreaBill({
                reportTime: new Date(reportDate2).getTime(),
                billName: billName2,
                regionLevel: "市级",
                waterSourceType: 1,
                waterFunctionAreaType: 2,
                waterFunctionAreaList: billData2,
              })
            );
          }

          // 上传到服务器

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

      return false;
    },
    importFileCountyTop(file) {
      const hide = this.$message.loading("导入中..", 0);

      let reader = new FileReader();

      reader.onload = (e) => {
        try {
          let data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, {
            type: "array",
          });
          //0.昼间数据 1.夜间数据 2.其他信息
          // let sheetNames = workbook.SheetNames;
          // 解析成二维数组
          let aoa1 = XLSX.utils.sheet_to_json(workbook.Sheets["地表水数据录入表"], {
            header: 1,
          });

          const reportDate = aoa1[1][0].replace(/[^\d]+/g, "-");
          const waterFunctionAreaList = aoa1.filter((item) => {
            return item.length >= 100 && item[0] && item[0] != "点位名称";
          });

          // 解析成对象数组
          const billName1 = aoa1[0][0];
          const billData1 = utils.toCountyUseTopWaterObjData(waterFunctionAreaList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveWaterFunctionAreaBill({
              reportTime: new Date(reportDate).getTime(),
              billName: billName1,
              regionLevel: "县级",
              waterSourceType: 1,
              waterFunctionAreaType: 2,
              waterFunctionAreaList: billData1,
            })
              .then((res) => {
                if (res.data.code == 0) {
                  Modal.success({
                    title: "导入成功",
                    content: `成功导入${billData1.length}条数据`,
                  });
                  this.$refs.water && this.$refs.water.reload();
                } else {
                  Modal.error({
                    title: "导入失败",
                    content: "数据上传出错",
                  });
                }
              })
              .catch(() => {
                Modal.error({
                  title: "导入失败",
                  content: "数据上传出错",
                });
              })
              .finally(() => {
                hide();
              });
          }
        } catch (error) {
          hide();
          Modal.error({
            title: "导入失败",
            content: error.message,
          });
        }
        // console.log(billData1);
      };
      reader.readAsArrayBuffer(file);
      return false;
    },
    importFileCountyBottom(file) {
      const hide = this.$message.loading("导入中..", 0);

      let reader = new FileReader();

      reader.onload = (e) => {
        try {
          let data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, {
            type: "array",
          });
          //0.昼间数据 1.夜间数据 2.其他信息
          // let sheetNames = workbook.SheetNames;
          // 解析成二维数组
          let aoa1 = XLSX.utils.sheet_to_json(workbook.Sheets["县级地下水录入版"], {
            header: 1,
          });

          const waterFunctionAreaList = aoa1.filter((item) => {
            return item.length >= 80 && item[0] && !item[0].includes("县域名称");
          });

          // 解析成对象数组
          const billName1 = aoa1[0][1];
          const billData1 = utils.toCountyUseBottomWaterObjData(waterFunctionAreaList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveWaterFunctionAreaBill({
              billName: billName1,
              regionLevel: "县级",
              waterSourceType: 2,
              waterFunctionAreaType: 2,
              waterFunctionAreaList: billData1,
            })
              .then((res) => {
                if (res.data.code == 0) {
                  Modal.success({
                    title: "导入成功",
                    content: `成功导入${billData1.length}条数据`,
                  });
                  this.$refs.water && this.$refs.water.reload();
                } else {
                  Modal.error({
                    title: "导入失败",
                    content: "数据上传出错",
                  });
                }
              })
              .catch(() => {
                Modal.error({
                  title: "导入失败",
                  content: "数据上传出错",
                });
              })
              .finally(() => {
                hide();
              });
          }
        } catch (error) {
          hide();
          Modal.error({
            title: "导入失败",
            content: error.message,
          });
          console.log(error);

        }
      };
      reader.readAsArrayBuffer(file);
      return false;
    },
  },
};
</script>

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