import '@/types/Store/Shopee/Ads';
import '@/types/Store/Shopee/Keyword';
import lodash from 'lodash';
import { mapActions } from 'vuex';
import PromiseMap from 'p-map';
import shortHash from 'short-hash';
import { exportSheet } from '@/lib/utils/sheet';
import { extractKeywordLine } from '@/lib/utils/utils';
import { getAdsCampaignId, addKeywordCampaignId, updateKeywordCampaignId } from '@/api/shopee/seller/ads';
import { tableKeywordColumn } from './Data';
import { getKeywordTypeValue, getKeywordTypeId, getKeywordTypeLabel } from '@/vue/components/Shopee/Seller/Keyword/mixin/Data';
import SelectKeywordType from '@/vue/components/Use/Shopee/SelectKeywordType.vue';

import { defineComponent } from '@vue/composition-api';

export default defineComponent({
  props: {
    campaignId: {
      type: String,
      require: true,
    },
  },
  components: {
    'select-keyword-type': SelectKeywordType,
  },
  data() {
    return {
      loadingData: false,
      tableKeyword: {
        column: tableKeywordColumn,
        data: [],
        selected: [],
        loading: false,
      },
      campaignDetail: {
        id: '',
        name: '',
        status: '',
      },
      formCopyKeyword: {
        loading: false,
        openPopup: false,
        collectionId: '',
      },
      formImportKeyword: {
        loading: false,
        openPopup: false,
        collectionId: '',
        list: [],
        selected: [],
      },
      formAddKeyword: {
        input: '',
        list: [],
        keyword: '',
        price: 0,
      },
    };
  },
  methods: {
    ...mapActions(['ShopeeKeywordGet']),
    async getDetail() {
      this.tableKeyword.loading = true;

      const campaginData = await getAdsCampaignId(this.campaignId);

      this.campaignDetail = {
        id: campaginData.campaign.campaignid,
        name: campaginData.campaign.name,
        status: campaginData.campaign.status,
      };

      /** @type {ShopeeAdsCampaignKeyword[]} */
      let listKeyword = [];

      campaginData.advertisements.find((item) => {
        const list = lodash.get(item, 'extinfo.keywords', []);
        if (list && list.length) {
          listKeyword = list;
        }
      });

      this.tableKeyword.data = listKeyword
        .sort((a, b) => b.status - a.status)
        .map((item, index) => {
          /** @type {AdsKeywordItem} */
          const keywordItem = {
            index: index + 1,
            type: getKeywordTypeValue(item.match_type),
            id: shortHash(item.keyword),
            keyword: item.keyword,
            algorithm: item.algorithm,
            priceOld: Number(item.price),
            price: Number(item.price),
            isActive: !!item.status,
            isNew: false,
            isChange: false,
            isCreated: true,
            isUpdated: true,
            loading: false,
          };

          return keywordItem;
        });

      this.tableKeyword.loading = false;
    },
    /**
     *
     * @param {AdsKeywordItem} row
     */
    rowKeywordColor(row) {
      if (row.isNew) {
        return 'ads-warning-row';
      }

      if (row.isChange) {
        return 'ads-info-row';
      }

      if (row.isNew && row.isUpdated) {
        return 'ads-success-row';
      }

      return '';
    },
    onSelectKeyword() {
      this.tableKeyword.selected = this.$refs.TableKeyword.getSelection();
    },
    checkSelectImport(value) {
      if (value) {
        this.formImportKeyword.selected = this.formImportKeyword.list.filter((item) => item.active).map((item) => item._id);
        return true;
      }

      this.formImportKeyword.selected = [];
    },
    async onSelectImport() {
      this.formImportKeyword.list = await this.ShopeeKeywordGet(this.formImportKeyword.collectionId);
    },
    openCopyKeyword() {
      if (!this.tableKeyword.selected.length) {
        return this.$Message.error(this.$t('KEYWORD_PLEASE_SELECT'));
      }
      this.formCopyKeyword.openPopup = true;
    },
    openImportKeyword() {
      this.formImportKeyword.openPopup = true;
    },
    async handlerImportKeyword() {
      if (!this.formImportKeyword.selected.length) {
        return this.$Message.error(this.$t('KEYWORD_PLEASE_SELECT'));
      }

      /** @type {KeywordCollectionItem[]} */
      const listKeyword = this.formImportKeyword.list.filter((item) => this.formImportKeyword.selected.includes(item._id));

      listKeyword.forEach((item) => this.addNewKeyword(item));
    },
    async handlerCopyKeyword() {
      if (!this.formCopyKeyword.collectionId) {
        return false;
      }

      /** @type {KeywordCollectionItem[]} */
      const listSelected = this.tableKeyword.selected;
      const countKeyword = listSelected.length;

      this.formCopyKeyword.loading = true;

      this.$Message.info(this.$t('KEYWORD_MASS_COPY_PROCESSING', { count: countKeyword }));

      await PromiseMap(
        listSelected,
        (item) => {
          return this.ShopeeKeywordAdd({
            collectionId: this.formCopyKeyword.collectionId,
            keyword: item.keyword,
            price: item.price,
            type: item.type,
            active: item.active,
            algorithm: item.algorithm,
          });
        },
        {
          concurrency: 1,
        },
      ).catch(() => {});

      this.$Message.success(this.$t('KEYWORD_MASS_COPY_DONE', { count: countKeyword }));

      this.formCopyKeyword.loading = false;
    },
    /**
     *
     * @param {AdsKeywordItem} row
     */
    async onChangeKeyword(row) {
      row.isChange = true;
      row.isUpdated = false;
    },
    /**
     *
     * @param {AdsKeywordItem} row
     */
    async onUpdateKeyword(row) {
      row.loading = true;

      /** @type {ShopeeAdsCampaignKeyword} */
      const keywordPayload = {
        keyword: row.keyword,
        price: row.price,
        status: row.isActive ? 1 : 0,
        match_type: getKeywordTypeId(row.type),
      };

      const update = await updateKeywordCampaignId(this.campaignId, keywordPayload);

      if (update && update.debug_detail) {
        return this.$Message.error(update.debug_detail);
      }
      row.loading = false;

      row.isUpdated = true;
    },
    /**
     *
     * @param {AdsKeywordItem} row
     */
    async onSubmitKeyword(row) {
      row.loading = true;
      const { keyword } = row;
      /** @type {ShopeeAdsCampaignKeyword} */
      const keywordPayload = {
        keyword: row.keyword,
        price: row.price,
        status: 1,
        match_type: getKeywordTypeId(row.type),
      };

      const create = await addKeywordCampaignId(this.campaignId, keywordPayload);

      row.loading = false;

      if (create && create.debug_detail) {
        return this.$Message.error(create.debug_detail);
      }

      row.isChange = false;
      row.isCreated = true;

      this.$Message.success(this.$t('KEYWORD_ADD_SUCCESS', { keyword }));
    },
    addNewKeyword({
      keyword, price, type, algorithm,
    }) {
      keyword = keyword.trim();
      const isExist = this.tableKeyword.data.some((item) => item.keyword === keyword);

      if (isExist) {
        return this.$Message.error(this.$t('KEYWORD_ADD_WAS_EXIST', { keyword }));
      }

      /** @type {AdsKeywordItem} */
      const payloadAdd = {
        index: this.tableKeyword.data.length + 1,
        id: shortHash(keyword),
        type: type || 'exact',
        keyword,
        algorithm: algorithm || 'kwrcmdv3',
        priceOld: Number(price),
        price: Number(price),
        isActive: true,
        isCreated: false,
        isNew: true,
        isUpdated: true,
        isChange: false,
        loading: false,
      };

      this.tableKeyword.data.push(payloadAdd);

      this.$Message.success(this.$t('KEYWORD_ADD_SUCCESS', { keyword }));
    },
    handlerInputKeyword() {
      const listInput = extractKeywordLine(this.formAddKeyword.input);

      listInput.forEach((item) => this.addNewKeyword(item));
    },
    handleSubmitKeyword() {
      this.addNewKeyword(this.formAddKeyword);
    },
    async exportKeyword() {
      const listKeyword = this.tableKeyword.data.map(
        (
          /** @type {AdsKeywordItem} */
          item,
        ) => {
          return {
            [this.$t('KEYWORD_COLUM.KEYWORD')]: item.keyword,
            [this.$t('KEYWORD_COLUM.PRICE')]: item.price,
            [this.$t('KEYWORD_COLUM.TYPE')]: getKeywordTypeLabel(item.type),
            [this.$t('KEYWORD_COLUM.STATUS')]: item.isActive,
          };
        },
      );

      return exportSheet(listKeyword, this.$t('ADS_KEYWORD_EXPORT_SHEET', { name: this.campaignDetail.id }));
    },
  },
  created() {
    this.ShopeeKeywordFetch();
    this.getDetail();
  },
  computed: {
    addKeywordBtnActive() {
      return this.formAddKeyword.keyword && Number(this.formAddKeyword.price);
    },
  },
});
