import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { buildOseCardPreviewUrl } from "@/module/ose-card/service/card-url";

export const useOseCardListPage = ({ store, router, tableColumns }) => {
  const search = ref("");
  const carouselDaysSearch = ref(false);
  const tableLoad = ref(true);

  const filterTableData = computed(() => {
    let searchResult = store.state.ose_card_store.card_list;

    if (search.value) {
      searchResult = searchResult.filter((data) => {
        for (const column of tableColumns) {
          try {
            if (
              data[column.id]
                .toLowerCase()
                .includes(search.value.toLowerCase())
            ) {
              return true;
            }
          } catch (error) {
            continue;
          }
        }

        return false;
      });
    }

    if (carouselDaysSearch.value) {
      searchResult = searchResult.filter((data) => data.carousel_days > 0);
    }

    return searchResult;
  });

  const openEditPage = async (queryParams) => {
    tableLoad.value = true;
    await router.push({
      name: "ose-card-edit",
      query: queryParams,
    });
    tableLoad.value = false;
  };

  const loadCardList = async () => {
    tableLoad.value = true;
    await store.dispatch(
      "ose_card_store/getCardList",
      store.state.user.current_corporate_customer
    );
    tableLoad.value = false;
  };

  const previewCard = (rowItem) => {
    window.open(buildOseCardPreviewUrl(rowItem.landing_page, rowItem.card_code));
  };

  const editCard = (rowItem) => {
    store.commit("ose_card_store/edit_card_data", rowItem);
    openEditPage({
      id: rowItem.id,
      mode: "edit",
    });
  };

  const copyCard = (rowItem) => {
    store.commit("ose_card_store/edit_card_data", rowItem);
    openEditPage({
      id: rowItem.id,
      mode: "copy",
    });
  };

  const deleteCard = async (rowItem) => {
    try {
      await ElMessageBox.confirm("請再次確認是否該刪除？", "注意", {
        confirmButtonText: "確認",
        cancelButtonText: "取消",
        type: "warning",
      });

      tableLoad.value = true;
      await store.dispatch("ose_card_store/deleteCard", rowItem.id);
      tableLoad.value = false;

      ElMessage({
        type: "success",
        message: "刪除成功",
      });
    } catch (error) {
      tableLoad.value = false;
      ElMessage({
        type: "info",
        message: "刪除取消",
      });
    }
  };

  return {
    search,
    carouselDaysSearch,
    tableLoad,
    filterTableData,
    openEditPage,
    loadCardList,
    previewCard,
    editCard,
    copyCard,
    deleteCard,
  };
};
