<template>
  <div class="treeData" :style="{ height: height }">
    <div class="treeSeach">
      <el-input
        v-model="filterText"
        style="height: 30px"
        placeholder="输入关键字过滤"
        :suffix-icon="Search"
      />
      <div class="treeShuax" @click="refreshFn">
        <img :src="tree_shuaxing" />
      </div>
    </div>
    <div class="treeMain">
      <div class="treeMainTit">
        <span>{{showTitle}}</span>
      </div>
      <!-- <div v-for="node in data" :key="node.id" class="treeMainMsg">
                <span>{{node.label}}</span>
                <tree-node :node="node.children" :data="data" :show-checkbox="showCheckbox"
                    :dropdownMenu="dropdownMenu">
                </tree-node>
            </div> -->
      <el-tree
        :data="data"
        :props="defaultProps"
        :default-expanded-keys="defaultExpandedKeys"
        highlight-current
        icon="none"
        :filter-node-method="filterNode"
        ref="tree"
        @node-click="funCurrentChange"
        :show-checkbox="showCheckbox"
        @check="funCheckChange"
        node-key="id"
        :expand-on-click-node="true"
        :current-node-key="activeNode"
        :class="showCheckbox ? 'elTreeSty' : ''"
      >
        <template #default="{ node, data }">
          <div class="dashedSty">
            <span
              class="hasMore_shu"
              :style="
                node.id !==
                node.parent.childNodes[node.parent.childNodes.length - 1].id
                  ? 'height: 30px'
                  : 'height: 18px'
              "
              :styel="shuFn(node, data)"
            ></span>
            <span class="hasMore_heng"></span>
          </div>

          <el-dropdown
            ref="dropdown1"
            size="small"
            trigger="contextmenu"
            @command="funCommand"
            :class="
              !node.expanded || (node.isLeaf && !node.isCurrent)
                ? ''
                : 'eldropdownCla'
            "
          >
            <span
              class="el-dropdown-link"
              :class="
                node.isCurrent || activeNode === data.id
                  ? 'changenodeLabel'
                  : 'nodeLabel'
              "
            >
              {{ node.label }}
            </span>
            <span>{{ node.label }}</span>
            <template #dropdown v-if="node.label.indexOf('风电场') !== -1">
              <el-dropdown-menu>
                <el-dropdown-item
                  class="text-[#409EFF]"
                  v-if="dropdownMenu.includes('save')"
                  :command="{ type: 'save', data, node }"
                  >保存</el-dropdown-item
                >
                <el-dropdown-item
                  class="text-[#409EFF]"
                  v-if="
                    data.childs &&
                    data.childs.length &&
                    dropdownMenu.includes('export')
                  "
                  :command="{ type: 'export', data, node }"
                  >导出
                </el-dropdown-item>
                <el-dropdown-item
                  class="text-[#F56C6C]"
                  v-if="dropdownMenu.includes('delete')"
                  :command="{ type: 'delete', data, node }"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #empty>
          <div class="nodata">
            <img :src="nodata" alt="" />
            <p class="nodataText">暂无数据,敬请期待</p>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script>
import httpRequest from "@/utils/request.js";
import tree_shuaxing from "@/assets/menuImg/tree_shuaxing.png";
import nodata from "@/assets/images/noData.png";
import TreeNode from "./treeStyle.vue";
import treeJson from "./treeJson.json";
import { Search } from "@element-plus/icons-vue";
import { saveAs } from "file-saver";
import { apiGetExportMsg } from "@/api/gengra";
import { DebugCameraPrimitive } from "cesium";
import DAYJS from "dayjs";
export default {
  components: {
    TreeNode,
  },
  props: {
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
    height: {
      type: String,
      default: () => {
        return "";
      },
    },
    type: {
      type: String,
      default: () => {
        return "wind";
      },
    },
    currentNodeKey: {
      type: String,
      default: () => {
        return "";
      },
    },
    dropdownMenu: {
      type: Array,
      default: () => {
        return ["export", "delete"];
      },
    },
    showCheckbox: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  },

  data() {
    return {
      // treeJson: treeJson,
      treeJsonArr: [],
      filterText: "",
      Search: Search,
      nodata: nodata,
      tree_shuaxing: tree_shuaxing,
      defaultProps: {
        children: "children",
        label: "label",
      },
      activeNode: "",
      showTitle: "",
      defaultExpandedKeys: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },

    currentNodeKey(value) {
      this.activeNode = value;
      const node = this.getTreeItem(value, this.data?.[0]) || null;
      this.$refs.tree.setChecked(node, true);
    },

    data(value) {
        this.showTitle = value.length>0 ? value[0].label : "数据"
      this.defaultExpandedKeys = this.getDefaultExpandedKey([], value);
    },
  },

  created() {
    this.defaultExpandedKeys = this.getDefaultExpandedKey([], this.data || []);
  },

  mounted() {
    // this.treeJsonFn()
  },

  methods: {
    getDefaultExpandedKey(defaultExpandedKey = [], data = []) {
      data?.forEach((ele) => {
        if (/(\d{1,2})月(\d{1,2})日/.test(ele.label)) {
          const monthReg = new RegExp(`${DAYJS().format("MM")}月`);
          if (monthReg.test(ele.label)) {
            defaultExpandedKey.push(ele.id);
          }
        } else {
          if (ele?.children?.length) {
            return this.getDefaultExpandedKey(defaultExpandedKey, ele.children);
          }
        }
      });
      return defaultExpandedKey;
    },
    treeJsonFn() {
      this.treeJsonArr = this.funRepeatMap(this.treeJson.data);
    },

    funRepeatMap(arr, type = "prepare") {
      return arr.map((o) => {
        if (o.children) {
          const findIndex = o.children.findIndex((p) => !!p.type);
          if (findIndex !== -1) {
            o.childs = o.children;
            o.children = [];
          }
        }
        return {
          ...o,
          children: o.children ? this.funRepeatMap(o.children, type) : [],
        };
      });
    },

    getTreeItem(id = "", data = {}) {
      if (!id) {
        return {};
      }

      if (data.id === id) {
        return data;
      } else {
        if (data?.children?.length) {
          for (let i = 0; i < data.children.length; i++) {
            const ele = data.children[i];
            if (ele.id === id) {
              return ele;
            } else {
              if (ele.children?.length) {
                return this.getTreeItem(id, ele);
              } else {
                return {};
              }
            }
          }
        } else {
          return {};
        }
      }
    },

    shuFn(node, data) {
      // debugger
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    refreshFn() {
      this.$emit("refresh");
    },

    funCurrentChange(current, currentNode) {
      this.activeNode = current?.id || "";
      this.$emit("currentChange", {
        current,
        currentNode,
      });
    },

    async funCommand({ type, data, node }) {
      switch (type) {
        case "save":
          /**该保存功能目前暂用于风电场, combine页 */
          if (this.type !== "wind") {
            return false;
          }
          ElMessageBox.confirm("确认保存当前节点的拟合功率?", "保存", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async () => {
            let saveArr = [];
            const repeatArr = (arr, saveArr) => {
              for (const unit of arr) {
                if (unit.childs.length) {
                  saveArr.push(...unit.childs.map((o) => o.id));
                } else if (unit.children.length) {
                  repeatArr(unit.children, saveArr);
                }
              }
            };
            if (data.childs.length) {
              saveArr = data.childs.map((o) => o.id);
            } else if (data.children.length) {
              repeatArr(data.children, saveArr);
            }
            let res = {
              code: 500,
            };
            res = await httpRequest.get("/power/fitting/curve/save", {
              params: {
                ids: saveArr.join(","),
              },
            }); //删除当前节点

            if (res.code === 200) {
              ElMessage.success(res.msg);
            }
          });
          break;
        case "export":
          ElMessageBox.confirm("确认导出当前节点的所有数据?", "导出", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            const a = document.createElement("a");
            let childs = [];
            childs =
              this.type === "wind"
                ? data.childs.map((o) => o.id)
                : data.childs.map((o) => o.path);
            const url =
              this.type === "wind"
                ? "/data/option/download?ids="
                : "/export/files?filename=";

            a.href =
              // config.baseURL + url + childs.join(",");
              process.env.VUE_APP_GENERAT_URL + url + childs.join(",");
            a.download = "";
            a.target = "_blank";
            a.click();

            // let that = this
            // let childs = []
            // childs = this.type === 'wind' ? data.childs.map((o) => o.id) : data.childs.map(
            //     (o) => o.path)
            // let params = {
            //     ids: childs.join(",")
            // }
            // apiGetExportMsg(params).then(datas => {
            //     let blob = new Blob([datas], {
            //         type: `application/vnd.ms-excel;charset=utf-8`
            //     })
            //     saveAs(blob)
            // }).catch((r) => {
            // })
          });
          break;
        case "delete":
          ElMessageBox.confirm("确认删除当前节点的所有数据?", "删除", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async () => {
            let deleteArr = [];
            const repeatArr = (arr, deleteArr) => {
              for (const unit of arr) {
                if (unit.childs.length) {
                  deleteArr.push(
                    ...unit.childs.map((o) =>
                      this.type === "wind" ? o.id : o.path
                    )
                  );
                } else if (unit.children.length) {
                  repeatArr(unit.children, deleteArr);
                }
              }
            };
            if (data.childs.length) {
              deleteArr = data.childs.map((o) =>
                this.type === "wind" ? o.id : o.path
              );
            } else if (data.children.length) {
              repeatArr(data.children, deleteArr);
            }
            let res = {
              code: 500,
            };
            if (this.type === "wind") {
              res = await httpRequest.get("/data/option/delete", {
                params: {
                  ids: deleteArr.join(","),
                },
              }); //删除当前节点
            } else {
              res = await httpRequest.delete("/delete/files", {
                data: {
                  filename: deleteArr.join(","),
                },
              }); //删除当前节点
            }
            if (res.code === 200) {
              ElMessage.success(res.msg);
              this.$emit("refresh");
            }
          });

          break;
      }
    },

    funCheckChange(current, checkedNodes) {
      this.$emit("checkChange", {
        current,
        checkedNodes,
      });
    },
  },
};
</script>
<style lang="less">
.treeData {
  overflow-y: auto;

  .eldropdownCla {
    .changenodeLabel {
    }
    .nodeLabel {
    }
  }

  .treeSeach {
    width: 100%;
    display: flex;
    margin-bottom: 5px;

    .treeShuax {
      cursor: pointer;
      margin-left: 5px;
      height: 30px;
      width: 30px;
      background: #5473e8;
      border-radius: 2px;
      text-align: center;

      img {
        width: 25px;
        height: 25px;

        position: relative;
        top: 2px;
        left: -1px;
      }
    }
  }

  .treeMain {
    .treeMainTit {
      width: calc(100% - 10px);
      height: 22px;
      background: #1e3f9a;
      color: #fff;
      font-size: 12px;
      padding: 8px 0 0 10px;
    }

    .treeMainMsg {
      span {
        font-family: Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: #121212;
        line-height: 30px;
      }
    }

    .el-tree {
      background: transparent;
      color: #fff;
      height: 100%;

      .is-current {
        width: 100%;
        background: none !important;
      }

      .el-tree__empty-block {
        img {
          margin-top: 20px;
        }

        .nodataText {
          line-height: 50px;
          font-size: 14px;
          color: #8c8e91;
        }
      }
    }
  }
}
</style>