import type { BasicTableProps } from "@/components/VxeTable";
import { isArrayLength } from "@/utils/is";
import { reactive, computed, watch, Ref, unref, onMounted } from "vue";

/**
 * 处理费项+费用类型列表不能重复显示
 * @param feeItemCategoryList 费项类型列表
 * @param feeItemLists 费用类型列表
 * @param sourceList 表格数据源
 * @returns
 */
function useFeeCombinationFiltering(
  feeItemCategoryList: Ref<Recordable[]>,
  feeItemLists: Ref<Recordable[]>,
  sourceList: BasicTableProps,
  feeField = 'feeItemId',
  feeId = 'id'
) {
  // 费项与费用基础下拉列表数据
  const stateFeeCombination = reactive({
    feeItemCategoryRemainList: [] as Recordable[], //过滤的费项类型
    feeItemIdRemainList: [] as Recordable[], //过滤的费项类型
  });
  onMounted(() => {
    // 监听费项列表
    if (isArrayLength(unref(feeItemCategoryList)))
      stateFeeCombination.feeItemCategoryRemainList =
        unref(feeItemCategoryList);
    // 监听费用列表
    if (isArrayLength(unref(feeItemLists)))
      stateFeeCombination.feeItemIdRemainList = unref(feeItemLists);
  });
  // 监听费项列表
  watch(feeItemCategoryList, (val) => {
    if (isArrayLength(val)) stateFeeCombination.feeItemCategoryRemainList = val;
  });
  // 监听费用列表
  watch(feeItemLists, (val) => {
    if (isArrayLength(val)) stateFeeCombination.feeItemIdRemainList = val;
  });
  // 获取新增或编辑的表格数据
  const sourceTableList = computed(() => sourceList.data || []);

  // 显示下拉列表触发-费项
  const feeItemCategoryVisibleChange = (val: boolean, row: Recordable) => {
    if (!val)
      return (stateFeeCombination.feeItemCategoryRemainList =
        unref(feeItemCategoryList));
    // 当前费用id
    const currentFeeItemId = row[feeField];
    // 费项类型 id 列表
    const feeItemCategoryIdKeys = unref(sourceTableList)
      .map((item) => {
        // 费用相同取已使用的费项类型
        if (item[feeField] === currentFeeItemId) return item.feeItemCategoryId;
      })
      .filter((key) => key);
    // 排除已使用的费项类型
    stateFeeCombination.feeItemCategoryRemainList = unref(
      feeItemCategoryList
    ).filter((item) => !feeItemCategoryIdKeys.includes(item.value));
  };
  // 显示下拉列表触发-费用
  const feeItemIdVisibleChange = (val: boolean, row: Recordable) => {
    if (!val)
      return (stateFeeCombination.feeItemIdRemainList = unref(feeItemLists));
    // 当前费项 id
    const currentFeeItemCategoryId = row.feeItemCategoryId;
    // 费项类型 id 列表
    const feeItemIdKeys = unref(sourceTableList)
      .map((item) => {
        // 费项相同取已使用的费用类型
        if (item.feeItemCategoryId === currentFeeItemCategoryId)
          return item[feeField];
      })
      .filter((key) => key);
    // 排除已使用的费用类型
    stateFeeCombination.feeItemIdRemainList = unref(feeItemLists).filter(
      (item) => !feeItemIdKeys.includes(item[feeId])
    );
  };

  return {
    stateFeeCombination,
    feeItemCategoryVisibleChange,
    feeItemIdVisibleChange,
  };
}

export { useFeeCombinationFiltering };
