import lodash from 'lodash';
import { mapActions, mapGetters } from 'vuex';
import moment from 'moment';
import { getFlashSaleId } from '@/api/shopee/seller/flashsale';
import {
  apiFlashsaleCampaignCreate, apiFlashsaleCampaignList, apiFlashsaleCampaignRemove, apiFlashsaleCampaignUpdate,
} from '@/api/autoshopee/shopee/flashsale';
import { ShopeeFlashSaleSave } from '@/models/shopee/seller/flashsale';
import { flashSaleSeller } from '@/adapter/shopee/render/index';
import { useStorage, useSessionStorage } from '@vueuse/core';
import { STORAGE_KEYS } from '@/constant/storage';
import { createScheduleFromCampaignId } from '@/service/shopee/flashsale/campaign';
import { loggerShopee } from '@/plugins/logger';

const hasTimeOverlap = (timeRanges) => {
  const validRanges = timeRanges
    .filter((r) => Array.isArray(r) && r.length === 2 && Number.isFinite(r[0]) && Number.isFinite(r[1]))
    .map(([start, end]) => ({ start, end }));

  validRanges.sort((a, b) => a.start - b.start);

  for (let i = 0; i < validRanges.length - 1; i++) {
    const current = validRanges[i];
    const next = validRanges[i + 1];

    if (current.end > next.start) {
      return {
        isOverlap: true,
        conflict: [current, next],
      };
    }
  }

  return {
    isOverlap: false,
  };
};

export default {
  data() {
    /** @type {number} */
    const timeFlashsaleBefore = useStorage(STORAGE_KEYS.LOCAL_STORAGE.SHOPEE_FLASHSALE_CAMPAIGN_TIME_FLASHSALE_BEFORE, 48);

    /** @type {number} */
    const daySchedulerBefore = useStorage(STORAGE_KEYS.LOCAL_STORAGE.SHOPEE_FLASHSALE_CAMPAIGN_DAY_SCHEDULER_BEFORE, 7);

    /** @type {number} */
    const timeSchedulerBefore = useStorage(STORAGE_KEYS.LOCAL_STORAGE.SHOPEE_FLASHSALE_CAMPAIGN_TIME_SCHEDULER_BEFORE, 48);

    /** @type {FlashSaleCampagin[]} */
    const listFsSave = useSessionStorage(STORAGE_KEYS.SESSION_STORAGE.SHOPEE_FLASHSALE_CAMPAIGN_SAVE, []) || [];

    /** @type {FlashSaleCampaignScheduler[]} */
    const listCampaign = useSessionStorage(STORAGE_KEYS.SESSION_STORAGE.SHOPEE_FLASHSALE_CAMPAIGN_LIST, []) || [];

    /**
      @type {ShopeeFsIndexListItem[]}
     */
    const listIndex = [];

    /**
       @type {ShopeeFsSetListItem[]}
     */
    const listSet = [];

    const createCampaign = {
      shopRef: '',
      campaignName: '',
      shopId: '',
      flashsaleIdClone: '',
      productCount: 0,
      timeFlashsaleBefore,
      timeSchedulerBefore,
      daySchedulerBefore,
      listSet,
      listIndex,
      timeSlotStart: 0,
      timeSlotEnd: 24,
      timeCampaginStart: moment().startOf('year').toDate(),
      timeCampaginEnd: moment().endOf('year').toDate(),
    };

    const listTimeSlot = Array.from({ length: 25 }, (_, index) => {
      return {
        value: index,
        label: `${String(index).padStart(2, '0')}:00`,
      };
    });

    return {
      enableAuto: false,
      tabActive: 'list',
      createCampaign,
      btnLoading: false,
      isEmpty: false,
      listCampaign,
      listTimeSlot,
      listFlashsale: listFsSave,
      errorMessage: '',
      logMessage: '',
    };
  },
  methods: {
    ...mapActions(['SetShopeeFlashsaleCampagin', 'SetShopeeFlashsaleCampaignAuto', 'RunShopeeFlashsaleAutoScheduler', 'RunShopeeFlashsaleAutoCampaign', 'FetchShopeeFlashsaleList']),
    openFlashsaleId(id) {
      return flashSaleSeller(id);
    },
    /**
     *
     * @param {FlashSaleCampaignScheduler} campagin
     */
    openCloneFlashsale(campagin) {
      const openUrl = this.openFlashsaleId(campagin.flashsaleIdClone);
      this.openExternalUrl(openUrl, true);
    },
    /**
     *
     * @param {FlashSaleCampaignScheduler} campagin
     * @param {boolean} active
     */
    toggleCampaign(campagin, active) {
      campagin.active = active;

      const payloadUpdate = {
        timeFlashsaleBefore: campagin.timeFlashsaleBefore,
        timeSchedulerBefore: campagin.timeSchedulerBefore,
        active,
      };
      return apiFlashsaleCampaignUpdate(campagin._id, payloadUpdate);
    },
    /**
     *
     * @param {FlashSaleCampaignScheduler} campagin
     */
    async runCampaign(campagin) {
      const campaginName = campagin.campaignName;

      /**
       * @param {{flashsaleScheduler: FlashSaleListScheduler, current: number, total: number}} payload
       */
      const callbackScheduler = (payload) => {
        const {
          flashsaleScheduler,
          current,
          total,
        } = payload;

        const logMessage = this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_LOG_RUNNING', {
          time: flashsaleScheduler.timeSlot.labelTime,
          current,
          total,
        });

        this.logMessage = `[${campaginName}] - ${logMessage}`;
        this.FetchShopeeFlashsaleList();
      };

      campagin.loading = true;

      await createScheduleFromCampaignId(campagin._id, callbackScheduler).then((listFlashsaleScheduler) => {
        if (listFlashsaleScheduler.length) {
          this.logMessage = `[${campaginName}] - ${this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_LOG_COMPLETE')}`;
          this.RunShopeeFlashsaleAutoScheduler();
        } else {
          this.logMessage = `[${campaginName}] - ${this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_LOG_EMPTY')}`;
        }
      }).catch((error) => {
        loggerShopee.error({
          msg: 'RUN_CAMPAIGN_ERROR',
          error,
          campagin,
        });

        this.logMessage = `[${campaginName}] - ${this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_LOG_ERROR')}`;
      });

      campagin.loading = false;

      const campaginUpdate = this.listCampaign.find((item) => item._id === campagin._id);
      campaginUpdate.loading = false;
    },
    /**
     *
     * @param {FlashSaleCampaignScheduler} campagin
     */
    removeCampaign(campagin) {
      this.$Modal.confirm({
        content: campagin.campaignName,
        title: this.$t('REMOVE_CONFIRM'),
        onOk: async () => {
          this.listCampaign = this.listCampaign.filter((item) => item._id !== campagin._id);
          this.$Message.success(this.$t('REMOVE_SUCCESS'));

          apiFlashsaleCampaignRemove(campagin._id);
        },
      });
    },
    async handlerCreate() {
      if (this.validateErrorMessage) {
        return false;
      }

      /** @type {FlashSaleCampaignScheduler} */
      const payloadCreate = lodash.cloneDeep(this.createCampaign);

      if (!payloadCreate.campaignName) {
        this.errorMessage = this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_ENTER_CAMPAIGN_NAME');

        return false;
      }

      if (!payloadCreate.flashsaleIdClone) {
        this.errorMessage = this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_SELECT_FALSHSALE_ERROR');

        return false;
      }

      this.errorMessage = '';

      this.btnLoading = true;

      const shopId = this.getShopeeShopId.toString();
      const shopName = this.getShopeeShopName;

      payloadCreate.shopId = shopId;
      payloadCreate.shopName = shopName;

      if (payloadCreate.daySchedulerBefore) {
        payloadCreate.timeSchedulerBefore = Number(payloadCreate.daySchedulerBefore) * 24;
      }

      try {
        const flashsaleId = payloadCreate.flashsaleIdClone;

        const flashsaleData = await getFlashSaleId(flashsaleId);

        if (!(flashsaleData && flashsaleData.total_count)) {
          this.errorMessage = this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_GET_DATA_ERROR');
          return false;
        }

        payloadCreate.listSet = flashsaleData.items.map((item) => ({
          item_id: item.item_id,
          status: item.status,
          model_id: item.model_id,
          input_promo_price: item.input_promotion_price,
          stock: item.stock,
          purchase_limit: item.purchase_limit,
        }));

        payloadCreate.listIndex = flashsaleData.item_info.map((product, index) => {
          return {
            item_id: product.itemid,
            display_sequence: index + 1,
          };
        });

        payloadCreate.productCount = Number(flashsaleData.total_count);

        payloadCreate.timeSlotStart = Number(payloadCreate.timeSlotStart);
        payloadCreate.timeSlotEnd = Number(payloadCreate.timeSlotEnd);

        if (!payloadCreate.shopRef) {
          delete payloadCreate.shopRef;
        }

        const campaignFlashsale = await apiFlashsaleCampaignCreate(payloadCreate);

        if (!campaignFlashsale) {
          this.errorMessage = this.$t('CREATE_ERROR');
          this.btnLoading = false;
          return false;
        }

        this.listCampaign.push(campaignFlashsale);
      } catch (error) {
        loggerShopee.error({
          msg: 'CREATE_FLASHSALE_CAMPAIGN_ERROR',
          error,
        });
      }

      this.tabActive = 'list';
      this.createCampaign.campaignName = '';
      this.btnLoading = false;
    },
    async initCampaign() {
      const shopId = this.getShopeeShopId.toString();

      if (shopId) {
        this.listCampaign = (await apiFlashsaleCampaignList(shopId)).map((item) => ({
          ...item,
          loading: false,
        }));
      } else {
        this.listCampaign = [];
      }

      if (!this.listCampaign.length) {
        this.isEmpty = true;

        setTimeout(() => {
          this.tabActive = 'create';
        }, 1000);
      }

      this.listFlashsale = await ShopeeFlashSaleSave.findMany({
        shopId,
      });
    },
  },
  created() {
    this.enableAuto = this.getShopeeFlashsaleCampaignJob.auto;

    this.initCampaign();
  },
  computed: {
    ...mapGetters(['getShopeeFlashsaleCampaignJob']),
    validateErrorMessage() {
      if (Number(this.createCampaign.timeSlotStart) > Number(this.createCampaign.timeSlotEnd)) {
        return this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_PICK_TIME_SLOT_ERROR');
      }

      if (moment(this.createCampaign.timeCampaginStart) > moment(this.createCampaign.timeCampaginEnd)) {
        return this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_PICK_TIME_CAMPAGIN_ERROR');
      }

      return '';
    },
    warningTimeSlot() {
      const listSotTime = this.listCampaign.filter((item) => item.active).map((item) => [item.timeSlotStart, item.timeSlotEnd]);

      const { isOverlap } = hasTimeOverlap(listSotTime);
      return isOverlap ? this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_TIME_SLOT_MAY_BE_DUPLICATED') : '';
    },
    btnDisabled() {
      return !(!this.validateErrorMessage && this.createCampaign.campaignName && this.createCampaign.flashsaleIdClone && this.getShopeeShopId);
    },
    campaginDescription() {
      if (!this.createCampaign.flashsaleIdClone) {
        return '';
      }

      const getFlashsale = this.listFlashsale.find((item) => item.flashSaleId === this.createCampaign.flashsaleIdClone);

      return this.createCampaign.flashsaleIdClone ? this.$t('FLASHSALE_CAMPAGIN_SCHEDULER_DESCRIPTION', {
        flashsale: getFlashsale.name,
        hour: this.createCampaign.timeFlashsaleBefore,
        day: this.createCampaign.daySchedulerBefore,
        from: `${this.createCampaign.timeSlotStart}:00`,
        to: `${this.createCampaign.timeSlotEnd}:00`,
      }) : '';
    },
    listCampaignShow() {
      return this.listCampaign;
    },
  },
  watch: {
    listCampaign(listCampaign) {
      this.SetShopeeFlashsaleCampagin(listCampaign);
    },
  },
};
