import { ref, computed } from "vue";
import { TDepartmentList, TCheckedStatus } from "@mobileUI/typings/BCDepartmentSelectorPopup";

/**
 * 处理选中列表的逻辑
 */
const useCheckedData = () => {
  //当前选中的列表
  const checkedList = ref<TDepartmentList[]>([]);

  const checkedIds = computed(() => checkedList.value.map((res) => res.id));

  //获取选中的列表
  const onGetCheckedList = (list: TDepartmentList[]) => {
    return list.filter((res) => res.checkedStatus === "checked");
  };

  //添加进选中列表
  const onAddCheckdList = (list: TDepartmentList[]) => {
    //需要对添加的列表做去重
    const uniqueArr = list.reduce((acc, item) => {
      return !checkedIds.value.includes(item.id) ? [...acc, item] : acc;
    }, []);
    checkedList.value = [...checkedList.value, ...uniqueArr];
  };

  /**回显处理默认值的逻辑
   * 1. 如果defaultList里面存在当前部门的话checkedStatus为checked
   * 2. 如果defaultList里面存在下一级个别子部门的话checkedStatus为pre-checked
   * 3. 如果defaultList里面存在下一级所有子部门的话checkedStatus为checked
   */
  const onSetCheckedbyIds = (list: TDepartmentList[], idList: string[], parentChecked = false) => {
    return list.map((ele) => {
      const { children = [], id } = ele;
      const parentIsChecked = idList.includes(id);
      const data = onSetCheckedbyIds(
        children,
        idList,
        parentChecked ? parentChecked : parentIsChecked
      );
      let isChecked = parentIsChecked ? "checked" : "no-check";
      if (!parentIsChecked) {
        let childrenCheckedLen = 0,
          childrenPreCheckLen = 0;
        data.forEach((element) => {
          if (element.checkedStatus === "pre-check") {
            childrenPreCheckLen++;
          } else if (element.checkedStatus === "checked") {
            childrenCheckedLen++;
          }
        });
        if (childrenCheckedLen !== 0) {
          isChecked = childrenCheckedLen === children.length ? "checked" : "pre-check";
        } else if (childrenPreCheckLen !== 0) {
          isChecked = "pre-check";
        }
      }
      const returnData = {
        ...ele,
        children: data,
        checkedStatus: parentChecked ? "checked" : isChecked,
      };
      //如果是半选/选中状态，需要添加到checkedList中
      if ((isChecked === "checked" && idList.includes(ele.id)) || isChecked === "pre-check") {
        onAddCheckdList([returnData]);
      }
      return returnData;
    });
  };

  /**
   * 根据传入的id的list修改状态
   * @param ids 传入的id列表
   * @param status 修改的状态
   */
  const onChangeCheckedStatus = (ids: string[], status: TCheckedStatus) => {
    checkedList.value = checkedList.value.map((res) => {
      const bool = ids.includes(res.id);
      return {
        ...res,
        checkedStatus: bool ? status : res.checkedStatus,
        showInCheckedList: bool || res.showInCheckedList,
      };
    });
  };

  return {
    checkedIds,
    checkedList,
    onAddCheckdList,
    onSetCheckedbyIds,
    onChangeCheckedStatus,
    onGetCheckedList,
  };
};

export default useCheckedData;
