<template>
  <div>
    <Form
      label-position="left"
      :label-width="100"
    >
      <FormItem
        v-if="name"
        :label="$t('SHOP_USERNAME')"
      >
        <Input
          v-model="username"
          readonly
        />
      </FormItem>
      <FormItem :label="$t('SHOP_SPCF')">
        <Row>
          <Col :span="20">
            <Input
              v-model="spcf"
              :disabled="!edit.spcf"
              @on-change="changeSpcf"
            />
          </Col>
          <Col
            :span="4"
            style="padding-left: 5px"
          >
            <Checkbox
              v-model="edit.spcf"
              size="default"
            >
              {{ $t('CHANGE_BTN') }}
            </Checkbox>
          </Col>
        </Row>
      </FormItem>
      <FormItem :label="$t('SHOP_COOKIES')">
        <Row>
          <Col :span="20">
            <Input
              v-model="cookie"
              :disabled="!edit.cookie"
              @on-change="changeCookie"
            />
          </Col>
          <Col
            :span="4"
            style="padding-left: 5px"
          >
            <Checkbox
              v-model="edit.cookie"
              size="default"
            >
              {{ $t('CHANGE_BTN') }}
            </Checkbox>
          </Col>
        </Row>
      </FormItem>
      <FormItem
        v-if="isShopAuthed"
        :label="$t('SHOP_PHONE_NUMBER')"
      >
        <Input
          v-model="phone"
          readonly
        />
      </FormItem>
      <FormItem
        v-if="isShopAuthed"
        :label="$t('SHOP_EMAIL')"
      >
        <Input
          v-model="email"
          readonly
        />
      </FormItem>
      <FormItem
        v-if="isShopAuthed"
        :label="$t('SHOP_ID')"
      >
        <Input
          v-model="id"
          readonly
        />
      </FormItem>
    </Form>
    <div
      v-if="isShopAuthed"
      class="row-between mt-10"
    >
      <span>{{ msg }}</span>
      <Button
        v-if="getIsAuthed"
        size="default"
        type="success"
        :loading="loading"
        :disabled="loading"
        @click="createShop"
      >
        {{ $t('SYNC_SHOP_TO_CLOUD') }}
      </Button>
    </div>
  </div>
</template>

<script>
import Promise from 'bluebird';
import { Input } from 'view-design';
import { shopeeShopSyncSellerCreate } from '@/api/autoshopee/shopee/shop';
import { imageUrl } from '@/adapter/shopee/render/index';
import { removeKeyCookie, setKeyCookie } from '@/browser/cookies';
import { getShopeeSpcfValue, getShopeeClientCookies, getShopeeProfileClient } from '@/api/shopee/client/shop/index';
import { getShopeeSellerFallbackInfo } from '@/api/shopee/seller';
import { loggerShopee } from '@/plugins/logger';

export default {
  name: 'ShopInfo',
  data() {
    return {
      msg: '',
      name: '',
      username: '',
      id: '',
      image: '',
      password: '',
      phone: '',
      email: '',
      spcf: '',
      cookie: '',
      edit: {
        spcf: false,
        cookie: false,
      },
      listUrl: [],
      rootDomain: '',
      loading: false,
    };
  },
  methods: {
    async init() {
      this.listUrl = [this.configAppApi.shopee.home, this.configAppApi.shopee.seller];
      this.rootDomain = this.configAppApi.shopee.domain;

      this.spcf = await getShopeeSpcfValue();

      this.cookie = JSON.stringify(await getShopeeClientCookies());

      const sellerData = await getShopeeProfileClient();

      if (sellerData && sellerData.shopid) {
        this.name = sellerData.display_name;
        this.username = sellerData.username;
        this.phone = sellerData.phone;
        this.email = sellerData.email;
        this.id = sellerData.shopid;
        this.image = imageUrl(sellerData.portrait);
        return true;
      }

      const sellerFallback = await getShopeeSellerFallbackInfo();
      this.name = sellerFallback.shopName;
      this.username = sellerFallback.username;
      this.id = sellerFallback.shopId;
    },
    async setCookie(name, value, time = 0) {
      await Promise.mapSeries(this.listUrl, async (url) => {
        await removeKeyCookie(name, url).catch(() => {});
        await setKeyCookie(name, value, url, this.rootDomain, time).catch(() => {});
      });
    },
    async changeSpcf() {
      const name = 'SPC_F';
      const value = this.spcf;
      if (value) {
        await this.setCookie(name, value).catch(() => {});
        this.reloadTabCurrent(true);
      }
    },
    async changeCookie() {
      const raw = this.cookie;
      if (raw) {
        try {
          const listCookie = JSON.parse(raw);
          await Promise.mapSeries(listCookie, async ({ name, value, expirationDate }) => {
            if (name === 'SPC_F') {
              this.spcf = value;
            }
            await this.setCookie(name, value, expirationDate).catch(() => {});
          }).catch(() => {});
          this.reloadTabCurrent(true);
        } catch (error) {}
      }
    },
    async createShop() {
      this.$Modal.confirm({
        render: (h) => h(Input, {
          props: {
            autofocus: true,
            placeholder: this.$t('ENTER_SHOP_PASSWORD'),
          },
          on: {
            input: (password) => {
              this.password = password;
            },
          },
        }),
        onOk: async () => {
          this.loading = true;
          try {
            const createShop = await shopeeShopSyncSellerCreate({
              account: this.username,
              password: this.password,
              cookies: JSON.parse(this.cookie),
              id: this.id,
              spcf: this.spcf,
            });

            if (createShop.success) {
              this.$Message.success(createShop.msg);
            } else {
              this.$Message.error(createShop.msg);
            }
          } catch (error) {
            loggerShopee.error({
              msg: 'ERROR_CONNECT_SHOP',
              error,
            });
            this.$Message.error(this.$t('SHOP_CONNECT_ERROR'));
          }
          this.loading = false;
        },
      });
    },
  },
  created() {
    this.init();
  },
  computed: {
    isShopAuthed() {
      return !!this.id;
    },
  },
};
</script>
