<template>
  <div class="rating-container">
    <Row :gutter="24">
        <Col
          :span="16"
          :offset="4"
        >
          <!-- Configuration Card -->
          <Card
            class="config-card"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-settings"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_RATING_ORDER_CONFIG') }}</span>
            </div>

            <Alert
              v-if="isRunLimitVisible"
              type="warning"
              show-icon
              class="mb-3"
            >
              {{ $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="form-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="form-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="form-help-text">
                      {{ $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="action-button"
                      @click="handlerRatingOrder"
                    >
                      <Icon
                        type="ios-play"
                        size="16"
                      />
                      <span class="ml-1">{{ $t('SHOPEE_AUTO_RATING_ORDER_BTN') }}</span>
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Card>

          <!-- Log Card -->
          <Card
            class="log-card mt-4"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-list"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_RATING_ORDER_LOG') }}</span>
              <Badge
                :count="ratingHandler.sent"
                class="ml-2"
                type="primary"
              />
            </div>

            <div class="log-container">
              <Input
                :value="logText"
                type="textarea"
                :rows="15"
                readonly
                class="log-textarea"
              />
            </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 scoped>
  .header-content {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .header-icon {
    color: #ff9900;
  }

  .header-title {
    margin: 0;
    color: #ff9900;
    font-size: 24px;
    font-weight: 600;
  }

  .rating-container {
    padding: 24px 0;
  }

  .config-card,
  .log-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .card-title {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #333;
  }

  .form-textarea {
    resize: vertical;
    min-height: 80px;
  }

  .form-help-text {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }

  .action-button {
    width: 100%;
    height: 40px;
    font-weight: 600;
  }

  .log-container {
    position: relative;
  }

  .log-textarea {
    font-family: 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.4;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
  }

  .mt-4 {
    margin-top: 24px;
  }

  .ml-1 {
    margin-left: 4px;
  }

  .ml-2 {
    margin-left: 8px;
  }
</style>
