<template>
  <div class="treeTransfer">
    <div class="rightTree">
      <div class="treeTit">
        {{ props.leftTit || "左侧栏：" }}
        <div>
          <el-link type="primary" @click="toggleSelectAllLeft()">全选 / 取消全选</el-link>
        </div>
      </div>
      <div class="list">
        <el-input style="margin-bottom: 10px;" v-model="searchKeyword" :placeholder=props.searchPlaceholder clearable
          :change="handleQueryLeft()" />
        <el-scrollbar>
          <el-tree ref="treeRef" :data="props.fromData" show-checkbox :node-key="props.nodeKey"
            highlight-current />
        </el-scrollbar>
      </div>
    </div>
    <div class="btnDiv">
      <div class="mg10" @click="toRight()">
        <el-button :icon="ArrowRight" circle />
      </div>
      <div class="mg10" @click="toLeft()">
        <el-button :icon="ArrowLeft" circle />
      </div>
    </div>
    <div class="leftTree">
      <div class="treeTit">
        {{ props.rightTit || "右侧栏：" }}
        <el-link type="primary" @click="selectAllItems()">全选 / 取消全选</el-link>
      </div>
      <div class="list leftList">
        <el-scrollbar>
          <el-checkbox-group v-model="modelGroup">
            <div v-for="(item, index) in toData" :key="index">
              <el-checkbox :label="item.id">{{ item.label }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  computed,
  watch,
} from "vue";
import { ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import { cloneDeep } from "lodash";
const props = defineProps([
  "nodeKey",
  "fromData",
  "propToData",
  "defaultProps",
  "leftTit",
  "rightTit",
  "searchPlaceholder",
]);
const emit = defineEmits(["checkVal"]);
const treeRef = ref();
const searchKeyword = ref('');

//右侧数据
const toData= ref([]);
const modelGroup = ref([]);

onMounted(() => {
  if (props.propToData.length > 0) {
    toData.value = cloneDeep(props.propToData);
    console.log("toData.value: ", toData.value);
    treeRef.value.setCheckedKeys([], false);
  }
});
watch(
  () => props.propToData,
  () => {
    console.log("那边的传值: ", props.propToData);

    toData.value = cloneDeep(props.propToData);
    treeRef.value.setCheckedKeys([], false);
  }
);
//去右边
const toRight = () => {
  const checkNodes = treeRef.value
    .getCheckedNodes(false, false)
    .filter((fil) => !fil.children);
  const newArr = toData.value.concat(checkNodes);
  let obj = {};
  let peon = newArr.reduce((cur, next) => {
    obj[next[props.nodeKey]]
      ? ""
      : (obj[next[props.nodeKey]] = true && cur.push(next));
    return cur;
  }, []);
  toData.value = peon;
  treeRef.value.setCheckedKeys([], false);
  modelGroup.value = [];

  checkVal();
};
//去左边
const toLeft = () => {
  for (var i = 0; i < toData.value.length; i++) {
    if (modelGroup.value.includes(toData.value[i].id)) {
      toData.value.splice(i, 1);
      i -= 1;
    }

  }
  checkVal();
};
//返回父组件
const checkVal = () => {
  emit("checkVal", toData.value);
};



// 获取所有节点的 key
const getAllKeys = (nodes) => {
  const keys = [];
  for (const node of nodes) {
    keys.push(node[props.nodeKey]);
    if (node.children && node.children.length > 0) {
      keys.push(...getAllKeys(node.children));
    }
  }
  return keys;
};

// 全选/取消全选按钮点击事件处理
const toggleSelectAllLeft = () => {
  const treeInstance = treeRef.value;
  if (treeInstance) {
    const allKeys = getAllKeys(props.fromData);
    const checkedKeys = treeInstance.getCheckedKeys();
    const isAllSelected = allKeys.every(key => checkedKeys.includes(key));
    const targetKeys = isAllSelected ? [] : allKeys;
    treeInstance.setCheckedKeys(targetKeys);
  }
};


// 全选按钮的点击事件处理函数
const selectAllItems = () => {
  if (modelGroup.value.length === toData.value.length) {
    // 如果已经全部选中，则取消选中全部节点
    modelGroup.value = [];
  } else {
    // 否则选中全部节点
    modelGroup.value = toData.value.map(item => item.id);
  }
};


// 搜索数据源
function handleQueryLeft() {
  // selectChild(searchKeyword.value,props.fromData,props.fromData)
}

// 树形搜索
// function selectChild(str, tag, res, parent) {
//   for (let item of tag) {
//     if (item.label.indexOf(str) !== -1) {
//       if (parent) {
//         res.push(parent)
//       } else {
//         res.push(item)
//       }
//     } else if (item.children && item.children.length) {
//       selectChild(str, item.children, res, parent || item)
//     }
//   }
// }

</script>


<style lang="scss">
.treeTransfer {
  display: flex;
  justify-content: space-between;

  .mg10 {
    margin: 10px;
  }

  .leftTree,
  .rightTree {
    flex-grow: 1;
    width: calc((100% - 60px) / 2);
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    padding-bottom: 20px;

    .treeTit {
      line-height: 32px;
      color: rgba(0, 0, 0, 0.85);
      // background: #e3e7ee;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
    }

    .list {
      height: 500px;
      padding: 15px 10px 24px 40px;
    }
  }

  .btnDiv {
    width: 60px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>