import axios from "axios";

import { URLS } from "../api/apiConfig";
import { TAxios } from "../api/TAxios";
import { GET_MY_INFO_ORDER_SEARCH_LIMIT } from "../utils/Config";
import { types } from "./actionTypes";
import { changeAppStatus, getTermsAgreeYn } from "./commonActions";

// 회원 주문 정보 조회 (IF-LGSP-340)
let getMyinfoOrderSearchKey = null;
let lastMyinfoOrderSearchParams = {};
export const getMyinfoOrderSearch =
  (params, forceUpdate = false, orderInfoDataIdx = 1, key, loading = true) =>
  (dispatch, getState) => {
    const { mbrNo, srchMonth, cancelOrderYn } = params;
    let limitNum = params.limitNum || GET_MY_INFO_ORDER_SEARCH_LIMIT;

    if (orderInfoDataIdx === 1) {
      // if (
      //   JSON.stringify(lastMyinfoOrderSearchParams) ===
      //     JSON.stringify(params) &&
      //   !forceUpdate
      // ) {
      //   console.log("getMyinfoOrderSearch ignore patch");
      //   return;
      // }

      lastMyinfoOrderSearchParams = params;
      dispatch(clearMyinfoOrderSearch());
    }

    if (loading) {
      dispatch(
        changeAppStatus({ showLoadingPanel: { show: true, type: "wait" } })
      );
    }

    let currentKey = key;
    const onSuccess = (response) => {
      console.log("getMyinfoOrderSearch onSuccess ", response.data);

      if (orderInfoDataIdx === 1) {
        getMyinfoOrderSearchKey = new Date();
        currentKey = getMyinfoOrderSearchKey;

        dispatch({
          type: types.GET_MY_INFO_ORDER_SEARCH,
          payload: response.data.data,
          orderSearchParams: {
            mbrNo,
            srchMonth,
            cancelOrderYn,
            limitNum,
          },
        });
      } else if (getMyinfoOrderSearchKey === currentKey) {
        dispatch({
          type: types.GET_MY_INFO_ORDER_SEARCH,
          payload: response.data.data,
          append: true,
          startIndex: (orderInfoDataIdx - 1) * limitNum,
          orderSearchParams: lastMyinfoOrderSearchParams,
        });
      }

      if (loading) {
        dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
      }
    };

    const onFail = (error) => {
      console.error("getMyinfoOrderSearch onFail ", error);
      if (loading) {
        dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
      }
      if (orderInfoDataIdx === 1) {
        lastMyinfoOrderSearchParams = {};
      }
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_MY_INFO_ORDER_SEARCH,
      {
        mbrNo,
        srchMonth,
        cancelOrderYn,
        limitNum,
        orderInfoDataIdx,
      },
      {},
      onSuccess,
      onFail
    );
  };

export const continueGetMyinfoOrderSearch =
  (orderInfoDataIdx = 2) =>
  (dispatch, getState) => {
    const state = getState();
    const orderSearchParams = state.order.orderSearchParams;
    const isCancelOrder = orderSearchParams.cancelOrderYn === "Y";
    const orderInfoData = isCancelOrder
      ? state.order.cancelOrderInfoData
      : state.order.orderInfoData;

    if (!orderInfoData || !orderInfoData.orderInfo) {
      return;
    }

    const totalCount = orderInfoData.orderInfoCount ?? 0;
    const startIndex = GET_MY_INFO_ORDER_SEARCH_LIMIT * (orderInfoDataIdx - 1);

    if (startIndex <= 1 || totalCount < startIndex) {
      return;
    }

    dispatch(
      getMyinfoOrderSearch(
        { ...lastMyinfoOrderSearchParams },
        false,
        orderInfoDataIdx,
        getMyinfoOrderSearchKey,
        false
      )
    );
  };

const clearMyinfoOrderSearch = () => ({
  type: types.CLEAR_MY_INFO_ORDER_SEARCH,
});

// 회원 주문 상세 정보 조회 (IF-LGSP-341)
export const getMyinfoOrderDetailSearch =
  (params, callback) => (dispatch, getState) => {
    const { mbrNo, ordNo, prdtId } = params;

    const onSuccess = (response) => {
      console.log("getMyinfoOrderDetailSearch onSuccess ", response.data);

      dispatch({
        type: types.GET_MY_INFO_ORDER_DETAIL_SEARCH,
        payload: response.data.data,
      });

      if (callback) callback(response.data);
    };

    const onFail = (error) => {
      console.error("getMyinfoOrderDetailSearch onFail ", error);
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_MY_INFO_ORDER_DETAIL_SEARCH,
      { mbrNo, ordNo, prdtId },
      {},
      onSuccess,
      onFail
    );
  };

export const getMyinfoOrderShippingSearch =
  (params, callback) => (dispatch, getState) => {
    const { mbrNo, ordNo, patnrId, prdtId, prodSno } = params;

    const onSuccess = (response) => {
      console.log("getMyinfoOrderShippingSearch onSuccess ", response.data);

      dispatch({
        type: types.GET_MY_INFO_ORDER_SHIPPING_SEARCH,
        payload: response.data.data,
      });

      if (callback) callback(response.data);
    };

    const onFail = (error) => {
      console.error("getMyinfoOrderShippingSearch onFail ", error);
    };

    TAxios(
      dispatch,
      getState,
      "get",
      URLS.GET_MY_INFO_ORDER_SHIPPING_SEARCH,
      { mbrNo, ordNo, patnrId, prdtId, prodSno },
      {},
      onSuccess,
      onFail
    );
  };

// 구매 약관 동의 (IF-LGSP-360)
export const setPurchaseTermsAgree = (params) => (dispatch, getState) => {
  const { mbrNo, termsList } = params;

  const onSuccess = (response) => {
    console.log("setPurchaseTermsAgree onSuccess ", response.data);

    dispatch({
      type: types.SET_PURCHASE_TERMS_AGREE,
      payload: response.data.data,
      retCode: response.data.retCode,
    });

    dispatch(getTermsAgreeYn());
  };

  const onFail = (error) => {
    console.error("setPurchaseTermsAgree onFail ", error);
  };

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.SET_PURCHASE_TERMS_AGREE,
    {},
    { mbrNo, termsList },
    onSuccess,
    onFail
  );
};

// 구매 약관 철회 (IF-LGSP-361)
export const setPurchasetermsWithdraw = (params) => (dispatch, getState) => {
  const { mbrNo, termsList } = params;

  const onSuccess = (response) => {
    console.log("setPurchasetermsWithdraw onSuccess ", response.data);

    dispatch({
      type: types.SET_PURCHASE_TERMS_WITHDRAW,
      payload: response.data.data,
      retCode: response.data.retCode,
    });

    dispatch(getTermsAgreeYn());
  };

  const onFail = (error) => {
    console.error("setPurchasetermsWithdraw onFail ", error);
  };

  TAxios(
    dispatch,
    getState,
    "post",
    URLS.SET_PURCHASE_TERMS_WITHDRAW,
    {},
    { mbrNo, termsList },
    onSuccess,
    onFail
  );
};
