<template>
  <div class="au-rating">
    <Row :gutter="24">
      <Col
        :span="16"
        :offset="4"
      >
        <Card
          class="au-rating__card"
          :bordered="false"
        >
          <div
            slot="title"
            class="au-rating__title"
          >
            <Icon
              class="au-rating__title-icon"
              type="ios-settings"
              size="18"
            />
            <span class="au-rating__title-text">
              {{ $t('SHOPEE_AUTO_RATING_ORDER_CONFIG') }}
            </span>
          </div>

          <Alert
            v-if="isRunLimitVisible"
            class="au-rating__alert"
            type="warning"
            show-icon
          >
            {{ $t('FEATURE_RUN_LIMIT_INFO', { limit: autoRunLimit }) }}
          </Alert>

          <Form
            :model="formData"
            :label-width="120"
          >
            <Row :gutter="16">
              <Col :span="12">
                <FormItem :label="$t('SHOPEE_AUTO_RATING_ORDER_INPUT_CONTENT')">
                  <Input
                    v-model="ratingOrder.text"
                    type="textarea"
                    :rows="4"
                    :placeholder="$t('SHOPEE_AUTO_RATING_ORDER_INPUT_CONTENT')"
                    class="au-rating__textarea"
                  />
                </FormItem>
              </Col>

              <Col :span="12">
                <FormItem :label="$t('SHOPEE_AUTO_RATING_ORDER_INPUT_CHAT')">
                  <Input
                    v-model="chatOrder.text"
                    type="textarea"
                    :rows="4"
                    :placeholder="$t('INPUT_PLACEHOLDER_EMPTY_WITHOUT_USE')"
                    class="au-rating__textarea"
                  />
                </FormItem>
              </Col>
            </Row>

            <Row :gutter="16">
              <Col :span="12">
                <FormItem :label="$t('ORDER_PAGE_START')">
                  <InputNumber
                    v-model="queryOrder.page"
                    :min="1"
                    :max="maxPage"
                    :disabled="ratingHandler.loading"
                    style="width: 100%"
                    :placeholder="$t('ORDER_PAGE_START')"
                  />
                  <div class="au-rating__help">
                    {{ $t('MAX_PAGE', { page: maxPage }) }}
                  </div>
                </FormItem>
              </Col>

              <Col :span="12">
                <FormItem label=" ">
                  <Button
                    type="primary"
                    size="large"
                    :loading="ratingHandler.loading"
                    :disabled="!ratingOrder.text || isRunLimitReached"
                    class="au-rating__run"
                    @click="handlerRatingOrder"
                  >
                    <Icon
                      type="ios-play"
                      size="16"
                    />
                    <span class="au-rating__run-text">
                      {{ $t('SHOPEE_AUTO_RATING_ORDER_BTN') }}
                    </span>
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card
          class="au-rating__card au-rating__card--log"
          :bordered="false"
        >
          <div
            slot="title"
            class="au-rating__title"
          >
            <Icon
              class="au-rating__title-icon"
              type="ios-list"
              size="18"
            />
            <span class="au-rating__title-text">
              {{ $t('SHOPEE_AUTO_RATING_ORDER_LOG') }}
            </span>
            <Badge
              class="au-rating__title-badge"
              :count="ratingHandler.sent"
              type="primary"
            />
          </div>

          <div class="au-rating__log">
            <Input
              :value="logText"
              type="textarea"
              :rows="15"
              readonly
              class="au-rating__log-text"
            />
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import lodash from 'lodash';
import delay from 'delay';
import PromiseMap from 'p-map';
import { getListOrderCompleted, getListOrderIndex } from '@/api/shopee/seller/order/list';
import { ratingOrderCompleted } from '@/api/shopee/seller/order/post';
import { sendChatMessage } from '@/api/shopee/seller/chat';
import { SHOPEE_AUTO_RUN_LIMITS } from '@/constant/shopee';

export default {
  name: 'ShopeeAutoReplyReview',
  data() {
    return {
      formData: {},
      ratingOrder: {
        text: this.$t('SHOPEE_AUTO_RATING_ORDER_PARAM_TEXT'),
        star: 5,
      },
      chatOrder: {
        text: '',
      },
      ratingHandler: {
        loading: false,
        log: [],
        sent: 0,
        sleepPerList: 15000,
        sleepPerRating: 200,
      },
      queryOrder: {
        limit: 40,
        page: 1,
        setensel: '',
        total: 0,
        isStopped: false,
        isError: false,
      },
    };
  },
  methods: {
    async fetchMeta() {
      const resultIndex = await getListOrderIndex(1, 0, '', 500);
      this.queryOrder.total = resultIndex.totalOrder;
    },
    async handlerRatingOrder() {
      this.ratingHandler.loading = true;
      this.ratingHandler.sent = 0;

      this.queryOrder.setensel = '';
      this.queryOrder.page = Number(this.queryOrder.page) || 1;

      let isAllow = true;

      for (let i = this.queryOrder.page; i < 1000; i++) {
        const { limit, page, setensel } = this.queryOrder;

        const fetchResult = await getListOrderCompleted(limit, page, setensel);

        if (fetchResult.isError) {
          this.queryOrder.isError = true;
        }

        if (!fetchResult.listOrder.length) {
          this.queryOrder.isStopped = true;
          this.ratingHandler.log.push(this.$t('SHOPEE_AUTO_RATING_ORDER_EMPTY', { page }));

          break;
        }

        if (fetchResult.nextsentinel) {
          this.queryOrder.setensel = fetchResult.nextsentinel;
        }

        if (fetchResult.totalOrder) {
          this.queryOrder.total = fetchResult.totalOrder;
        }

        this.queryOrder.page++;

        /** @type {ShopeeSellerOrderCard[]} */
        const listOrderRating = fetchResult.listOrder.filter(
          (order) => order.order_ext_info.is_order_ratable,
        );

        if (listOrderRating.length) {
          await PromiseMap(
            listOrderRating,
            async (orderData) => {
              if (!isAllow) {
                return false;
              }

              const { text, star } = this.ratingOrder;
              const orderId = orderData.order_ext_info.order_id;
              const buyerId = orderData.order_ext_info.buyer_user_id;
              const buyerName = orderData.card_header.buyer_info.username;

              const payloadLog = {
                order_id: orderId,
                buyer: buyerName,
                text,
                star,
                page,
              };

              await ratingOrderCompleted(orderId, text, star)
                .then(() => {
                  this.ratingHandler.log.push(
                    `✅ ${this.$t('SHOPEE_AUTO_RATING_ORDER_SENT_SUCCESS', payloadLog)}`,
                  );
                })
                .catch(() => {
                  this.ratingHandler.log.push(
                    `❌ ${this.$t('SHOPEE_AUTO_RATING_ORDER_SENT_ERROR', payloadLog)}`,
                  );
                });

              if (this.chatOrder.text) {
                const toUserId = buyerId;
                const toShopId = buyerId;

                const textChat = this.chatOrder.text;

                const payloadLog = {
                  text: textChat,
                };

                sendChatMessage(toUserId, toShopId, textChat)
                  .then(() => {
                    this.replyHandler.log.push(
                      `✅ ${this.$t('SHOPEE_AUTO_CHAT_ORDER_SENT_SUCCESS', payloadLog)}`,
                    );
                  })
                  .catch(() => {
                    this.replyHandler.log.push(
                      `❌ ${this.$t('SHOPEE_AUTO_CHAT_ORDER_SENT_ERROR', payloadLog)}`,
                    );
                  });
              }

              this.ratingHandler.log.push('-------------');

              this.ratingHandler.sent += 1;

              if (this.ratingHandler.sent >= this.autoRunLimit) {
                const msg = this.$t('FEATURE_RUN_LIMIT_REACHED', {
                  sent: this.ratingHandler.sent,
                  limit: this.autoRunLimit,
                });
                this.$Message.warning(msg);
                this.ratingHandler.log.push(msg);
                isAllow = false;
              }

              await delay(this.ratingHandler.sleepPerRating);
            },
            {
              concurrency: 1,
            },
          );
        } else {
          this.ratingHandler.log.push(this.$t('SHOPEE_AUTO_RATING_ORDER_EMPTY', { page }));
        }

        if (!isAllow) {
          break;
        }

        this.ratingHandler.log.push(
          this.$t('SLEEP_TINE', { wait: `${this.ratingHandler.sleepPerList / 1000}s` }),
        );

        await delay(this.ratingHandler.sleepPerList);
      }

      this.ratingHandler.loading = false;
    },
  },
  created() {
    this.fetchMeta();
  },
  computed: {
    logText() {
      return this.ratingHandler.log.join('\n');
    },
    maxPage() {
      if (!this.queryOrder.total) {
        return 0;
      }
      return lodash.round(this.queryOrder.total / this.queryOrder.limit, 0);
    },
    autoRunLimit() {
      const config = SHOPEE_AUTO_RUN_LIMITS.ratingOrder[this.getUserPlan];
      if (config) {
        return config.runLimit;
      }
      return 0;
    },
    isRunLimitVisible() {
      return Number.isFinite(this.autoRunLimit) && this.autoRunLimit > 0;
    },
    isRunLimitReached() {
      return this.isRunLimitVisible && this.ratingHandler.sent >= this.autoRunLimit;
    },
  },
};
</script>

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

.au-rating {
  padding: 24px 0;

  &__card {
    &.ivu-card {
      background: $c-surface;
      border-radius: $radius-card;
      box-shadow: $shadow-card;
      transition: box-shadow $motion-base;
    }

    &.ivu-card:hover {
      box-shadow: $shadow-hover;
    }

    &--log.ivu-card {
      margin-top: 24px;
    }
  }

  &__title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__title-icon {
    color: $c-brand;
  }

  &__title-text {
    @include ellipsis;
  }

  &__title-badge {
    margin-left: 2px;
  }

  &__alert.ivu-alert {
    margin-bottom: 16px;
    border-radius: $radius-item;
    background: $c-warning-bg;
    border-color: transparent;
    color: $c-text;
  }

  &__textarea {
    ::v-deep textarea.ivu-input {
      resize: vertical;
      min-height: 80px;
      border-radius: $radius-item;
      border-color: $c-border-input;
      color: $c-text-strong;
      transition: border-color $motion-fast, box-shadow $motion-fast;
    }

    ::v-deep textarea.ivu-input::placeholder {
      color: $c-text-placeholder;
    }
  }

  &__help {
    margin-top: 4px;
    font-size: 12px;
    color: $c-text-muted;
  }

  &__run.ivu-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    width: 100%;
    height: 40px;
    font-weight: 600;
    border-radius: $radius-item;
    background: $c-brand;
    border-color: $c-brand;
    transition: background $motion-fast, border-color $motion-fast, box-shadow $motion-base;
  }

  &__run.ivu-btn:hover,
  &__run.ivu-btn:focus {
    background: $c-brand-hover;
    border-color: $c-brand-hover;
    box-shadow: $shadow-hover;
  }

  &__run.ivu-btn[disabled],
  &__run.ivu-btn[disabled]:hover {
    background: $c-surface-alt;
    border-color: $c-border-input;
    color: $c-text-placeholder;
    box-shadow: none;
  }

  &__log {
    position: relative;
  }

  &__log-text {
    ::v-deep textarea.ivu-input {
      font-family: 'Courier New', monospace;
      font-size: 13px;
      line-height: 1.5;
      color: $c-text;
      background: $c-surface-soft;
      border: 1px solid $c-border;
      border-radius: $radius-item;
      resize: vertical;

      @include scrollbar;
    }
  }
}
</style>
