import { ref, computed } from "vue";
import { TEmployeeData } from "../../type";
import { remove, concat, uniqBy, map } from "lodash-es";

const useSelectedData = () => {
  const selectedEmployeeList = ref<TEmployeeData[]>([]);

  const selectedEmployeeIds = computed(() => selectedEmployeeList.value.map((res) => res.id));

  const onChangeSelected = (list: TEmployeeData[]) => {
    selectedEmployeeList.value = list;
  };

  const isRepeat = (idList: string[], item: TEmployeeData) => {
    return idList.includes(item.id);
  };

  const onRemoveSelected = (list: TEmployeeData[], item: TEmployeeData) => {
    return remove(list, (res) => res.id !== item.id);
  };

  //从选中列表添加或者删除，需要切换选中状态
  const onHandleSelected = (item: TEmployeeData) => {
    if (isRepeat(selectedEmployeeIds.value, item)) {
      const result = onRemoveSelected(selectedEmployeeList.value, item);
      onChangeSelected(result);
    } else {
      const result = concat(selectedEmployeeList.value, item);
      onChangeSelected(result);
    }
  };

  //将list批量添加到selectedList
  const onBatchAddSelectedList = (list: TEmployeeData[]) => {
    const result = uniqBy(concat(selectedEmployeeList.value, list), "id");
    onChangeSelected(result);
  };

  //将list批量添加到selectedList
  const onBatchRemoveSelectedList = (list: TEmployeeData[]) => {
    const ids = map(list, (res) => res.id);
    const result = remove(
      selectedEmployeeList.value,
      (res: TEmployeeData) => !ids.includes(res.id)
    );
    onChangeSelected(result);
  };

  return {
    selectedEmployeeIds,
    selectedEmployeeList,
    onChangeSelected,
    onHandleSelected,
    onBatchAddSelectedList,
    onBatchRemoveSelectedList,
  };
};

export default useSelectedData;
