<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <template #title>
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <a-upload
                  :before-upload="importUseFileCity"
                  :showUploadList="false"
                  accept=".xls,.xlsx,.csv"
                >
                  市级在用导入
                </a-upload>
              </a-menu-item>
              <a-menu-item>
                <a-upload
                  :before-upload="importSpareFileCity"
                  :showUploadList="false"
                  accept=".xls,.xlsx,.csv"
                >
                  市级备用导入
                </a-upload>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>
            市级导入
            <DownOutlined />
          </a-button>
        </a-dropdown>

        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <a-upload
                  :before-upload="importUseFileCountyTop"
                  :showUploadList="false"
                  accept=".xls,.xlsx,.csv,.xlsm"
                >
                  县级在用导入
                </a-upload>
              </a-menu-item>
              <a-menu-item>
                <a-upload
                  :before-upload="importSpareFileCountyTop"
                  :showUploadList="false"
                  accept=".xls,.xlsx,.csv"
                >
                  县级备用导入
                </a-upload>
              </a-menu-item>
              <a-menu-item>
                <a-upload
                  :before-upload="importFileCountyBottom"
                  :showUploadList="false"
                  accept=".xls,.xlsx,.csv"
                >
                  县级地下水导入
                </a-upload>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button style="left: 30px">
            县级导入
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-dropdown>
          <template #overlay>
            <a-menu  style="word-spacing:10px;">
              <a-menu-item @click="download('市级（在用）地表水饮用水','xls')" > 市级（在用）地表水饮用水 </a-menu-item>
              <a-menu-item @click="download('市级（备用）地表水饮用水','xlsx')" > 市级（备用）地表水饮用水 </a-menu-item>
              <a-menu-item @click="download('县级（在用）地表水饮用水','xlsm')" > 县级（在用）地表水饮用水 </a-menu-item>
              <a-menu-item @click="download('县级（备用、规划）地表水饮用水','xls')"> 县级（备用、规划）地表水饮用水 </a-menu-item>
              <a-menu-item @click="download('县级地下水饮用水','xlsx')" > 县级地下水饮用水 </a-menu-item>
              <a-menu-item @click="download('各取水点取水量情况表','xlsx')" > 各取水点取水量取水量表 </a-menu-item>
            </a-menu>
          </template>
          <a-button  type="primary" style="left: 60px">
            模板下载
            <DownOutlined />
          </a-button>
        </a-dropdown>
      </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 { DownOutlined } from "@ant-design/icons-vue";
import { Modal } from "ant-design-vue";
import WaterBill from "./water-bill.vue";
import moment from "moment";
import { saveDrinkingWaterBill } from "@/api/ecology/drinking-water";
import {
  downloadTemplatexls,
  downloadTemplate,
  downloadTemplatexlsm,
} from "@/utils/excel-util";
export default {
  name: "DrinkWaterCollectIndex",
  components: {
    WaterBill,
    DownOutlined,
  },
  data() {
    return {
      activeKey: "water",
      time: moment(),
      year: new Date().getFullYear(),
    };
  },
  methods: {
    /* 导入市级在用地表水文件 */
    importUseFileCity(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 drinkingWaterList = aoa1.filter((item) => {
            return (
              item.length >= 80 && item[0] && !item[0].includes("点位名称")
            );
          });

          // 解析成对象数组
          const billName1 = file.name;
          const billData1 = utils.toCityUseTopWaterObjData(drinkingWaterList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveDrinkingWaterBill({
              billName: billName1,
              regionLevel: "市级",
              waterSourceType: 1,
              drinkingWaterType: 1,
              drinkingWaterList: billData1,
              // reportTime:  new Date(`${this.year}-01-01 00:00:00`).getTime(),
            })
              .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;
    },
    // 市级备用地表水
    importSpareFileCity(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 drinkingWaterList = aoa1.filter((item) => {
            return (
              item.length >= 60 && item[0] && !item[0].includes("点位名称")
            );
          });

          // 解析成对象数组
          const billName1 = file.name;
          const billData1 = utils.toCitySpareTopWaterObjData(drinkingWaterList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveDrinkingWaterBill({
              billName: billName1,
              regionLevel: "市级",
              waterSourceType: 1,
              drinkingWaterType: 2,
              drinkingWaterList: billData1,
              // reportTime:  new Date(`${this.year}-01-01 00:00:00`).getTime(),
            })
              .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: "数据上传出错1",
                  });
                }
              })
              .catch(() => {
                Modal.error({
                  title: "导入失败",
                  content: "数据上传出错2",
                });
              })
              .finally(() => {
                hide();
              });
          }
        } catch (error) {
          hide();
          Modal.error({
            title: "导入失败",
            content: error.message,
          });
          console.log(error);
        }
      };
      reader.readAsArrayBuffer(file);
      return false;
    },
    //县级在用地表水
    importUseFileCountyTop(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 drinkingWaterList = aoa1.filter((item) => {
            return (
              item.length >= 62 && item[0] && !item[0].includes("点位名称")
            );
          });

          // 解析成对象数组
          const billName1 = file.name;
          const billData1 = utils.toCountyUseTopWaterObjData(drinkingWaterList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveDrinkingWaterBill({
              billName: billName1,
              regionLevel: "县级",
              waterSourceType: 1,
              drinkingWaterType: 1,
              drinkingWaterList: billData1,
              // reportTime:  new Date(`${this.year}-01-01 00:00:00`).getTime(),
            })
              .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;
    },
    //县级备用地表水
    importSpareFileCountyTop(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 drinkingWaterList = aoa1.filter((item) => {
            return (
              item.length >= 80 && item[0] && !item[0].includes("点位名称")
            );
          });

          // 解析成对象数组
          const billName1 = file.name;
          const billData1 = utils.toCountyUseTopWaterObjData(drinkingWaterList);

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

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveDrinkingWaterBill({
              billName: billName1,
              regionLevel: "县级",
              waterSourceType: 1,
              drinkingWaterType: 2,
              drinkingWaterList: billData1,
              // reportTime:  new Date(`${this.year}-01-01 00:00:00`).getTime(),
            })
              .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;
    },
    //县级地下水
    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 drinkingWaterList = aoa1.filter((item) => {
            return (
              item.length >= 80 && item[0] && !item[0].includes("县域名称")
            );
          });

          // 解析成对象数组
          const billName1 = file.name;
          const billData1 =
          utils.toCountyUseBottomWaterObjData(drinkingWaterList);
          console.log(billData1);
          if (!billData1 || billData1.length == 0) {
            hide();
            Modal.error({
              title: "导入失败",
              content: "找不到可用数据",
            });

            return;
          }

          if (billData1.length > 0) {
            // 上传到服务器
            saveDrinkingWaterBill({
              billName: billName1,
              regionLevel: "县级",
              waterSourceType: 2,
              drinkingWaterType: 1,
              drinkingWaterList: billData1,
              // reportTime:  new Date(`${this.year}-01-01 00:00:00`).getTime(),
            })
              .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;
    },
    //下载文件
    download(filename, fileType) {
      if (fileType == "xls") {
        downloadTemplatexls(filename);
      } else if (fileType == "xlsm") {
        downloadTemplatexlsm(filename);
      } else if (fileType == "xlsx") {
        downloadTemplate(filename);
      }
    },
  },
};
</script>

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