<template>
  <div class="tree-wrapper card-shadow">
    <el-input
      v-model="filterText"
      placeholder="输入关键字过滤"
      @input="funfilterChange"
    />
    <el-tree
      class="treeRef"
      ref="treeRef"
      :data="props.data"
      :show-checkbox="props.showCheckbox"
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
      :current-node-key="''"
      @check="funCheckChange"
      :expand-on-click-node="false"
      @node-click="funCurrentChange"
      :filter-node-method="funTreeFilter"
    >
      <template #default="{ node, data }">
        <p v-if="node.level === 1" class="dashboard-tree-title">
          <span>{{ node.label }}</span>
          <el-icon
            class="refresh"
            size="14"
            title="刷新"
            @click.stop="emits('refresh')"
          >
            <RefreshRight />
          </el-icon>
        </p>
        <el-dropdown
          ref="dropdown1"
          v-else
          size="small"
          trigger="contextmenu"
          @command="funCommand"
          style="color: #b3bdc0"
        >
          <span class="el-dropdown-link">
            <el-icon>
              <Folder
                v-if="!node.expanded || (node.isLeaf && !node.isCurrent)"
              />
              <FolderOpened v-else />
            </el-icon>
            {{ node.label }}
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-if="props.dropdownMenu.includes('save')"
                :command="{ type: 'save', data, node }"
                >保存</el-dropdown-item
              >
              <el-dropdown-item
                v-if="
                  data.childs &&
                  data.childs.length &&
                  props.dropdownMenu.includes('export')
                "
                :command="{ type: 'export', data, node }"
                >导出
              </el-dropdown-item>
              <el-dropdown-item
                v-if="props.dropdownMenu.includes('delete')"
                :command="{ type: 'delete', data, node }"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-tree>
  </div>
</template>

<script setup name="search">
import { ref, defineExpose, defineEmits, defineProps } from "vue";
import {
  fittingCurveSave,
  dataOptionDel,
  filesDel,
} from "@/api/powerGenerating/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
const baseURL = process.env.VUE_APP_TEST;
const socketURL = process.env.WS_APP_TEST;
const emits = defineEmits(["currentChange", "checkChange", "refresh"]);
const props = defineProps({
  data: {
    type: Array,
    default: () => {},
  },
  showCheckbox: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "wind",
  },
  dropdownMenu: {
    type: Array,
    default: () => ["export", "delete"],
  },
});
const treeRef = ref();
const filterText = ref("");
/**输入框过滤 */
const funfilterChange = () => {
  treeRef.value.filter(filterText.value);
};
const funTreeFilter = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};
/**选中节点变化 */
const funCurrentChange = (current, currentNode) => {
  emits("currentChange", { current, currentNode });
};
/**复选框选中变化 */
const funCheckChange = (
  current,
  { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }
) => {
  emits("checkChange", {
    current,
    checkedNodes,
    checkedKeys,
    halfCheckedNodes,
    halfCheckedKeys,
  });
};
//右键时, command菜单
const funCommand = async ({ type, data, node }) => {
  switch (type) {
    case "save":
      /**该保存功能目前暂用于风电场, combine页 */
      if (props.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 fittingCurveSave({ 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 =
          props.type === "wind"
            ? data.childs.map((o) => o.id)
            : data.childs.map((o) => o.path);
        const url =
          props.type === "wind"
            ? "/data/option/download?ids="
            : "/export/files?filename=";
        a.href = baseURL + url + childs.join(",");
        a.download = "";
        a.target = "_blank";
        a.click();
      });
      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) =>
                  props.type === "wind" ? o.id : o.path
                )
              );
            } else if (unit.children?.length) {
              repeatArr(unit.children, deleteArr);
            }
          }
        };
        if (data.childs?.length) {
          deleteArr = data.childs.map((o) =>
            props.type === "wind" ? o.id : o.path
          );
        } else if (data.children?.length) {
          repeatArr(data.children, deleteArr);
        }
        let res = { code: 500 };
        if (props.type === "wind") {
          res = await dataOptionDel({ ids: deleteArr.join(",") }); //删除当前节点
        } else {
          res = await filesDel({ filename: deleteArr.join(",") }); //删除当前节点
        }
        if (res.code === 200) {
          ElMessage.success(res.msg);
          emits("refresh");
        }
      });

      break;
  }
};

const getCheckedNodes = () => {
  // // console.log(treeRef.value!.getCheckedNodes(false, false));
};
const getCheckedKeys = () => {
  // // console.log(treeRef.value!.getCheckedKeys(false));
};
const setCheckedNodes = () => {
  treeRef.value.setCheckedNodes(
    [
      {
        id: 5,
        label: "Level two 2-1",
      },
      {
        id: 9,
        label: "Level three 1-1-1",
      },
    ],
    false
  );
};
const setCheckedKeys = (keyArr) => {
  treeRef.value.setCheckedKeys(keyArr, false);
};
const resetChecked = () => {
  treeRef.value.setCheckedKeys([], false);
};

const defaultProps = {
  children: "children",
  label: "label",
};
defineExpose({ setCheckedKeys });
</script>
<style lang="less" scoped>
.tree-wrapper {
  height: 100%;
  ;
  padding: 20px;

  .treeRef {
    height: calc(100% - 30px - 20px);
    width: 100%;
    margin-top: 10px;
    padding: 10px 0;
    overflow: auto;

    .dashboard-tree-title {
      display: flex;
      justify-content: space-between;
      width: 100%;
    }
    .refresh {
      margin-right: 15px;
    }
  }
}
.el-tree::v-deep {
  .el-tree-node__content:hover,
  .el-tree-node__content:active {
    background: rgba(97, 97, 90, 25%);
  }
  &.el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: rgba(97, 97, 90, 25%);
  }
}
</style>
