<template>
  <van-overlay :show="overlayloading">
    <div class="wrapper">
      <van-loading color="#0094ff"> 加载中... </van-loading>
    </div>
  </van-overlay>
  <seltopbar
    showtype="addressList"
    @commitSelect="commitSelect"
    @cancelSelect="cancelSelect"
  ></seltopbar>
  <van-search v-model="filterText" show-action placeholder="请输入搜索地点" />
  <div :style="{ height: divHeight + 'px' }" class="divTree">
    <el-tree
      v-if="data.length > 0"
      ref="treeRef"
      :data="data"
      :props="defaultProps"
      :filter-node-method="filterNode"
      node-key="id"
      accordion
      :default-expanded-keys="expandNodes"
      show-checkbox
      @check="handleNodeClick"
    />
  </div>
</template>

<script setup>
import { ref, watch, nextTick, reactive, onMounted } from "vue";
import seltopbar from "@/components/selTopbar.vue";
import { getAddrList } from "@/api/index.js";
// import { ElTree, ElInput } from "element-plus";
// import "element-plus/dist/index.css";

const overlayloading = ref(false);

//列表数据
const data = reactive([]);

const props = defineProps({
  selAddr: Array,
});
const emit = defineEmits(["closeFullPicker"]);
// 设置树的高度
const divHeight = ref(0);

//默认展开节点
const expandNodes = ref([]);

// 树
const treeRef = ref();

nextTick(() => {
  divHeight.value = document.documentElement.clientHeight - 46 - 54 - 5;
  //默认展开节点['L01']
  if (props.selAddr.length == 0) {
    expandNodes.value = ["YH-01"];
  } else {
    expandNodes.value = props.selAddr.map((item) => item.id);
  }
});
onMounted(() => {
  console.log(props.selAddr);
  getAddress();
});

// 搜索
const filterText = ref("");
watch(filterText, (val) => {
  treeRef.value.filter(val);
});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.includes(value);
};

//树单选
const handleNodeClick = (data) => {
  if (data.parent) {
    showFailToast("不能选择父节点，请重新选择");
  } else {
    treeRef.value.setCheckedKeys([data.id]);
    // props.selAddr.push(data);
  }
};

const defaultProps = {
  label: "text",
  children: "children",
  id: "id",
  disabled(data, node) {
    return data.children.length > 0;
  },
};

function getAddress() {
  overlayloading.value = true;
  let param = {};
  getAddrList(param).then((res) => {
    console.log(res);
    if (typeof res === "object" && Array.isArray(res)) {
      data.push(res[0]);
      console.log(data);
      nextTick(() => {
        console.log("props.selAddr", props.selAddr);
        //获取所有的id为默认选中
        treeRef.value.setCheckedNodes(props.selAddr);
      });
      // setTimeout(() => {
      //   treeRef.value.setCheckedNodes(props.selAddr);
      // }, 1000);
      overlayloading.value = false;
    } else {
      showFailToast("地点列表获取失败");
      overlayloading.value = false;
    }
    // if (typeof res === "object" && Array.isArray(res)) {
    //   data.push(res[0]);
    //   nextTick(() => {
    //     //默认展开节点['L01']
    //     if (props.selAddr.length == 0) {
    //       expandNodes.value = ["YH-01"];
    //     } else {
    //       // 详情没有id，所以先通过name获取id，然后再回显已选中
    //       // if (!props.selAddr[0].id) {
    //       //   let sel = findNodeInTree(data, "text", props.selAddr[0].name);
    //       //   props.selAddr[0] = { id: sel.id, name: sel.text };
    //       // }
    //       // //获取所有的id为默认选中
    //       // treeRef.value.setCheckedNodes(props.selAddr);
    //       // expandNodes.value = props.selAddr.map((item) => item.id);
    //       console.log("props.selAddr", props.selAddr);
    //       //获取所有的id为默认选中
    //       treeRef.value.setCheckedNodes(props.selAddr);
    //     }
    //   });
    //   overlayloading.value = false;
    // } else {
    //   showFailToast("获取地点失败");
    //   overlayloading.value = false;
    // }
  });
}

// 选中的地点
const commitSelect = () => {
  const addrs = treeRef.value.getCheckedNodes();
  console.log(addrs);
  if (addrs.length == 0) {
    showFailToast("至少选择一个地点");
  } else if (addrs.length > 1) {
    showFailToast("不能选择父节点，请重新选择");
  } else {
    overlayloading.value = true;
    props.selAddr.length = 0;
    props.selAddr.push(...addrs);
    emit("closeFullPicker", "ok");
    console.log("123", treeRef.value.getCheckedNodes());
    overlayloading.value = false;
  }
};
const cancelSelect = () => {
  emit("closeFullPicker", "cancel");
};
//遍历 通过text 获取id
function findNodeInTree(tree, targetKey, targetValue) {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i][targetKey] === targetValue) {
      return tree[i];
    }
    if (tree[i].children) {
      const foundNode = findNodeInTree(
        tree[i].children,
        targetKey,
        targetValue
      );
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
}
</script>

<style>
.divTree {
  overflow-y: scroll;
  margin-bottom: 5px;
}

/* 搜索行 */
.van-search--show-action {
  padding-right: 10px;
}
/* 遮罩 */
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.van-overlay {
  z-index: 2;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
