<template>
  <div class="st-setting">
    <Tabs
      v-model="tabActive"
      class="st-setting__tabs"
      :animated="false"
    >
      <!-- Tab general-->
      <TabPane
        :label="$t('GENERAL_SETTING')"
        name="general"
      >
        <div class="st-setting__card">
          <Form>
            <Row :gutter="5">
              <Col
                v-for="setting in listStatusSet"
                :key="setting.key"
                :span="12"
              >
                <FormItem>
                  <Checkbox
                    v-model="shopeeConfig[setting.key]"
                    size="default"
                    @on-change="saveSetting"
                  >
                    <span>{{ setting.label }}</span>
                  </Checkbox>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>

        <div class="st-setting__card">
          <Row :gutter="10">
            <Col :span="6">
              <Checkbox
                :value="getBetaMode"
                size="default"
                @on-change="SetBetaMode"
              >
                {{ $t('ENABLE_BETA_MODE_FEATURE') }}
              </Checkbox>
            </Col>
            <Col :span="6">
              <Checkbox
                :value="getWorkerFetchService"
                size="default"
                @on-change="SetWorkerFetch"
              >
                {{ $t('ENABLE_WORKER_FETCH_SERVICE') }}
              </Checkbox>
            </Col>
            <Col :span="12">
              <Checkbox
                :value="getUseShopManager"
                size="default"
                disabled
                @on-change="SetUseShopManager"
              >
                {{ $t('ENABLE_USE_SHOP_MANAGER') }}
              </Checkbox>
            </Col>
          </Row>
        </div>

        <div class="st-setting__card">
          <div class="st-setting__footer">
            <Input
              v-tooltip="$t('APP_PROFILE_ID')"
              class="st-setting__profile"
              :value="getProfileId"
              readonly
              size="small"
            />
            <div class="st-setting__actions">
              <a
                href="javascript:void(0)"
                class="st-setting__link is-danger"
                @click="clearCache"
              >
                {{ $t('CACHE_CLEAR_ALL') }}
              </a>
              <a
                v-if="false"
                href="javascript:void(0)"
                class="st-setting__link is-danger"
                @click="clearSetting"
              >
                {{ $t('SETTING_CLEAR_ALL') }}
              </a>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- Tab Affiliate-->
      <TabPane
        v-if="getBetaMode"
        :label="$t('SHOPEE_AFFILIATE_SETTING')"
        name="shopee-affiliate"
      >
        <div class="st-setting__aff-head">
          <a
            href="javascript:void(0)"
            class="st-setting__link is-danger is-strong"
            @click="openGetAff"
          >
            <b>
              {{ $t('SHOPEE_AFFILIATE_GET_APP') }}
            </b>
          </a>
        </div>
        <Form class="st-setting__aff-form">
          <Row :gutter="5">
            <Col :span="8">
              <FormItem :label="$t('SHOPEE_AFFILIATE_APP_ID')">
                <Input
                  v-model="shopeeAffialite.id"
                  type="number"
                  @on-change="saveAffiliateConfig"
                />
              </FormItem>
            </Col>
            <Col :span="16">
              <FormItem :label="$t('SHOPEE_AFFILIATE_APP_TOKEN')">
                <Input
                  v-model="shopeeAffialite.token"
                  type="password"
                  @on-change="saveAffiliateConfig"
                />
              </FormItem>
            </Col>
            <Col
              v-for="(_, index) in shopeeAffialite.subId"
              :key="index"
              :span="4"
            >
              <FormItem :label="labelSubId(index)">
                <Input
                  v-model="shopeeAffialite.subId[index]"
                  @on-change="saveAffiliateSubId"
                />
              </FormItem>
            </Col>
            <Col :span="24">
              <FormItem :label="$t('SHOPEE_AFFILIATE_CONTENT_CHAT')">
                <Input
                  v-model="shopeeAffialite.content"
                  type="textarea"
                  :rows="4"
                  @on-change="saveAffiliateContent"
                />
              </FormItem>
              <ul class="st-setting__hint">
                <ol
                  v-for="(item, index) in $t('SHOPEE_AFFILIATE_CONTENT_CHAT_CONFIG')"
                  :key="index"
                  class="st-setting__hint-row"
                >
                  <b class="st-setting__hint-key">{{ index }}</b>
                  <span>:</span>
                  <span>{{ item }}</span>
                </ol>
              </ul>
            </Col>
          </Row>
        </Form>
      </TabPane>

      <!-- Tab wartermark-->
      <TabPane
        :label="$t('SHOPEE_CLONE_IMAGE_CONFIG')"
        name="shopeeClone"
      >
        <Row :gutter="16">
          <Col :span="12">
            <div class="st-setting__card st-setting__mark">
              <Checkbox
                class="st-setting__mark-toggle"
                :value="getProductWartermark.active"
                size="default"
                @on-change="saveProductWartermark"
              >
                <span class="ml-5"> {{ $t('WARTERMARK_IMAGE_ACTIVE') }}</span>
              </Checkbox>
              <div class="st-setting__mark-upload">
                <base64-upload
                  :style="styleWartermark"
                  :image-src="imageWartermarkSrc"
                  @change="onUploadWartermark"
                />
              </div>
            </div>
          </Col>
          <Col :span="12">
            <div class="st-setting__card">
              <div class="st-setting__label">
                {{ $t('SHOPEE_SIZE_CHART_IMAGE') }}
              </div>
              <div
                v-if="shopeeSizeChart.listImage.length > 0"
                class="st-setting__chart-grid"
              >
                <div
                  v-for="(image, index) in shopeeSizeChart.listImage"
                  :key="index"
                  :class="['st-setting__chart-item', { 'is-selected': shopeeSizeChart.selected === image }]"
                  @click="selectSizeChartImage(image)"
                >
                  <img
                    :src="image"
                    alt="Size Chart"
                    class="st-setting__chart-thumb"
                  >
                  <div
                    v-if="shopeeSizeChart.selected === image"
                    class="st-setting__chart-check"
                  >
                    ✓
                  </div>
                </div>
              </div>
              <div
                v-else
                class="st-setting__chart-empty"
              >
                {{ $t('NO_SIZE_CHART_IMAGE_AVAILABLE') }}
              </div>
              <div
                v-if="shopeeSizeChart.selected"
                class="st-setting__chart-preview"
              >
                <div class="st-setting__label">
                  {{ $t('SELECTED_SIZE_CHART_IMAGE') }}:
                </div>
                <img
                  :src="shopeeSizeChart.selected"
                  alt="Size Chart"
                  class="st-setting__chart-preview-img"
                >
              </div>
            </div>
          </Col>
        </Row>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import lodash from 'lodash';
import Base64Upload from 'vue-base64-upload';
import { cacheDestroyAll } from '@/plugins/store/cache';
import { wartermarkConfig, getImageSize, appendBase64Image } from '@/vue/plugins/image';
import { useLocalStorage } from '@vueuse/core';
import { getShopeePayloadClone } from '@/config/shopee';
import { STORAGE_KEYS } from '@/constant/storage';

export default {
  name: 'SettingIndex',
  components: {
    'base64-upload': Base64Upload,
  },
  data() {
    const shopeeClone = useLocalStorage(STORAGE_KEYS.LOCAL_STORAGE.SHOPEE_PRODUCT_CLONE_EDIT_DATA, getShopeePayloadClone());

    return {
      tabActive: 'general',
      shopeeConfig: {
        spyDetail: true,
        spySearch: true,
        spyAds: true,
        showShopName: false,
        addCloneBtn: true,
      },
      shopeeSizeChart: {
        listImage: [],
        selected: '',
      },
      shopeeAffialite: {
        token: '',
        id: '',
        content: '',
        subId: [],
      },
      listBadword: [],
      shopeeClone,
    };
  },
  methods: {
    ...mapActions([
      'SetWorkerFetch',
      'SetBetaMode',
      'SetClearSetting',
      'SetBadword',
      'SetSettingShopee',
      'SetSettingCloneShope',
      'ShopeeAffiliateConfig',
      'ShopeeAffiliateSubId',
      'ShopeedAffiliateContent',
      'SetWartermarkProductActive',
      'SetWartermarkProductBase64',
    ]),
    async clearCache() {
      await cacheDestroyAll();

      this.$Message.success(this.$t('CLEAR_ALL_CACHE_SUCCESS'));
    },
    clearSetting() {
      this.$Modal.confirm({
        title: this.$t('CLEAR_ALL_SETTING_CONFIRM'),
        onOk: async () => {
          this.$Message.success(this.$t('CLEAR_ALL_SETTING_SUCCESS'));
          this.UserLogout();
          this.SetClearSetting();
        },
      });
    },
    openGetAff() {
      this.openExternalUrl(this.configAppApi.shopee.affiliate.getToken);
    },
    saveSetting() {
      this.SetSettingShopee(this.shopeeConfig);
      this.$Message.success(this.$t('SAVE_SETTING_SUCCESS'));
    },
    saveAffiliateConfig() {
      this.ShopeeAffiliateConfig(this.shopeeAffialite);
      this.$Message.success(this.$t('SAVE_SETTING_SUCCESS'));
    },
    saveAffiliateSubId() {
      this.ShopeeAffiliateSubId(this.shopeeAffialite.subId);
    },
    saveAffiliateContent() {
      this.ShopeedAffiliateContent(this.shopeeAffialite.content);
    },
    saveBadword() {
      this.SetBadword(this.listBadword);
    },
    labelSubId(index) {
      return `SubId ${index + 1}`;
    },
    handlerBadword(data) {
      if (data.split(',').length > 1) {
        this.listBadword.push(...data.split(','));
        return '';
      }

      return data;
    },
    async onUploadWartermark(image) {
      if (image.type !== 'image/png') {
        this.$Message.error(this.$t('WARTERMARK_IMAGE_FORMAT_PNG'));
        return false;
      }

      const base64Image = image.base64;

      const imageSize = await getImageSize(
        appendBase64Image(base64Image),
      );

      const payloadSet = {
        base64: base64Image,
        size: imageSize,
      };

      this.SetWartermarkProductBase64(payloadSet);
      this.SetWartermarkProductActive(true);
    },
    saveProductWartermark(status) {
      this.SetWartermarkProductActive(status);
    },
    selectSizeChartImage(image) {
      this.shopeeSizeChart.selected = image;
      this.saveSizeChartSelected(image);
    },
    saveSizeChartSelected(value) {
      this.shopeeSizeChart.selected = value;
      this.shopeeClone.sizeChart = value;
      this.$Message.success(this.$t('SAVE_SETTING_SUCCESS'));
    },
    settingInit() {
      this.shopeeConfig = Object.assign(this.shopeeConfig, this.getConfigProductShopee);

      this.listBadword = this.getListBadword;
      this.shopeeAffialite = this.getAffiliateShopee;
      this.shopeeSizeChart.listImage = lodash.get(this.getPlatformShopeeConfig, 'sizeChart.listImage', []) || [];
      this.shopeeSizeChart.selected = this.shopeeClone.sizeChart;
    },
  },
  created() {
    this.settingInit();

    if (this.$route.query.tab) {
      this.tabActive = this.$route.query.tab;
    }
  },
  computed: {
    ...mapGetters([
      'getWorkerFetchService',
      'getBetaMode',
      'getUseShopManager',
      'getProfileId',
      'getConfigProductShopee',
      'getListBadword',
      'getAffiliateShopee',
      'getProductWartermark',
      'getPlatformShopeeConfig',
    ]),
    listStatusSet() {
      return [
        {
          key: 'spyDetail',
          label: this.$t('SETTING_LABEL_SPY_DETAIL_PRODUCT'),
          value: this.shopeeConfig.spyDetail,
          show: true,
        },
        {
          key: 'spyAds',
          label: this.$t('SETTING_LABEL_SPY_ADS_PRODUCT'),
          value: this.shopeeConfig.spyAds,
          show: true,
        },
        {
          key: 'spySearch',
          label: this.$t('SETTING_LABEL_SPY_LIST_PRODUCT'),
          value: this.shopeeConfig.spySearch,
          show: true,
        },
        {
          key: 'showShopName',
          label: this.$t('SETTING_LABEL_SPY_SHOP_NAME'),
          value: this.shopeeConfig.showShopName,
          show: false,
        },
        {
          key: 'addCloneBtn',
          label: this.$t('SETTING_LABEL_ADD_BTN_PRODUCT'),
          value: this.shopeeConfig.addCloneBtn,
          show: true,
        },
      ].filter((item) => item.show);
    },
    styleWartermark() {
      return {
        height: '300px',
        width: '300px',
        'background-position': 'center',
        'background-size': 'cover',
        'background-image': `url("${wartermarkConfig.productImage}")`,
      };
    },
    imageWartermarkSrc() {
      if (!this.getProductWartermark.base64) {
        return wartermarkConfig.noImage;
      }

      return `data:image/png;base64,${this.getProductWartermark.base64}`;
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.st-setting {
  &__tabs.ivu-tabs {
    color: $c-text;

    .ivu-tabs-nav .ivu-tabs-tab {
      color: $c-text;
      font-weight: 600;
      transition: color $motion-fast;

      &:hover {
        color: $c-brand-hover;
      }
    }

    .ivu-tabs-nav .ivu-tabs-tab-active {
      color: $c-brand;
    }

    .ivu-tabs-ink-bar {
      background-color: $c-brand;
    }

    .ivu-tabs-bar {
      border-bottom-color: $c-border;
    }
  }

  &__card {
    @include card;

    border: 1px solid $c-border;
    margin-bottom: 12px;

    .ivu-form-item {
      margin-bottom: 0;
    }
  }

  &__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }

  &__profile.ivu-input-wrapper {
    width: 150px;
    flex-shrink: 0;

    .ivu-input {
      border-radius: $radius-item;
      border-color: $c-border-input;
      background: $c-surface-soft;
      color: $c-text-muted;
    }
  }

  &__actions {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  &__link {
    font-size: 13px;
    font-weight: 600;
    color: $c-text;
    transition: color $motion-fast;

    &.is-danger {
      color: $c-error;
    }

    &.is-strong {
      font-size: 14px;
    }

    &:hover {
      color: $c-brand-hover;
    }
  }

  &__aff-head {
    margin: 12px 0;
  }

  &__aff-form {
    .ivu-form-item-label {
      color: $c-text-muted;
      font-size: 13px;
      font-weight: 600;
    }

    .ivu-input {
      border-radius: $radius-item;
      border-color: $c-border-input;
      color: $c-text-strong;

      &:focus {
        border-color: $c-brand;
        box-shadow: 0 0 0 2px $c-brand-tint;
      }
    }
  }

  &__hint {
    margin: 8px 0 0;
    padding: 12px;
    list-style: none;
    background: $c-surface-soft;
    border-radius: $radius-item;
    font-size: 12px;
    color: $c-text-muted;
  }

  &__hint-row {
    display: flex;
    align-items: baseline;
    gap: 4px;
    line-height: 1.7;
  }

  &__hint-key {
    color: $c-text-strong;
  }

  &__label {
    margin-bottom: 10px;
    font-size: 13px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__mark {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  &__mark-toggle {
    display: flex;
    justify-content: center;
  }

  &__mark-upload {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  &__chart-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
    margin-bottom: 10px;
  }

  &__chart-item {
    position: relative;
    cursor: pointer;
    border: 1px solid $c-border-strong;
    border-radius: $radius-item;
    padding: 4px;
    background: $c-surface;
    transition: border-color $motion-base, box-shadow $motion-base, background $motion-base;

    &:hover {
      border-color: $c-brand-hover;
      box-shadow: $shadow-card;
    }

    &.is-selected {
      border-color: $c-brand;
      background: $c-brand-tint;
    }
  }

  &__chart-thumb {
    width: 100%;
    height: 100px;
    object-fit: contain;
    display: block;
  }

  &__chart-check {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: $c-brand;
    color: $c-surface;
    font-size: 12px;
  }

  &__chart-empty {
    padding: 20px;
    text-align: center;
    font-size: 13px;
    color: $c-text-placeholder;
    background: $c-surface-soft;
    border-radius: $radius-item;
  }

  &__chart-preview {
    margin-top: 16px;
  }

  &__chart-preview-img {
    max-width: 100%;
    max-height: 300px;
    display: block;
    border: 1px solid $c-border;
    border-radius: $radius-item;
  }
}
</style>
