<template>
  <div>
    <Tabs
      v-model="tabActive"
      :animated="false"
    >
      <!-- Tab general-->
      <TabPane
        :label="$t('GENERAL_SETTING')"
        name="general"
      >
        <Card
          dis-hover
          class="mt-10 mb-10"
        >
          <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>
        </Card>

        <Card
          dis-hover
          class="mb-10"
        >
          <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>
        </Card>

        <Card
          dis-hover
        >
          <Row
            :gutter="10"
            type="flex"
            align="middle"
          >
            <Col :span="8">
              <Input
                v-tooltip="$t('APP_PROFILE_ID')"
                :value="getProfileId"
                style="width: 150px"
                readonly
                size="small"
              />
            </Col>
            <Col
              :span="16"
              style="text-align: right"
            >
              <a
                href="javascript:void(0)"
                class="text-danger mr-10"
                @click="clearCache"
              >
                {{ $t('CACHE_CLEAR_ALL') }}
              </a>
              <a
                v-if="false"
                href="javascript:void(0)"
                class="text-danger"
                @click="clearSetting"
              >
                {{ $t('SETTING_CLEAR_ALL') }}
              </a>
            </Col>
          </Row>
        </Card>
      </TabPane>

      <!-- Tab Affiliate-->
      <TabPane
        v-if="getBetaMode"
        :label="$t('SHOPEE_AFFILIATE_SETTING')"
        name="shopee-affiliate"
      >
        <div>
          <a
            href="javascript:void(0)"
            class="text-danger"
            @click="openGetAff"
          >
            <b>
              {{ $t('SHOPEE_AFFILIATE_GET_APP') }}
            </b>
          </a>
        </div>
        <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>
                <ol
                  v-for="(item, index) in $t('SHOPEE_AFFILIATE_CONTENT_CHAT_CONFIG')"
                  :key="index"
                >
                  <b>{{ 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>
          <Col :span="12">
            <div>
              <Checkbox
                :value="getProductWartermark.active"
                size="default"
                style="display: flex; justify-content: center;"
                @on-change="saveProductWartermark"
              >
                <span class="ml-5"> {{ $t('WARTERMARK_IMAGE_ACTIVE') }}</span>
              </Checkbox>
            </div>
            <div style="width: 100%; display: flex; justify-content: center;">
              <base64-upload
                :style="styleWartermark"
                :image-src="imageWartermarkSrc"
                @change="onUploadWartermark"
              />
            </div>
          </Col>
          <Col :span="12">
            <div>
              <div class="size-chart-label">
                {{ $t('SHOPEE_SIZE_CHART_IMAGE') }}
              </div>
              <div
                v-if="shopeeSizeChart.listImage.length > 0"
                class="size-chart-grid"
              >
                <div
                  v-for="(image, index) in shopeeSizeChart.listImage"
                  :key="index"
                  :class="['size-chart-item', { 'size-chart-item-selected': shopeeSizeChart.selected === image }]"
                  @click="selectSizeChartImage(image)"
                >
                  <img
                    :src="image"
                    alt="Size Chart"
                    class="size-chart-thumbnail"
                  >
                  <div
                    v-if="shopeeSizeChart.selected === image"
                    class="size-chart-checkmark"
                  >
                    ✓
                  </div>
                </div>
              </div>
              <div
                v-else
                class="size-chart-empty"
              >
                {{ $t('NO_SIZE_CHART_IMAGE_AVAILABLE') }}
              </div>
              <div
                v-if="shopeeSizeChart.selected"
                class="size-chart-preview-wrapper"
              >
                <div class="size-chart-preview-label">
                  {{ $t('SELECTED_SIZE_CHART_IMAGE') }}:
                </div>
                <img
                  :src="shopeeSizeChart.selected"
                  alt="Size Chart"
                  class="size-chart-preview"
                >
              </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 scoped>
.size-chart-label {
  margin-bottom: 10px;
  font-weight: 500;
}

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

.size-chart-item {
  position: relative;
  cursor: pointer;
  border: 2px solid #ddd;
  border-radius: 4px;
  padding: 4px;
  background-color: #fff;
  transition: all 0.3s;
}

.size-chart-item-selected {
  border: 3px solid #2d8cf0;
  background-color: #e6f7ff;
}

.size-chart-thumbnail {
  width: 100%;
  height: 100px;
  object-fit: contain;
  display: block;
}

.size-chart-checkmark {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #2d8cf0;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.size-chart-empty {
  padding: 20px;
  text-align: center;
  color: #999;
}

.size-chart-preview-wrapper {
  margin-top: 15px;
}

.size-chart-preview-label {
  margin-bottom: 8px;
  font-weight: 500;
}

.size-chart-preview {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: block;
}
</style>
