<template>
  <div class="au-reply">
    <Row :gutter="24">
      <Col
        :span="16"
        :offset="4"
      >
        <Card
          class="au-reply__card"
          :bordered="false"
        >
          <div
            slot="title"
            class="au-reply__title"
          >
            <Icon
              class="au-reply__title-icon"
              type="ios-code"
              size="18"
            />
            <span class="au-reply__title-text">
              {{ $t('SHOPEE_AUTO_REPLY_RATING_VARIABLES') }}
            </span>
          </div>

          <div class="au-reply__vars">
            <div
              v-for="(matchValue, matchKey) in matchText"
              :key="matchKey"
              class="au-reply__var"
            >
              <Tag
                color="blue"
                class="au-reply__var-tag"
              >
                {{ matchKey }}
              </Tag>
              <span class="au-reply__var-desc">{{ matchValue }}</span>
            </div>
          </div>
        </Card>

        <Card
          class="au-reply__card au-reply__card--gap"
          :bordered="false"
        >
          <div
            slot="title"
            class="au-reply__title"
          >
            <Icon
              class="au-reply__title-icon"
              type="ios-settings"
              size="18"
            />
            <span class="au-reply__title-text">
              {{ $t('SHOPEE_AUTO_REPLY_RATING_CONFIG') }}
            </span>
          </div>

          <Alert
            v-if="isRunLimitVisible"
            class="au-reply__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_REPLY_RATING_INPUT_CONTENT')">
                  <Input
                    v-model="replyRating.text"
                    type="textarea"
                    :rows="4"
                    :placeholder="$t('SHOPEE_AUTO_REPLY_RATING_INPUT_CONTENT')"
                    class="au-reply__textarea"
                  />
                </FormItem>
              </Col>

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

            <Row :gutter="16">
              <Col :span="12">
                <FormItem :label="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')">
                  <Select
                    v-model="queryRating.star"
                    multiple
                    style="width: 100%"
                    :placeholder="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')"
                    @on-change="getchMetaRating"
                  >
                    <Option
                      v-for="star in [1, 2, 3, 4, 5]"
                      :key="star"
                      :value="star"
                    >
                      {{ $t('RATING_STAR', { star }) }}
                    </Option>
                  </Select>
                  <div class="au-reply__help">
                    {{ $t('SHOPEE_AUTO_REPLY_RATING_STAR_HELP') }}
                  </div>
                </FormItem>
              </Col>

              <Col :span="12">
                <FormItem label=" ">
                  <Button
                    type="primary"
                    size="large"
                    :loading="replyHandler.loading"
                    :disabled="!(replyRating.text && queryRating.star.length) || isRunLimitReached"
                    class="au-reply__run"
                    @click="handleReplyRating"
                  >
                    <Icon
                      type="ios-play"
                      size="16"
                    />
                    <span class="au-reply__run-text">
                      {{ $t('SHOPEE_AUTO_REPLY_RATING_BTN') }}
                    </span>
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card
          class="au-reply__card au-reply__card--gap"
          :bordered="false"
        >
          <div
            slot="title"
            class="au-reply__title"
          >
            <Icon
              class="au-reply__title-icon"
              type="ios-list"
              size="18"
            />
            <span class="au-reply__title-text">
              {{ $t('SHOPEE_AUTO_REPLY_RATING_LOG') }}
            </span>
            <Badge
              class="au-reply__title-badge"
              :count="replyHandler.sent"
              type="primary"
            />
            <span class="au-reply__title-total"> / {{ replyHandler.total | addCommas }} </span>
          </div>

          <div class="au-reply__log">
            <Input
              :value="logText"
              type="textarea"
              :rows="15"
              readonly
              class="au-reply__log-text"
            />
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import delay from 'delay';
import PromiseMap from 'p-map';
import { getRatingListUnReply, replyRatingId, getRatingMeta } from '@/api/shopee/seller/rating';
import { sendChatMessage } from '@/api/shopee/seller/chat';
import { SHOPEE_AUTO_RUN_LIMITS } from '@/constant/shopee';

export default {
  name: 'ShopeeAutoReplyReview',
  data() {
    return {
      formData: {},
      queryRating: {
        star: [5],
        limit: 20,
      },
      replyRating: {
        text: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_TEXT'),
      },
      replyChat: {
        text: '',
      },
      replyHandler: {
        loading: false,
        log: [],
        sent: 0,
        total: 0,
        sleepPerList: 5000,
        sleepPerRating: 500,
      },
      matchText: {
        BUYER_NAME: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_BUYER_NAME'),
        ORDER_ID: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_ORDER_ID'),
        RATING_STAR: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_RATING_STAR'),
      },
    };
  },
  methods: {
    async getchMetaRating() {
      const metaRating = await getRatingMeta(this.queryRating.star);
      this.replyHandler.total = metaRating.to_reply_count;
    },
    async handleReplyRating() {
      this.replyHandler.loading = true;

      this.replyHandler.sent = 0;

      let isAllow = true;

      while (isAllow) {
        const listRating = await getRatingListUnReply(
          this.queryRating.star,
          this.queryRating.limit,
        );

        if (!(listRating && listRating.length)) {
          break;
        }

        await PromiseMap(
          listRating,
          async (ratingData) => {
            if (!isAllow) {
              return false;
            }

            const {
              user_id: buyerId,
              order_id: orderId,
              comment_id: commentId,
              rating_star: ratingStar,
              user_name: buyerName,
              reply,
            } = ratingData;

            if (!(!reply && this.queryRating.star.includes(ratingStar))) {
              return false;
            }

            const ratingText = this.replyRating.text
              .replace(/BUYER_NAME/g, buyerName)
              .replace(/ORDER_ID/g, orderId)
              .replace(/RATING_STAR/g, ratingStar);

            const payloadLog = {
              buyer: buyerName,
              order_id: orderId,
              star: ratingStar,
              text: ratingText,
              process_current: this.replyHandler.sent,
              process_total: this.replyHandler.total,
            };

            await replyRatingId(orderId, commentId, ratingText)
              .then((result) => {
                if (result.message === 'success') {
                  this.replyHandler.log.push(
                    `✅ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_SUCCESS', payloadLog)}`,
                  );
                } else {
                  this.replyHandler.log.push(
                    `❌ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_ERROR', payloadLog)}`,
                  );
                }
              })
              .catch(() => {
                this.replyHandler.log.push(
                  `❌ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_ERROR', payloadLog)}`,
                );
              });

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

              const textChat = this.replyChat.text
                .replace(/BUYER_NAME/g, buyerName)
                .replace(/ORDER_ID/g, orderId)
                .replace(/RATING_STAR/g, ratingStar);

              const payloadLog = {
                buyer: buyerName,
                text: textChat,
              };

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

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

            this.replyHandler.sent += 1;

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

            await delay(this.replyHandler.sleepPerRating);
          },
          {
            concurrency: 1,
          },
        );

        if (!isAllow) {
          break;
        }

        await delay(this.replyHandler.sleepPerList);
      }
      this.replyHandler.loading = false;
    },
  },
  created() {
    this.getchMetaRating();
  },
  computed: {
    logText() {
      return this.replyHandler.log.join('\n');
    },
    autoRunLimit() {
      const config = SHOPEE_AUTO_RUN_LIMITS.replyRating[this.getUserPlan];
      if (config) {
        return config.runLimit;
      }
      return 0;
    },
    isRunLimitVisible() {
      return Number.isFinite(this.autoRunLimit) && this.autoRunLimit > 0;
    },
    isRunLimitReached() {
      return this.isRunLimitVisible && this.replyHandler.sent >= this.autoRunLimit;
    },
  },
};
</script>

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

.au-reply {
  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;
    }

    &--gap.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;
  }

  &__title-total {
    font-size: 13px;
    font-weight: 500;
    color: $c-text-muted;
  }

  &__vars {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 12px;
  }

  &__var {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: $c-surface-soft;
    border: 1px solid $c-border;
    border-radius: $radius-item;
    transition: border-color $motion-fast, background $motion-fast;
  }

  &__var:hover {
    background: $c-surface-alt;
    border-color: $c-border-strong;
  }

  &__var-tag.ivu-tag {
    flex-shrink: 0;
    margin: 0;
    font-family: 'Courier New', monospace;
    font-weight: 600;
    border-radius: $radius-sm;
  }

  &__var-desc {
    font-size: 13px;
    color: $c-text;

    @include line-clamp(2);
  }

  &__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>
