import '@/types/Store/Shopee/Shopee';
import lodash from 'lodash';
import { getShopeeProfileClient, getShopeeSpcfValue } from '@/api/shopee/client/shop';
import { shopeeSetting } from '@/plugins/setting';
import {
  shopeeShopCreate,
  shopeeShopUpdateShopId,
  shopeeShopRemoveShopId,
  shopeeShopGetShopId,
} from '@/api/autoshopee/shopee/shop';
import { getShopeeSellerCookies, getShopeeSellerCds, setShopeeSellerCds } from '@/api/shopee/seller/init';
import {
  getShopeSellerLogisticList,
  getShopeSellerWarehouseList,
  getShopeeSellerLogin,
  getShopeeSellerInfo,
  getShopeeSellerFallbackInfo,
} from '@/api/shopee/seller';
import { imageUrl } from '@/adapter/shopee/render/index';
import { validateShopeeApiAuthed } from '@/api/shopee/utils';
import { getTabIsCaptcha } from '@/bridge/shopee/api';
import i18n from '@/vue/i18n';
import { loggerShopee } from '@/plugins/logger';

const SHOP_INIT_INTERVAL = 5 * 60 * 1000;

/** @type {VuexStoreModule} */
export const sellerStore = {
  /**
   *
   * @returns {StoreShopeeShop}
   */
  state() {
    return {
      ref: shopeeSetting.shopeeShopRef.get(),
      id: shopeeSetting.shopeeShopId.get(),
      name: shopeeSetting.shopeeShopName.get(),
      image: shopeeSetting.shopeeShopImage.get(),
      spccds: shopeeSetting.shopeeShopSpcCds.get(),
      spcf: shopeeSetting.shopeeShopSpcf.get(),
      lastestSync: {},
      shopInfo: {},
      shopSync: {},
      shopLogistic: {
        selected: [],
        list: [],
      },
      shopWarehouse: {
        selected: [],
        list: [],
      },
      isInited: false,
      isAuthed: false,
      isCaptcha: false,
      isFetched: false,
    };
  },
  mutations: {
    /**
     *
     * @param {StoreShopeeShop} state
     * @param {ShopeeShopProfile} shopInfo
     */
    SET_SHOPEE_SELLER_INFO(state, shopInfo) {
      const shopId = shopInfo.shopid || shopInfo.shop_id;
      const username = shopInfo.username || shopInfo.user_id;

      state.id = shopId;
      state.name = username;
      state.image = imageUrl(shopInfo.portrait);
      state.shopInfo = shopInfo;
      shopeeSetting.shopeeShopId.set(state.id);
      shopeeSetting.shopeeShopName.set(state.name);
      shopeeSetting.shopeeShopImage.set(state.image);
      state.isInited = true;
    },
    SET_SHOPEE_SELLER_SHOP_ID(state, shopId) {
      state.id = shopId;
      shopeeSetting.shopeeShopId.set(shopId);
    },
    SET_SHOPEE_SELLER_SHOP_NAME(state, shopName) {
      state.name = shopName;
      shopeeSetting.shopeeShopName.set(shopName);
    },
    /**
     *
     * @param {StoreShopeeShop} state
     * @param {object} shopSync
     */
    SET_SHOPEE_SELLER_SYNC(state, shopSync) {
      state.shopSync = shopSync;
      state.ref = shopSync._id;
      shopeeSetting.shopeeShopRef.set(state.ref);
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    SET_SHOPEE_SELLER_UNSYNC(state) {
      state.shopSync = {};
      state.ref = '';
      shopeeSetting.shopeeShopRef.set('');
    },
    /**
     *
     * @param {StoreShopeeShop} state
     * @param {string} SPC_F
     */
    SET_SHOPEE_SELLER_SPC_F(state, SPC_F) {
      state.spcf = SPC_F;
      shopeeSetting.shopeeShopSpcf.set(SPC_F);
    },
    /**
     *
     * @param {StoreShopeeShop} state
     * @param {string} SPC_CDS
     */
    SET_SHOPEE_SELLER_SPC_CDS(state, SPC_CDS) {
      state.spccds = SPC_CDS;
      shopeeSetting.shopeeShopSpcCds.set(SPC_CDS);
    },
    SET_SHOPEE_SELLER_LOGISTIC(state, value) {
      state.shopLogistic.selected = value;
    },
    SET_SHOPEE_SELLER_WAREHOUSE(state, value) {
      state.shopWarehouse.selected = value;
    },
  },
  getters: {
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeShopId(state) {
      return state.id;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeShopName(state) {
      return state.name;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeShopImage(state) {
      return state.image;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeShopRef(state) {
      return state.ref;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeShopCOnnected(state) {
      return !!state.ref;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeSellerAuthed(state) {
      return state.isAuthed;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeSellerLogistic(state) {
      return state.shopLogistic;
    },
    /**
     *
     * @param {StoreShopeeShop} state
     */
    getShopeeSellerWarehouse(state) {
      return state.shopWarehouse;
    },

  },
  actions: {
    async ShopeeSellerSync({ state }) {
      /** @type {StoreShopeeShop} */
      const shopState = state;

      if (!(shopState.ref && shopState.id)) {
        return null;
      }

      const shopRef = state.ref;

      const cookies = await getShopeeSellerCookies();

      const payload = {
        cookies,
        shopId: shopState.id.toString(),
      };

      return shopeeShopUpdateShopId(shopRef, payload);
    },
    async ShopeeSellerUnSync({ state }) {
      /** @type {StoreShopeeShop} */
      const shopState = state;

      if (!(shopState.ref && shopState.id)) {
        return null;
      }

      const shopRef = shopState.ref;
      state.ref = '';

      return shopeeShopRemoveShopId(shopRef);
    },
    ShopeeSellerLogisticSet({ commit }, value) {
      commit('SET_SHOPEE_SELLER_LOGISTIC', value);
    },
    ShopeeSellerWarehouseSet({ commit }, value) {
      commit('SET_SHOPEE_SELLER_WAREHOUSE', value);
    },
    async ShopeeSellerConnect({ dispatch }) {
      const cookies = await getShopeeSellerCookies();

      const payloadCreate = {
        shopId: '',
        name: '',
        username: '',
        password: '',
        cookies,
        phone: '',
        email: '',
        image: '',
      };

      const profileClient = await getShopeeProfileClient();

      if (profileClient && profileClient.username) {
        payloadCreate.shopId = profileClient.shopid || profileClient.shop_id;
        payloadCreate.name = profileClient.username;
        payloadCreate.username = profileClient.username;
        payloadCreate.phone = profileClient.phone;
        payloadCreate.email = profileClient.email;
      } else {
        const sellerFallback = await getShopeeSellerFallbackInfo();

        if (sellerFallback) {
          payloadCreate.shopId = sellerFallback.shopId;
          payloadCreate.name = sellerFallback.shopName;
          payloadCreate.username = sellerFallback.username;
        }
      }

      if (!payloadCreate.shopId) {
        return false;
      }

      const shopCreate = await shopeeShopCreate(payloadCreate);

      dispatch('ShopeeSellerInit', true);

      return shopCreate;
    },
    async ShopeeSellerInit({ state, commit, dispatch }, isForceSync = false) {
      /** @type {StoreShopeeShop} */
      const shopState = state;

      if (isForceSync) {
        shopState.isInited = false;
      }

      if (shopState.isInited) {
        return false;
      }

      let sellerId = 0;
      const sellerInfo = await getShopeeSellerInfo();

      if (sellerInfo) {
        commit('SET_SHOPEE_SELLER_INFO', sellerInfo);
        sellerId = sellerInfo.shopid || sellerInfo.shop_id;
      } else {
        const sellerFallback = await getShopeeSellerFallbackInfo();
        sellerId = sellerFallback.shopId;
        commit('SET_SHOPEE_SELLER_SHOP_ID', sellerId);
        commit('SET_SHOPEE_SELLER_SHOP_NAME', sellerFallback.shopName);
      }

      dispatch('ShopeeSellerConfig').catch((error) => {
        loggerShopee.error({
          msg: 'SHOP_FETCH_CONFIG_ERROR',
          error,
        });
      });

      if (isForceSync) {
        const shopId = sellerId.toString();

        if (!lodash.isObject(shopState.lastestSync)) {
          shopState.lastestSync = {};
        }

        const lastestFetch = Number(shopState.lastestSync[shopId]) || 0;

        const difftime = (Date.now() - lastestFetch) || 0;

        const isReSync = !lastestFetch || difftime >= SHOP_INIT_INTERVAL;

        if (isForceSync || isReSync) {
          const shopSync = (await shopeeShopGetShopId(shopId)).data;

          if (shopSync) {
            await commit('SET_SHOPEE_SELLER_SYNC', shopSync);

            dispatch('ShopeeSellerSync').catch((error) => {
              loggerShopee.error({
                msg: 'SHOP_UPDATE_SYNC_ERROR',
                error,
              });
            });

            shopState.lastestSync[shopId] = Date.now();
          } else {
            await commit('SET_SHOPEE_SELLER_UNSYNC');
          }
        }
      }

      return true;
    },
    async ShopeeSellerConfig({ state }) {
      /** @type {StoreShopeeShop} */
      const shopState = state;

      if (shopState.isFetched) {
        return false;
      }

      const shopId = shopState.id;
      const listLogistic = await getShopeSellerLogisticList(shopId);
      const listWarehouse = await getShopeSellerWarehouseList(shopId);

      // Logistic
      const logisticPriority = listLogistic.filter(({ enabled, is_mask_channel }) => enabled && is_mask_channel);
      const logisticActive = listLogistic.filter(({ enabled, is_mask_channel }) => enabled && !is_mask_channel);

      shopState.shopLogistic.list = (logisticPriority && logisticPriority.length ? logisticPriority || [] : logisticActive || []).map(({ channel_id, name }) => {
        return {
          name,
          id: channel_id,
          value: channel_id.toString(),
          express: name.includes('Hỏa Tốc'),
          disabled: false,
        };
      });

      if (!shopState.shopLogistic.selected.length) {
        shopState.shopLogistic.selected = shopState.shopLogistic.list.map((item) => item.value);
      }

      // Warehouse
      shopState.shopWarehouse.list = listWarehouse.map((item) => {
        const extendLabel = item.in_holiday_mode ? ' (Off)' : '';

        return {
          name: item.warehouse_name + extendLabel,
          value: item.location_id,
          id: item.warehouse_id,
          disabled: item.in_holiday_mode,
        };
      });

      if (!shopState.shopWarehouse.selected.length) {
        shopState.shopWarehouse.selected = shopState.shopWarehouse.list.map((item) => item.value);
      }

      shopState.isFetched = true;

      return true;
    },
    async ShopeeSellerFetchAuth({ state, dispatch, commit }) {
      /** @type {StoreShopeeShop} */
      const shopState = state;

      let SPC_CDS = await getShopeeSellerCds();

      if (SPC_CDS) {
        commit('SET_SHOPEE_SELLER_SPC_CDS', SPC_CDS);
      }

      if (!SPC_CDS && shopState.spccds) {
        SPC_CDS = shopState.spccds;
        await setShopeeSellerCds(SPC_CDS);
      }

      if (SPC_CDS) {
        await getShopeeSellerLogin(SPC_CDS);
      }

      const captchaCheck = async () => {
        shopState.isCaptcha = await getTabIsCaptcha();

        if (shopState.isCaptcha) {
          dispatch('PushMessageError', i18n.t('SHOPEE_CAPTCHA_DETECT_RESLOVER'));
        }
      };

      shopState.isAuthed = await validateShopeeApiAuthed();

      if (!shopState.isAuthed) {
        setTimeout(async () => {
          shopState.isAuthed = await validateShopeeApiAuthed();
        }, 3000);
      }

      captchaCheck();
      setInterval(captchaCheck, 10000);

      const SPC_F = await getShopeeSpcfValue();

      if (SPC_F) {
        commit('SET_SHOPEE_SELLER_SPC_F', SPC_F);
      }

      return shopState.isAuthed;
    },
  },
};
