import { getDept } from "../api";
import WlLoading from "@mobileUI/components/WlLoading";
import { TDepartmentList } from "@mobileUI/typings/BCDepartmentSelectorPopup";

const useHandleData = () => {
  //将数组转成树
  const useArrToTree = (arr: TDepartmentList[]): TDepartmentList[] => {
    const returnArr = [];
    const map = arr.reduce((acc, item) => {
      acc[item.id] = item;
      return acc;
    }, {});
    const len = arr.length;
    for (let i = 0; i < len; i++) {
      arr[i].checkedStatus = "no-check";
      arr[i].showInCheckedList = true;
      if (!arr[i].pid || arr[i].pid === "0") returnArr.push(arr[i]);
      const item = map[arr[i].pid];
      if (item) item.children = [...(item.children ?? []), arr[i]];
    }
    return returnArr;
  };

  /***
   * @description: 处理数据
   * @param {*} init_data 初始数据
   * @param {*} pids 调用时不用传，表示当前节点的上级id
   * @return {*} 返回带上parent和children的id数据
   */
  const treeFilter = (init_data = [], pids = []) => {
    const data = init_data;
    init_data = null;
    const res = data.map((ele) => {
      const { children = [], id } = ele;
      const childrenList = treeFilter(children, [id, ...pids]);
      let childrenIds = childrenList.reduce((pre, cur) => {
        const { id = "", childrenIds = [] } = cur;
        return [...pre, id, ...childrenIds];
      }, []);
      return {
        ...ele,
        children: childrenList,
        childrenIds,
        parentIds: pids,
      };
    });
    pids = null;
    return res;
  };

  const onGetData = () => {
    return new Promise((resolve) => {
      WlLoading({ type: "show" });
      getDept({
        pid: "",
        filter: {
          only_leader: false,
          //限定角色集合，为空则查全部角色: 1-员工 2-管理员 3-超级管理员 5-销售 6-市场
          role_types: [],
          only_dept: true,
          only_sub: true,
        },
      }).then((res) => {
        const originData = res.data?.data_list ?? [];
        const treeData = treeFilter(useArrToTree(originData));
        resolve(treeData);
        WlLoading({ type: "hide" });
      });
    });
  };

  return {
    onGetData,
  };
};

export default useHandleData;
