import { concat } from "lodash-es";
import {
  TRenderData,
  TDepartmentData,
  TCheckedStatus,
  TEmployeeData,
  TChangeRadioStatusType,
  TChangeRadioStatusParams,
  TChangeRadioStatusReturn,
} from "../../type";
import { includesArr } from "@mobileUI/utils";

//为列表数据处理选中状态
const useHandleCheckStatus = (
  list: TRenderData[],
  checkedIds?: string[],
  checkedList?: TEmployeeData[]
) => {
  /**
   * 处理员工选择器的选中状态
   * 员工列表只有选中和非选中
   * 部门列表有选中，半选和非选中
   */
  const useChangeRadioStatus = (data: TChangeRadioStatusParams): TChangeRadioStatusReturn => {
    const onJudgeEmployee = (data: TChangeRadioStatusParams): TChangeRadioStatusReturn => {
      const { checkedIds, currentItem } = data ?? {};
      const isChoosed = checkedIds.includes(currentItem.id);
      return {
        type: "hook",
        checkedStatus: isChoosed ? "checked" : "no-check",
        isChoosed,
      };
    };

    const getCheckedStatus = (
      checkedList: TEmployeeData[],
      currentItem: TDepartmentData
    ): TCheckedStatus => {
      const { childrenIds = [], id, count } = currentItem ?? {};
      //统计checkedList中的用户有多少属于当前部门下的个数
      const useCount = checkedList.reduce((acc, item) => {
        const parentIds = item.parentIds ?? [];
        if (includesArr(childrenIds, parentIds) || parentIds.includes(id)) acc++;
        return acc;
      }, 0);
      return useCount === 0 ? "no-check" : useCount === count ? "checked" : "pre-check";
    };

    const getJudgeDepartmentParams = (checkedStatus: TCheckedStatus) => {
      const type = {
        "pre-check": "icon",
        checked: "hook",
        "no-check": "icon",
      }[checkedStatus];
      const icon = checkedStatus === "pre-check" ? "prohibitFill" : "";
      const isChoosed = ["pre-check", "checked"].includes(checkedStatus);
      return {
        type: type as TChangeRadioStatusType,
        icon,
        checkedStatus,
        isChoosed,
      };
    };

    const onJudgeDepartment = (data: TChangeRadioStatusParams): TChangeRadioStatusReturn => {
      const { checkedList, currentItem } = data ?? {};
      const checkedStatus = getCheckedStatus(checkedList, currentItem as TDepartmentData);
      return getJudgeDepartmentParams(checkedStatus);
    };

    return data?.currentItem?.renderType === "employee"
      ? onJudgeEmployee(data)
      : onJudgeDepartment(data);
  };
  return (list ?? []).reduce((acc, item) => {
    //如果是部门的话需要count>0才显示
    const condition =
      ["initial", "employee"].includes(item.renderType) ||
      (item.renderType === "department" && (item as TDepartmentData).count > 0);
    return condition
      ? concat(acc, {
          ...item,
          ...useChangeRadioStatus({
            checkedIds: checkedIds ?? [],
            checkedList: checkedList ?? [],
            currentItem: item,
          }),
        })
      : acc;
  }, []);
};

export default useHandleCheckStatus;
