<template>
  <div>
    <div v-if="isValid">
      <Form>
        <Row :gutter="10">
          <Col :span="16">
            <FormItem :label="$t('SHOPEE_AFFILIATE_SHORT_LINK_URL')">
              <Input
                v-model="shorLink.url"
                @on-change="handlerSortLink"
              />
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem :label="$t('SHOPEE_AFFILIATE_SHORT_LINK_RESULT')">
              <Input
                v-model="shorLink.result"
                readonly
                @click.native="copyShortLink"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>
    <div v-else>
      <Alert
        type="warning"
        class="hand-hover"
        @click.native="RouterTo('setting')"
      >
        {{ $t('SHOPEE_AFFILIATE_INVALID') }}
      </Alert>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';

export default {
  name: 'ShopeeAffialite',
  data() {
    return {
      shorLink: {
        url: '',
        result: '',
      },
    };
  },
  methods: {
    ...mapActions(['ShopeeGetShortLink']),
    async handlerSortLink() {
      if (this.shorLink.url) {
        this.shorLink.result = '';
        this.shorLink.result = await this.ShopeeGetShortLink(this.shorLink.url);
        if (this.shorLink.result) {
          this.$Message.success(this.$t('SHOPEE_AFFILIATE_SHORT_LINK_FINISH'));
        } else {
          this.$Message.error(this.$t('SHOPEE_AFFILIATE_SHORT_LINK_ERROR'));
        }
      }
    },
    copyShortLink() {
      if (this.shorLink.result) {
        this.$copyText(this.shorLink.result).then(() => {
          this.$Message.info(
            [this.$t('SHOPEE_AFFILIATE_SHORT_COPIED'), this.shorLink.result].join(' > '),
          );
        });
      }
    },
    async init() {
      await this.AppInitUrl();
      const url = this.getUrlCurrent;

      if (url.includes(this.configAppApi.shopee.home)) {
        this.shorLink.url = url;
        this.handlerSortLink();
      }
    },
  },
  created() {
    if (this.isValid) {
      this.init();
    }
  },
  computed: {
    isValid() {
      return !!(this.getAffiliateShopee.id && this.getAffiliateShopee.token);
    },
    ...mapGetters(['getAffiliateShopee']),
  },
};
</script>
