<template>
  <div>
    <div>
      <Button
        ghost
        type="primary"
        :disabled="!productSelected"
        size="small"
        @click="openUpdateWeight"
      >
        <span class="mr-2">{{ $t('PRODUCT_MASS_UPDATE_BTN') }}</span>
        <span>({{ productSelected }})</span>
      </Button>
    </div>
    <div>
      <Modal
        v-model="openPopup"
        :title="$t('PRODUCT_MASS_UPDATE_TITLE')"
        width="1200"
        scrollable
        :footer-hide="true"
        :mask-closable="false"
      >
        <div>
          <!-- Update Weight-->
          <Row class="mb-10">
            <Col
              :span="24"
              class="row-between"
            >
              <span>
                <InputNumber
                  v-model="updateWeight.setWeight"
                  size="small"
                  class="mr-2"
                />
                <Button
                  size="small"
                  @click="setWeightMass"
                >
                  {{ $t('SET_VALUE_BTN') }}
                </Button>
              </span>
              <Button
                type="primary"
                size="small"
                :loading="updateWeight.loading"
                @click="handlerUpdateWeight"
              >
                <span>{{ $t('UPDATE_CONFIRM_BTN') }}</span>
              </Button>
            </Col>
          </Row>
          <Row class="model-container-box">
            <Col :span="24">
              <Row class="divider-div">
                <Col
                  :span="1"
                  class="text-center"
                >
                  #
                </Col>
                <Col
                  :span="14"
                  class="text-center"
                >
                  <b>{{ $t('PRODUCT_NAME') }}</b>
                </Col>
                <Col
                  :span="2"
                  class="text-center"
                >
                  <b>{{ $t('PRODUCT_WEIGHT') }}</b>
                </Col>
                <Col
                  :span="3"
                  class="text-center"
                >
                  <b> {{ $t('PRODUCT_WEIGHT_SET') }}</b>
                </Col>
                <Col
                  :span="4"
                  class="text-center"
                >
                  <b>{{ $t('RESULT_LOG') }}</b>
                </Col>
              </Row>
            </Col>
            <Col
              v-for="(product, index) in updateWeight.list"
              :key="product.id"
              :span="24"
              class="divider-div"
            >
              <Row>
                <Col
                  :span="1"
                  class="text-center"
                >
                  {{ index + 1 }}
                </Col>
                <Col :span="14">
                  <a
                    :href="product.url"
                    target="_blank"
                  >
                    {{ product.name | maxString(100) }}
                  </a>
                </Col>
                <Col
                  :span="2"
                  class="text-center"
                >
                  {{ product.originalWeight }}
                </Col>
                <Col :span="2">
                  <Input
                    v-model="product.setWeight"
                    size="small"
                    type="number"
                  />
                </Col>
                <Col
                  :span="5"
                  class="text-center"
                >
                  <div :class="logColor(product)">
                    {{ product.log | maxString(50) }}
                  </div>
                </Col>
              </Row>
            </Col>
          </Row>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import PromiseMap from 'p-map';
import { useSellerShopeeProductUpdateStore } from '@/vue/pinia/shopee/seller/product/update';
import { shopeeSellerUpdateProductId } from '@/api/shopee/seller/product/post';
import { CacheShopeeSellerProductId } from '@/plugins/store/cache';
import { makeTabShopeeSellerProduct } from '@/bridge/shopee/tab';

const productUpdateStore = useSellerShopeeProductUpdateStore();

const removeCacheProductId = (productId) => new CacheShopeeSellerProductId(productId).remove();

export default {
  name: 'ShopeeSellerProductUpdate',
  data() {
    return {
      openPopup: false,
      updateWeight: {
        incWeight: 0,
        subWeight: 0,
        setWeight: 100,
        loading: false,
        list: [],
      },
    };
  },
  methods: {
    setWeightMass() {
      this.updateWeight.list.forEach((product) => {
        product.setWeight = Number(this.updateWeight.setWeight);
      });
    },
    openUpdateWeight() {
      this.updateWeight.list = productUpdateStore.listProduct
        .map((product) => {
          return {
            name: product.name,
            id: product.id,
            url: product.meta.sellerUrl,
            originalWeight: Number(product.weight.value),
            setWeight: Number(product.weight.value),
            unit: product.weight.unit,
            isProcessed: false,
            isSuccess: false,
            isError: false,
            log: '',
          };
        })
        .sort((a, b) => b.originalWeight - a.originalWeight);

      this.openPopup = true;

      makeTabShopeeSellerProduct();
    },
    async handlerUpdateWeight() {
      this.updateWeight.loading = true;

      await PromiseMap(
        this.updateWeight.list,
        async (product) => {
          const productId = product.id;

          product.originalWeight = Number(product.originalWeight);
          product.setWeight = Number(product.setWeight);

          product.isProcessed = true;
          product.isSuccess = false;
          product.isError = false;
          product.log = '';

          if (!(product.setWeight > 0 && product.originalWeight !== product.setWeight)) {
            product.log = this.$t('PRODUCT_UPDATE_LOG_SKIP');
            return false;
          }

          const payloadSet = {
            weight: {
              value: product.setWeight.toString(),
              unit: product.unit,
            },
          };

          try {
            const result = await shopeeSellerUpdateProductId(productId, payloadSet);

            if (result.user_message !== 'success') {
              throw {
                error: result.user_message || result.msg,
              };
            }

            product.isSuccess = true;
            product.log = this.$t('PRODUCT_UPDATE_LOG_SUCCESS');
            product.originalWeight = product.setWeight;

            removeCacheProductId(productId);
          } catch (error) {
            product.isError = false;
            product.log = error.error
              ? JSON.stringify(error)
              : this.$t('PRODUCT_UPDATE_LOG_ERRROR');
          }
        },
        {
          concurrency: 1,
        },
      );

      this.updateWeight.loading = false;
    },
    logColor({ isError, isSuccess }) {
      if (isSuccess) {
        return 'text-success';
      }

      if (isError) {
        return 'text-danger';
      }

      return '';
    },
  },
  computed: {
    productSelected() {
      return productUpdateStore.listProduct.length;
    },
  },
};
</script>
