<template>
  <div>
    <div class="title">
      本地数据
      <div class="title_time">{{ currentDate }}</div>
    </div>

    <div class="card">
      <div class="screen">
        <el-radio-group v-model="commerce" size="large" fill="#0052d9" @change="oncommerce">
          <el-radio-button label="工商业储能" :value="1" />
          <el-radio-button label="大储储能" :value="2" />
        </el-radio-group>
        <div class="screen_right" v-if="commerce == 1">
          <div class="export">
            <el-button type="primary" size="large" color="#0052d9" @click="newaddition">数据回复</el-button>
          </div>
        </div>
        <div class="screen_right" v-if="commerce == 2">
          <div>
            电站&ensp;&ensp;
            <el-cascader v-model="localdata" :options="optionsfile" :props="cascaderProps" filterable @change="postemsDevice" />
          </div>
          &ensp;&ensp;&ensp;&ensp;
          <el-button type="primary" size="large" color="#0052d9" @click="query(0)">查询</el-button>
          <div class="export">
            <el-button type="primary" size="large" color="#0052d9" @click="newaddition">导入</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="card cardbottom">
      <div>&ensp;</div>
      <el-table
        :data="commerce == 1 ? tableData.children : options"
        row-key="name"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%"
        border
        show-overflow-tooltip
        @row-click="handleRowClick"
      >
        <el-table-column prop="name" label="文件名称" />

        <el-table-column prop="id" label="ID" />
        <el-table-column prop="parentId" label="父ID" />
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button v-if="scope.row.type == 'file'" @click="downloadxlsx(scope.row.name)">下载</el-button>
            <el-button v-if="scope.row.fileType == 'file'" @click="downloadfilezip(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    -->
    </div>
    <el-dialog v-model="dialogVisible" title="导出中" top="300px" width="40%" @close="handleClose">
      <div class="lexce">{{ message }}</div>
      <template #footer>
        <div class="dialog-footer" v-if="excelexport">
          <el-button v-if="excelexport.progress == 0" @click="handleClose">取消导出</el-button>
          <el-button v-if="excelexport.progress == 3" type="primary" @click="handleClose"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!--     -->
    <el-dialog v-model="energystorage" title="大储导入" top="100px" width="40%" @close="handenergyClose">
      <div class="dialoglexce_box">
        <div class="dialoglexce">
          <div class="dialoglexcebox">
            电站&ensp;&ensp;
            <el-cascader
              v-model="status"
              style="width: 300px"
              :options="optionsfile"
              :props="cascaderProps"
              filterable
              @change="e => onpostemsDevice(e)"
            />
          </div>
          <div class="dialogpileup">
            &ensp;&ensp;{{ acbcType == 1 ? "堆" : "PCS" }}&ensp;&ensp;<el-input
              v-model="emsdevicename"
              style="width: 300px"
              size="large"
              placeholder="请输入"
            />
          </div>
          <div class="dialogpileup" v-if="acbcType == 1">
            &ensp;&ensp;栈&ensp;&ensp;<el-input v-model="Stackename" style="width: 300px" size="large" placeholder="请输入" />
          </div>
        </div>
        <div class="dialoglexce_right">
          <el-upload class="upload-demo" :data="uploadData" drag :before-upload="beforeUpload" multiple>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">点击上传 <em>拖拽上传</em></div>
            <template #tip>
              <div class="el-upload__tip">上传文件，文件大小500kb</div>
            </template>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handenergyClose">取消导出</el-button>
          <el-button type="primary" @click="handenergysure"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!--  

-->
<script setup lang="ts">
import { directorylURL, selectfileURL, tdengineyuanshiURL, downloadfileURL, selectfileidURL } from "@/api/home/Multisite";
import { onMounted, Ref, ref } from "vue";
import { UploadFilled } from "@element-plus/icons-vue";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
// const { BUTTONS } = useAuthButtons();
// import { Station } from "@/api/interface";
// import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ElMessage, TreeNode } from "element-plus";
// import { saveAs } from "file-saver";
// import axios from "axios";

// import { useRouter } from "vue-router";
// const router = useRouter();
// const translate = ref();

const timevalue: Ref<any> = ref([]);
const options = ref();
const cascaderProps = ref({
  value: "id", // 绑定值的字段
  label: "name", // 显示文本的字段
  children: "children", // 子选项的字段
  checkStrictly: true
});
const postselectfileURL = async () => {
  const { data } = await selectfileURL({});
  console.log(data);
  options.value = data;
};
// 回显
const optionsfile = ref();
const onselectfileid = async () => {
  const { data } = await selectfileidURL({});
  console.log(data);
  optionsfile.value = data;
};
const dialogVisible = ref(false);
const message = ref("");

const status = ref();
const localdata = ref();

const timerId = ref();

const excelexport = ref();
const handleClose = async () => {
  if (timerId.value) {
    clearTimeout(timerId.value);
    timerId.value = ""; // 清除引用
    dialogVisible.value = false;
  }
};

const tableData = ref();

const head = ref();
const pageable = ref({
  pn: 1,
  ps: 10,
  total: 0
});
const currentPath = ref();
const handleRowClick = (node: TreeNode) => {
  // 获取当前点击行的所有父级名称
  const parentNames = getParentNames(tableData.value, node, []);
  console.log("点击的节点: ", node); // 输出当前点击节点
  // 拼接成字符串
  currentPath.value = parentNames?.join("/"); // 不反转顺序，确保路径是从根节点到目标节点的顺序
  console.log("父级路径: ", currentPath.value); // 输出拼接后的父级路径
};

// 明确指定参数类型和返回类型
const getParentNames = (currentNode: any, targetNode: any, parentNames: string[]): string[] | null => {
  // 如果找到了目标节点
  if (currentNode.name === targetNode.name) {
    parentNames.push(currentNode.name); // 添加当前节点的名称到父级路径
    return parentNames;
  }

  // 如果当前节点有子节点，递归查找
  if (currentNode.children && currentNode.children.length) {
    const newParentNames = [...parentNames, currentNode.name]; // 创建新的父级名称数组
    for (let child of currentNode.children) {
      const result = getParentNames(child, targetNode, newParentNames);
      if (result) return result;
    }
  }

  // 如果没有找到，返回 null
  return null;
};

const downloadxlsx = (name: any) => {
  let fileUrl = `myDeviceData/${name}`;
  let fileName = name;
  fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
      // 创建一个临时的URL对象
      const url = URL.createObjectURL(blob);
      // 创建一个隐藏的<a>标签，并设置其href属性为临时URL
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName; // 设置下载的文件名
      a.style.display = "none";
      // 将<a>标签添加到文档中，并模拟点击下载
      document.body.appendChild(a);
      a.click();
      // 下载完成后，移除<a>标签和临时URL对象
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    })
    .catch(error => {
      console.error("下载文件时出错:", error);
    });
};
//
const downloadfilezip = async (row: { name: any }) => {
  console.log(row.name);
  try {
    let params = {
      fileName: row.name
    };
    const response = await downloadfileURL(params); // 假设返回的是包含 headers 的完整响应
    const blob = response; // 获取 Blob 数据
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([blob]));
    console.log(blob);

    const a = document.createElement("a");
    a.href = url;
    a.setAttribute("download", `${row.name}.zip`); // 设置下载文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    return;
  } catch (error) {
    console.error("下载失败:", error);
  }
};
const getplatformuserlist = async () => {
  const { data } = await directorylURL();

  tableData.value = data;

  head.value = Object.keys(tableData.value.list[0]);
  pageable.value.total = tableData.value.page.totald;
};

const currentDate = ref();

const commerce = ref(1);

const oncommerce = async () => {
  console.log(commerce.value);
  if (commerce.value == 1) {
    getplatformuserlist();
  } else {
    postselectfileURL();
    onselectfileid();
  }
};
// 大储弹窗
const energystorage = ref(false);

const handenergyClose = async () => {
  energystorage.value = false;
};

const emsdevicename = ref("");
const Stackename = ref("");
const uploadData = ref();
const handenergysure = async () => {
  // 构建额外参数对象
  console.log(status.value);
  console.log(emsdevicename.value);
  console.log(Stackename.value);

  if (acbcType.value == 1) {
    if (status.value == undefined || emsdevicename.value == "" || Stackename.value == "" || uploadData.value == undefined) {
      ElMessage({
        type: "warning",
        message: "请输入完整信息"
      });
      return;
    } else if (status.value.length < 4) {
      ElMessage({
        type: "warning",
        message: "最少选择到仓级"
      });
      return;
    }
  } else if (acbcType.value == 2) {
    if (status.value == undefined || emsdevicename.value == "" || uploadData.value == undefined) {
      ElMessage({
        type: "warning",
        message: "请输入完整信息"
      });
      return;
    } else if (status.value.length < 4) {
      ElMessage({
        type: "warning",
        message: "最少选择到仓级"
      });
      return;
    }
  }

  let obj = {
    deviceId: status.value[1],
    acdcType: acbcType.value,
    acdcId: status.value[2],
    syspileId: emsdevicename.value,
    crowdId: Stackename.value
  };
  // 创建 FormData 对象
  const formData = new FormData();
  formData.append("file", uploadData.value); // 添加文件
  try {
    // 调用上传接口
    const { data } = await tdengineyuanshiURL(obj, formData);
    console.log(data);
    energystorage.value = false;
  } catch (error) {
    console.error("上传失败:", error);
  }
};
const newaddition = async () => {
  console.log(commerce.value);
  energystorage.value = true;
};
const acbcType = ref(1);
const onpostemsDevice = async (e: any) => {
  console.log(e);
  console.log(options);

  if (e.length == 3) {
    const [firstLevel, secondLevel, thirdLevel] = e;

    // 查找第一层
    const firstLevelOption = options.value.find((item: { id: any }) => item.id === firstLevel);
    if (firstLevelOption && firstLevelOption.children) {
      // 查找第二层
      const secondLevelOption = firstLevelOption.children.find((item: { id: any }) => item.id === secondLevel);
      if (secondLevelOption && secondLevelOption.children) {
        // 查找第三层
        const selectedOption = secondLevelOption.children.find((item: { id: any }) => item.id === thirdLevel);
        console.log("当前点击的节点:", selectedOption);
        acbcType.value = selectedOption.acbcType;
      }
    }
    emsdevicename.value = "";
    Stackename.value = "";
  } else if (e.length == 4) {
    emsdevicename.value = e[3];
    Stackename.value = "";
  } else if (e.length == 5) {
    emsdevicename.value = e[3];
    Stackename.value = e[4];
  }
};
const postemsDevice = async (e: any) => {
  console.log(e);
};
const query = async (e: any) => {
  console.log(e);
};
const beforeUpload = (file: Blob | MediaSource) => {
  // 获取文件的临时路径
  const filePath = URL.createObjectURL(file);
  console.log("文件临时路径:", filePath);
  console.log(file);
  uploadData.value = file;
  // 手动上传文件
  // uploadFile(file);

  // 返回 false，阻止默认上传行为
  return false;
};

onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
  }
  const today = new Date();
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(today.getDate() - 7);
  const sevenDaysAgoDate = sevenDaysAgo.toISOString().split("T")[0];

  timevalue.value = [currentDate.value, sevenDaysAgoDate];
  console.log(timevalue.value);

  oncommerce();
  // postselectfileURL();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
<!--

-->
