<template>
  <div class="ele-body">
    <a-card style="width: 100%" :bordered="false">
      <template #title>
        <a-dropdown>
          <a-upload :before-upload="importFileCity" :showUploadList="false" accept=".xls,.xlsx,.csv">
            <a-button>江河导入</a-button>
          </a-upload>
        </a-dropdown>
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <a-upload :before-upload="importFileFunctionArea" @change="currentVal(1)" :showUploadList="false"
                  accept=".xls,.xlsx,.csv">
                  国家级水功能
                </a-upload>
              </a-menu-item>
              <a-menu-item>
                <a-upload :before-upload="importFileFunctionArea" @change="currentVal(2)" :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 @click="handleMenuClick">
              <a-menu-item v-for="item in form" :key="item.waterStationPointId">
                {{ item.stationName }}
                <a-upload :before-upload="importFileStation" @change="currentSel(item)" :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 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('水功能区-自治区级水站月均值数据表','xls')"> 水功能区-自治区级水站月均值数据表</a-menu-item>
              <a-menu-item @click="download('水站-国家级水站历史数据表','xlsx')"> 水站-国家级水站历史数据表</a-menu-item>
              <a-menu-item @click="download('水站-自治区级水站均值数据报表','xlsx')" style="word-spacing:3px">水站-自治区级水站均值数据报表
              </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-tab-pane tab="水功能区" key="functionWater">
          <function-bill ref="functionWater"></function-bill>
        </a-tab-pane>
        <a-tab-pane tab="水站" key="station">
          <station-bill ref="station"></station-bill>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <a-modal v-model:visible="visibleConfirm" ok-text="确认" cancel-text="取消" @ok="hideModal" title="confirmTitle">
    </a-modal>
  </div>
</template>

<script>
  import XLSX from "xlsx";
  import utils from "./utils";
  import {
    Modal
  } from "ant-design-vue";
  import WaterBill from "./water-bill.vue";
  import FunctionBill from "../../water-function-area/collect/water-bill"
  import StationBill from "../../river-station/collect/water-bill"
  import {
    DownOutlined
  } from "@ant-design/icons-vue";
  import {
    saveWaterFunctionAreaBill,
    saveJudgeInfoWater,
  } from "@/api/ecology/water-function-area"
  import {
    saveRiverBill,
    saveJudgeInfo,
  } from "@/api/ecology/river";
  import {
    saveRiverStationBill,
    saveJudgeInfoStation,
  } from "@/api/ecology/river-station";

  import {
    listInfo
  } from "@/api/ecology/water/river-water";

  import {
    saveRiverSiteBill,
    saveJudgeInfoSite,
  } from "@/api/ecology/river-site";
  import {
    downloadTemplatexls,
    downloadTemplate
  } from "@/utils/excel-util";
  export default {
    name: "RiverCollectIndex",

    components: {
      WaterBill,
      FunctionBill,
      DownOutlined,
      StationBill
    },
    data() {
      return {
        activeKey: "functionWater",
        visible: false,
        exportType: String,
        visibleWater: false,
        visibleConfirm: false,
        confirmTitle: String,
        form: [],
        param: {}
      };
    },
    created() {
      this.form = [];
      listInfo().then((res) => {
        if (res.data.code == 0) {
          console.log(res.data.data)
          this.visibleWater = true;
          res.data.data.forEach(e => {
            this.form.push(e);
          });
          console.log("this.form" + this.form[0].stationName)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },


    methods: {
      showModalWater() {
        listInfo().then((res) => {
          if (res.data.code == 0) {
            console.log(res.data.data)
            this.visibleWater = true;
            this.form = res.data.data
            console.log("this.form" + this.form.stationName)
          } else {
            this.$message.error(res.data.msg);
          }
        })
      },
      //模板下载
      download(filename, fileType) {
        if (fileType == "xls") {
          downloadTemplatexls(filename);
        } else if (fileType == "xlsx") {
          downloadTemplate(filename);
        }
      },
      currentSel(selVal) {
        this.param.waterStationPointId = selVal.waterStationPointId;
        this.param.riverName = selVal.riverName;
        this.param.stationName = selVal.stationName;
        this.param.system = selVal.system;
        this.param.waterTarget = selVal.waterTarget;
      },
      currentVal(val) {
        this.exportType = val;
      },
      showModal() {
        this.visible = true;
      },
      // hideModal() {
      //   saveRiverBill({
      //     reportTime: new Date(reportDate).getTime(),
      //     billName: billName,
      //     regionLevel: "市级",
      //     surfaceWaterSectionList: billData,
      //   });
      // },
      /* 导入本地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 aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
              header: 1,
            });

            const reportDate = aoa[1][0].replace(/[^\d]+/g, "-");

            const riverList = aoa.filter(
              (item) => {
                return item.length >= 30 && item[0] && item[0] != "断面编码"
              }
            );


            // 解析成对象数组
            const billName = file.name;
            const billData = utils.toObjData(riverList);
            if (!billData || billData.length == 0) {
              hide()
              Modal.error({
                title: "导入失败",
                content: "找不到数据",
              });
              return;
            }
            const tasks = [];
            if (billData.length > 0) {
              hide();
              saveJudgeInfo({
                surfaceWaterSectionList: billData,
              }).then(resp => {
                console.log('判断111' + resp.data.code);
                if (resp.data.code == 0) {
                  console.log('判断222' + resp.data.data);
                  if (resp.data.data == "true") {
                    Modal.confirm({
                      title: '有重复数据，确认是否覆盖？',
                      onOk() {
                        tasks.push(
                          saveRiverBill({
                            reportTime: new Date(reportDate).getTime(),
                            billName: billName,
                            regionLevel: "市级",
                            surfaceWaterSectionList: billData,
                          }).then((res) => {
                            console.log("res" + res.data.code)
                            if (res.data.code == 0) {
                              Modal.success({
                                title: "导入成功",
                                content: `成功导入${billData.length}条数据`,
                              });
                              this.$refs.water && this.$refs.water.reload();
                            } else {
                              Modal.error({
                                title: "导入失败",
                                content: "数据上传出错",
                              });
                            }
                          })
                        );
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  } else {
                    saveRiverBill({
                      reportTime: new Date(reportDate).getTime(),
                      billName: billName,
                      regionLevel: "市级",
                      surfaceWaterSectionList: billData,
                    }).then((res) => {
                      console.log("res" + res.data.code)
                      if (res.data.code == 0) {
                        Modal.success({
                          title: "导入成功",
                          content: `成功导入${billData.length}条数据`,
                        });
                        this.$refs.water && this.$refs.water.reload();
                      } else {
                        Modal.error({
                          title: "导入失败",
                          content: "数据上传出错",
                        });
                      }
                    })
                  }

                } else {
                  Modal.error({
                    title: resp.data.msg,
                  });
                }
              })

            }

          } catch (error) {
            hide();
            Modal.error({
              title: "导入失败",
              content: error.message,
            });
          }
          // console.log(billData);
        };
        reader.readAsArrayBuffer(file);

        return false;
      },
      importFileFunctionArea(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",
              cellDates: true
            });
            //0.昼间数据 1.夜间数据 2.其他信息
            let sheetNames = workbook.SheetNames;
            // 解析成二维数组
            let aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
              header: 1,
            });
            var riverList = [];
            riverList = aoa.filter(
              (item) => {
                console.log("export" + this.exportType)
                if (this.exportType == "1") { //国家级水功能
                  return item.length >= 30 && item[8] && item[8] != "水体类型"
                } else { //区控水站水功能模板
                  return item[6] && item[6] != "站点名称"
                }

              }
            );
            console.log(riverList)
            // 解析成对象数组
            const billName = file.name;
            var billData;
            if (this.exportType == "1") {
              billData = utils.toNationalLevelDataObj(riverList);
            } else {
              billData = utils.towaterStationDataObj(riverList);
            }

            if (!billData || billData.length == 0) {
              hide()
              Modal.error({
                title: "导入失败",
                content: "找不到数据",
              });
              return;
            }
            const tasks = [];
            var varType = this.exportType;
            if (billData.length > 0) {
              if (this.exportType == "1") {
                hide();
                saveJudgeInfoWater({
                  nationalLevelWaterFunctionAreaList: billData,
                }).then(resp => {
                  if (resp.data.code == 0) {
                    if (resp.data.data == "true") {
                      Modal.confirm({
                        title: '有重复数据，确认是否覆盖？',
                        onOk() {
                          tasks.push(
                            saveWaterFunctionAreaBill({
                              billName: billName,
                              regionLevel: varType,
                              nationalLevelWaterFunctionAreaList: billData,
                            }).then((res) => {
                              console.log("res" + res.data.code)
                              if (res.data.code == 0) {
                                Modal.success({
                                  title: "导入成功",
                                  content: `成功导入${billData.length}条数据`,
                                });
                                this.$refs.water && this.$refs.water.reload();
                              } else {
                                Modal.error({
                                  title: "导入失败",
                                  content: "数据上传出错",
                                });
                              }
                            })
                          )
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    } else {
                      saveWaterFunctionAreaBill({
                        billName: billName,
                        regionLevel: varType,
                        nationalLevelWaterFunctionAreaList: billData,
                      }).then((res) => {
                        console.log("res" + res.data.code)
                        if (res.data.code == 0) {
                          Modal.success({
                            title: "导入成功",
                            content: `成功导入${billData.length}条数据`,
                          });
                          this.$refs.water && this.$refs.water.reload();
                        } else {
                          Modal.error({
                            title: "导入失败",
                            content: "数据上传出错",
                          });
                        }
                      })
                    }

                  } else {
                    Modal.error({
                      title: resp.data.msg,
                    });
                  }
                })

              } else {
                hide();
                saveJudgeInfoStation({
                  waterStationWaterFunctionAreaList: billData,
                }).then(resp => {
                  if (resp.data.code == 0) {
                    console.log('判断222' + resp.data.data);
                    if (resp.data.data == "true") {
                      Modal.confirm({
                        title:'有重复数据，确认是否覆盖？',
                        onOk() {
                          tasks.push(
                            saveRiverStationBill({
                              billName: billName,
                              regionLevel: varType,
                              waterStationWaterFunctionAreaList: billData,
                            }).then((res) => {
                              console.log("res" + res.data.code)
                              if (res.data.code == 0) {
                                Modal.success({
                                  title: "导入成功",
                                  content: `成功导入${billData.length}条数据`,
                                });
                                this.$refs.water && this.$refs.water.reload();
                              } else {
                                Modal.error({
                                  title: "导入失败",
                                  content: "数据上传出错",
                                });
                              }
                            })
                          )
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    } else {
                      saveRiverStationBill({
                        billName: billName,
                        regionLevel: varType,
                        waterStationWaterFunctionAreaList: billData,
                      }).then((res) => {
                        console.log("res" + res.data.code)
                        if (res.data.code == 0) {
                          Modal.success({
                            title: "导入成功",
                            content: `成功导入${billData.length}条数据`,
                          });
                          this.$refs.water && this.$refs.water.reload();
                        } else {
                          Modal.error({
                            title: "导入失败",
                            content: "数据上传出错",
                          });
                        }
                      })
                    }
                  } else {
                    Modal.error({
                      title:resp.data.msg,
                    });
                  }
                })

              }

            }
          } catch (error) {
            hide();
            Modal.error({
              title: "导入失败",
              content: error.message,
            });
          }
          // console.log(billData);
        };
        reader.readAsArrayBuffer(file);

        return false;
      },
      importFileStation(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",
              cellDates: true
            });
            let sheetNames = workbook.SheetNames;
            // 解析成二维数组
            let aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
              header: 1,
            });
            const riverList = aoa.filter(
              (item) => {
                if (this.param.system == "1") {
                  return item[1] && item[1] != "时间"
                } else {

                  return item[2] && item[2] != "时间" && item[2] != "三类标准" && item[2] != "平均值" && item[2] != "最大值" &&
                    item[2] != "最小值" && item[2] != "有效数据个数" && item[2] != "总数据个数"
                }

              }
            );
            console.log(riverList)
            // 解析成对象数组
            const billName = file.name;
            var billData;
            if (this.param.system == "1") { //国家系统
              billData = utils.toRiverStationObjData(riverList, this.param);
            } else {
              billData = utils.toCityStationObjData(riverList, this.param);
            }

            if (!billData || billData.length == 0) {
              hide()
              Modal.error({
                title: "导入失败",
                content: "找不到数据",
              });
              return;
            }
            const tasks = [];
            var system = this.param.system;
            if (billData.length > 0) {
              hide();
              saveJudgeInfoSite({
                waterSiteList: billData,
              }).then(resp => {
                if (resp.data.code == 0) {
                  if (resp.data.data == "true") {
                    Modal.confirm({
                      title:'有重复数据，确认是否覆盖？',
                      onOk() {
                        tasks.push(
                          saveRiverSiteBill({
                            billName: billName,
                            systemType: system,
                            waterSiteList: billData,
                          }).then((res) => {
                            console.log("res" + res.data.code)
                            if (res.data.code == 0) {
                              Modal.success({
                                title: "导入成功",
                                content: `成功导入${billData.length}条数据`,
                              });
                              this.$refs.water && this.$refs.water.reload();
                            } else {
                              Modal.error({
                                title: "导入失败",
                                content: "数据上传出错",
                              });
                            }
                          })
                        )
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  } else {
                    saveRiverSiteBill({
                      billName: billName,
                      systemType: system,
                      waterSiteList: billData,
                    }).then((res) => {
                      console.log("res" + res.data.code)
                      if (res.data.code == 0) {
                        Modal.success({
                          title: "导入成功",
                          content: `成功导入${billData.length}条数据`,
                        });
                        this.$refs.water && this.$refs.water.reload();
                      } else {
                        Modal.error({
                          title: "导入失败",
                          content: "数据上传出错",
                        });
                      }
                    })
                  }

                } else {
                  Modal.error({
                    title: resp.data.msg,
                  });
                }
              })

            }

          } catch (error) {
            hide();
            Modal.error({
              title: "导入失败",
              content: error.message,
            });
          }
          // console.log(billData);
        };
        reader.readAsArrayBuffer(file);

        return false;
      },
    },
  };

</script>

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