<template>
  <div class="message-container">
    <Row :gutter="24">
      <Col
        :span="16"
        :offset="4"
      >
        <div>
            <div class="mb-20">
              <Form
                :label-width="200"
                label-position="left"
              >
                <FormItem :label="$t('SEND_MESSAGE_COLLECTOR_TYPE')">
                  <Select
                    v-model="collectorType"
                    style="width: 300px"
                  >
                    <Option
                      v-for="collector in collectorList"
                      :key="collector.type"
                      :value="collector.type"
                    >
                      {{ collector.name }}
                    </Option>
                  </Select>
                </FormItem>
              </Form>
            </div>
            <Card
              v-if="collectorType === 'orderRating'"
              dis-hover
            >
              <div slot="title">
                {{ $t('SEND_MESSAGE_FILTER_RATING_TITLE') }}
              </div>
              <div>
                <Form
                  :label-width="150"
                  label-position="left"
                >
                  <Row :gutter="16">
                    <Col :span="12">
                      <FormItem :label="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')">
                        <Select
                          v-model="filterRating.star"
                          multiple
                          style="width: 100%"
                          :placeholder="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')"
                        >
                          <Option
                            v-for="star in [1, 2, 3, 4, 5]"
                            :key="star"
                            :value="star"
                          >
                            {{ $t('RATING_STAR', { star }) }}
                          </Option>
                        </Select>
                      </FormItem>
                    </Col>
                    <Col :span="12">
                      <FormItem :label="$t('SEARCH_INPUT')">
                        <Input
                          v-model="filterRating.search"
                          :placeholder="$t('SEARCH_INPUT')"
                          clearable
                        />
                      </FormItem>
                    </Col>
                  </Row>
                  <Row :gutter="16">
                    <Col :span="12">
                      <FormItem :label="$t('SEND_MESSAGE_FILTER_TIME_START')">
                        <DatePicker
                          v-model="filterRating.timeStartDate"
                          type="datetime"
                          :placeholder="$t('SEND_MESSAGE_FILTER_TIME_START')"
                          style="width: 100%"
                          clearable
                          @on-change="onTimeStartChange"
                        />
                      </FormItem>
                    </Col>
                    <Col :span="12">
                      <FormItem :label="$t('SEND_MESSAGE_FILTER_TIME_END')">
                        <DatePicker
                          v-model="filterRating.timeEndDate"
                          type="datetime"
                          :placeholder="$t('SEND_MESSAGE_FILTER_TIME_END')"
                          style="width: 100%"
                          clearable
                          @on-change="onTimeEndChange"
                        />
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col :span="24">
                      <div class="text-right">
                        <Button
                          v-if="log.length > 0"
                          type="info"
                          ghost
                          class="mr-10"
                          @click="popupLog = true"
                        >
                          <Icon
                            type="ios-list"
                            size="16"
                          />
                          <span class="ml-5">{{ $t('SEND_MESSAGE_VIEW_LOG') }}</span>
                        </Button>
                        <Button
                          type="primary"
                          :loading="loadingFetch"
                          @click="handleFetchFromRating"
                        >
                          <i
                            class="fa fa-search mr-5"
                            aria-hidden="true"
                          />
                          {{ $t('FETCH_BTN') }}
                        </Button>
                      </div>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Card>

            <Card
              v-if="collectorType === 'import'"
              dis-hover
              class="mt-20"
            >
              <div slot="title">
                {{ $t('SEND_MESSAGE_IMPORT_TITLE') }}
              </div>
              <div>
                <Form
                  :label-width="150"
                  label-position="left"
                >
                  <FormItem :label="$t('SEND_MESSAGE_IMPORT_TITLE')">
                    <Input
                      v-model="importText"
                      type="textarea"
                      :rows="10"
                      :placeholder="$t('SEND_MESSAGE_IMPORT_PLACEHOLDER')"
                    />
                  </FormItem>
                  <Row>
                    <Col :span="24">
                      <div class="text-right">
                        <Button
                          v-if="log.length > 0"
                          type="info"
                          ghost
                          class="mr-10"
                          @click="popupLog = true"
                        >
                          <Icon
                            type="ios-list"
                            size="16"
                          />
                          <span class="ml-5">{{ $t('SEND_MESSAGE_VIEW_LOG') }}</span>
                        </Button>
                        <Button
                          type="primary"
                          :loading="loadingFetch"
                          @click="handleImportFromText"
                        >
                          <i
                            class="fa fa-upload mr-5"
                            aria-hidden="true"
                          />
                          {{ $t('SEND_MESSAGE_IMPORT_BTN') }}
                        </Button>
                      </div>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Card>

            <Card
              dis-hover
              class="mt-20"
            >
              <div slot="title">
                <Icon
                  type="ios-people"
                  size="18"
                />
                <span class="ml-5">{{ $t('SEND_MESSAGE_CUSTOMER_LIST_TITLE') }}</span>
              </div>
              <div>
                <template v-if="!listCustomer.length">
                  <div class="empty-customer">
                    <Icon
                      type="ios-people-outline"
                      size="48"
                      class="empty-icon"
                    />
                    <p class="empty-text">
                      {{ $t('SEND_MESSAGE_CUSTOMER_LIST_EMPTY') }}
                    </p>
                  </div>
                </template>
                <template v-else>
                  <div class="mb-10 text-right">
                    <Page
                      v-model="paggingCustomer.current"
                      :total="paggingCustomer.total"
                      :page-size="paggingCustomer.limit"
                      show-sizer
                      show-total
                      :page-size-opts="paggingCustomer.size"
                      @on-change="onPaggingCustomerChange"
                      @on-page-size-change="onPaggingCustomerSize"
                    />
                  </div>
                  <Table
                    :loading="loadingCustomer"
                    :columns="tableCustomerColumns"
                    :data="listCustomer"
                    size="small"
                    border
                    highlight-row
                  >
                    <template
                      slot="index"
                      slot-scope="{ index }"
                    >
                      {{ (paggingCustomer.current - 1) * paggingCustomer.limit + index + 1 }}
                    </template>
                    <template
                      slot="active"
                      slot-scope="{ row }"
                    >
                      <Checkbox
                        v-model="row.active"
                        @on-change="(value) => onToggleActive(row, value)"
                      />
                    </template>
                    <template
                      slot="status"
                      slot-scope="{ row }"
                    >
                      <Tag :color="getCustomerStatusColor(row.status)">
                        {{ $t(`MARKETING_SENDER_CUSTOMER_STATUS.${row.status}`) }}
                      </Tag>
                    </template>
                    <template
                      slot="createdAt"
                      slot-scope="{ row }"
                    >
                      {{ formatDate(row.createdAt) }}
                    </template>
                    <template
                      slot="action"
                      slot-scope="{ row }"
                    >
                      <Button
                        type="text"
                        size="small"
                        class="text-danger"
                        @click="onRemoveCustomer(row)"
                      >
                        {{ $t('DELETE_BTN') }}
                      </Button>
                    </template>
                  </Table>
                  <div class="mt-10 text-right">
                    <Page
                      v-model="paggingCustomer.current"
                      :total="paggingCustomer.total"
                      :page-size="paggingCustomer.limit"
                      show-sizer
                      show-total
                      :page-size-opts="paggingCustomer.size"
                      @on-change="onPaggingCustomerChange"
                      @on-page-size-change="onPaggingCustomerSize"
                    />
                  </div>
                </template>
              </div>
            </Card>
          </div>
      </Col>
    </Row>

    <Modal
      v-model="popupLog"
      :title="$t('SEND_MESSAGE_LOG_TITLE')"
      width="800"
      :footer-hide="true"
      :mask-closable="true"
    >
      <div>
        <div class="mb-20">
          <Row :gutter="16">
            <Col :span="6">
              <div class="stat-item">
                <div class="stat-label">
                  {{ $t('SEND_MESSAGE_STAT_TOTAL_SCANNED') }}
                </div>
                <div class="stat-value">
                  {{ logStats.total }}
                </div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-item">
                <div class="stat-label">
                  {{ $t('SEND_MESSAGE_STAT_TOTAL_SKIPPED') }}
                </div>
                <div class="stat-value text-warning">
                  {{ logStats.skipped }}
                </div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-item">
                <div class="stat-label">
                  {{ $t('SEND_MESSAGE_STAT_TOTAL_ADDED') }}
                </div>
                <div class="stat-value text-success">
                  {{ logStats.success }}
                </div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-item">
                <div class="stat-label">
                  {{ $t('MARKETING_SENDER_COLUMN_TOTAL_CUSTOMERS') }}
                </div>
                <div class="stat-value">
                  {{ countCustomer }}
                </div>
              </div>
            </Col>
          </Row>
        </div>
        <div class="log-container">
          <div
            v-if="!log.length"
            class="empty-log"
          >
            <Icon
              type="ios-list-outline"
              size="48"
              class="empty-icon"
            />
            <p class="empty-text">
              {{ $t('SEND_MESSAGE_LOG_EMPTY') }}
            </p>
          </div>
          <template v-else>
            <div
              v-for="(item, index) in log"
              :key="index"
              class="log-item"
              :class="`log-${item.type}`"
            >
              <Icon
                :type="getLogIconType(item.type)"
                :class="`text-${getLogColorType(item.type)}`"
                size="16"
              />
              <span class="ml-5">{{ item.message }}</span>
            </div>
          </template>
        </div>
      </div>
    </Modal>
  </div>
</template>
<script>
import PromiseMap from 'p-map';
import arrayDedupe from 'array-dedupe';
import {
  ShopeeMarketingSenderCustomer,
  ShopeeMarketingSenderCollect,
} from '@/models/shopee/marketing/sender';
import { getRatingListReply } from '@/api/shopee/seller/rating';

export default {
  name: 'ShopeeAutoSendMessageCollect',
  data() {
    return {
      collectName: '',
      collectData: {},
      collectId: this.$route.params.id,
      listCustomer: [],
      collectorType: 'orderRating',
      countCustomer: 0,
      filterRating: {
        star: [1, 2, 3, 4, 5],
        timeStart: 0,
        timeEnd: 0,
        timeStartDate: null,
        timeEndDate: null,
        search: '',
        limit: 40,
        page: 1,
        max: 100,
      },
      log: [],
      loadingFetch: false,
      popupLog: false,
      loadingCustomer: false,
      importText: '',
      paggingCustomer: {
        current: 1,
        limit: 20,
        total: 0,
        size: [10, 20, 50, 100],
      },
    };
  },
  methods: {
    onTimeStartChange(date) {
      if (date) {
        this.filterRating.timeStart = new Date(date).getTime() / 1000;
      } else {
        this.filterRating.timeStart = 0;
      }
    },
    onTimeEndChange(date) {
      if (date) {
        this.filterRating.timeEnd = new Date(date).getTime() / 1000;
      } else {
        this.filterRating.timeEnd = 0;
      }
    },
    async handleFetchFromRating() {
      if (!this.filterRating.star || !this.filterRating.star.length) {
        this.$Message.warning(this.$t('SEND_MESSAGE_FILTER_STAR_REQUIRED'));
        return;
      }

      this.loadingFetch = true;
      this.log = [];
      this.popupLog = true;

      try {
        await this.fetchFromRating();
        this.$Message.success(this.$t('FETCH_DATA_SUCCESS'));
      } catch (error) {
        this.$Message.error(this.$t('FETCH_DATA_ERROR'));
      } finally {
        this.loadingFetch = false;
      }

      this.fetchCustomers();
    },
    detectDelimiter(line) {
      if (line.includes('\t')) {
        return '\t';
      }

      if (line.includes(',')) {
        return ',';
      }

      if (line.includes(' ')) {
        return ' ';
      }

      return '\t';
    },
    parseImportData(text) {
      if (!text || !text.trim()) {
        return {
          customers: [],
          errors: [],
        };
      }

      const lines = text.trim().split('\n');
      const customers = [];
      const errors = [];

      lines.forEach((line, index) => {
        const trimmedLine = line.trim();
        const lineNumber = index + 1;

        if (!trimmedLine) {
          return;
        }

        try {
          const delimiter = this.detectDelimiter(trimmedLine);
          let parts = trimmedLine.split(delimiter);

          if (delimiter === ' ') {
            parts = parts.filter((part) => part.trim().length > 0);
          }

          parts = parts.map((part) => part.trim()).filter((part) => part.length > 0);

          if (parts.length < 1) {
            errors.push({
              line: lineNumber,
              content: trimmedLine,
              message: this.$t('SEND_MESSAGE_IMPORT_INVALID_FORMAT_LINE', { line: lineNumber }),
            });
            return;
          }

          const userId = parts[0];
          const userName = parts[1] || userId;

          if (!userId) {
            errors.push({
              line: lineNumber,
              content: trimmedLine,
              message: this.$t('SEND_MESSAGE_IMPORT_INVALID_FORMAT_LINE', { line: lineNumber }),
            });
            return;
          }

          const shopIdNumber = Number(this.getShopeeShopId);

          if (!shopIdNumber || isNaN(shopIdNumber)) {
            errors.push({
              line: lineNumber,
              content: trimmedLine,
              message: this.$t('SEND_MESSAGE_IMPORT_SHOP_ID_REQUIRED', { line: lineNumber }),
            });
            return;
          }

          const isNumericUserId = /^\d+$/.test(userId);

          if (isNumericUserId) {
            customers.push({
              customerName: userName,
              toUserId: userId,
              toShopId: shopIdNumber,
            });
          } else {
            customers.push({
              customerName: userName,
              toUserId: 0,
              toShopId: shopIdNumber,
              username: userId,
            });
          }
        } catch (error) {
          errors.push({
            line: lineNumber,
            content: trimmedLine,
            message: this.$t('SEND_MESSAGE_IMPORT_INVALID_FORMAT_LINE', { line: lineNumber }),
          });
        }
      });

      return {
        customers,
        errors,
      };
    },
    async handleImportFromText() {
      if (!this.importText || !this.importText.trim()) {
        this.$Message.warning(this.$t('SEND_MESSAGE_IMPORT_EMPTY'));
        return;
      }

      this.loadingFetch = true;
      this.log = [];
      this.popupLog = true;

      try {
        const { customers, errors } = this.parseImportData(this.importText);

        if (errors.length > 0) {
          errors.forEach((error) => {
            this.log.push({
              type: 'error',
              message: error.message,
            });
          });
        }

        if (!customers.length) {
          if (errors.length > 0) {
            this.$Message.warning(this.$t('SEND_MESSAGE_IMPORT_NO_VALID_DATA'));
          } else {
            this.$Message.warning(this.$t('SEND_MESSAGE_IMPORT_EMPTY'));
          }
          this.loadingFetch = false;
          return;
        }

        await this.importCustomers(customers);
        this.$Message.success(this.$t('FETCH_DATA_SUCCESS'));
        this.importText = '';
      } catch (error) {
        this.$Message.error(error.message || this.$t('FETCH_DATA_ERROR'));
        this.log.push({
          type: 'error',
          message: error.message || this.$t('FETCH_DATA_ERROR'),
        });
      } finally {
        this.loadingFetch = false;
      }

      this.fetchCustomers();
    },
    getCustomerDedupeKey(customer) {
      if (customer.username) {
        return `u-${customer.username}`;
      }
      return `${customer.toUserId}-${customer.toShopId}`;
    },
    async importCustomers(customers) {
      const sourceCustomer = 'import';

      const seenKeys = new Set();
      const uniqueCustomers = [];

      customers.forEach((customer) => {
        const key = this.getCustomerDedupeKey(customer);

        if (seenKeys.has(key)) {
          return;
        }

        seenKeys.add(key);
        uniqueCustomers.push(customer);
      });

      if (uniqueCustomers.length < customers.length) {
        const duplicateCount = customers.length - uniqueCustomers.length;
        this.log.push({
          type: 'skipped',
          message: this.$t('SEND_MESSAGE_IMPORT_DUPLICATE_IN_DATA', { count: duplicateCount }),
        });
      }

      const collectId = this.collectId;
      const existingCustomersMap = new Map();

      const existingCustomers = await ShopeeMarketingSenderCustomer.findMany(
        {
          collectId,
        },
        10000,
        0,
      );

      existingCustomers.forEach((existing) => {
        const key = this.getCustomerDedupeKey(existing);
        existingCustomersMap.set(key, existing);
      });

      const newCustomers = [];
      const skippedCustomers = [];

      uniqueCustomers.forEach((customer) => {
        const key = this.getCustomerDedupeKey(customer);

        if (existingCustomersMap.has(key)) {
          skippedCustomers.push({
            ...customer,
            existing: existingCustomersMap.get(key),
          });
        } else {
          newCustomers.push(customer);
        }
      });

      if (skippedCustomers.length > 0) {
        this.log.push({
          type: 'skipped',
          message: this.$t('SEND_MESSAGE_IMPORT_DUPLICATE_IN_DB', {
            count: skippedCustomers.length,
          }),
        });

        skippedCustomers.forEach((skipped) => {
          this.log.push({
            type: 'skipped',
            message: this.$t('SEND_MESSAGE_CUSTOMER_SKIPPED', { name: skipped.customerName }),
          });
        });
      }

      if (newCustomers.length === 0) {
        this.log.push({
          type: 'skipped',
          message: this.$t('SEND_MESSAGE_IMPORT_ALL_EXISTS'),
        });
        return;
      }

      await PromiseMap(
        newCustomers,
        async (customer) => {
          const {
            customerName, toUserId, toShopId, username,
          } = customer;

          try {
            const { isAdded } = await this.addCustomer({
              toUserId,
              toShopId,
              customerName,
              source: sourceCustomer,
              username: username || '',
            });

            if (isAdded) {
              this.log.push({
                type: 'success',
                message: this.$t('SEND_MESSAGE_ADD_CUSTOMER_SUCCESS', { name: customerName }),
              });
            }
          } catch (error) {
            this.log.push({
              type: 'error',
              message: this.$t('SEND_MESSAGE_ADD_CUSTOMER_ERROR', {
                name: customerName,
                error: error.message,
              }),
            });
          }
        },
        {
          concurrency: 2,
        },
      );
    },
    async fetchFromRating() {
      const sourceCustomer = 'orderRating';
      const payloadFilter = {
        rating_star: this.filterRating.star.join(','),
      };

      if (this.filterRating.timeStart) {
        payloadFilter.time_start = this.filterRating.timeStart;
      }

      if (this.filterRating.timeEnd) {
        payloadFilter.time_end = this.filterRating.timeEnd;
      }

      if (this.filterRating.search) {
        payloadFilter.search_request = this.filterRating.search;
      }

      this.filterRating.page = 0;

      let cursorRatingId = 0;

      const toShopId = Number(this.getShopeeShopId);

      for (let page = 0; page < this.filterRating.max; page++) {
        /** @type {ShopeeListRatingOrder[]} */
        const listRating = await getRatingListReply(
          payloadFilter,
          this.filterRating.limit,
          page,
          cursorRatingId,
        );
        this.filterRating.page++;

        if (!listRating.length) {
          break;
        }

        cursorRatingId = listRating.at(-1).comment_id;

        const listCustomer = arrayDedupe(listRating, ['user_id']);

        await PromiseMap(
          listCustomer,
          async (rating) => {
            const toUserId = rating.user_id;
            const customerName = rating.user_name || 'unknown';

            try {
              const { isExist, isAdded } = await this.addCustomer({
                toUserId,
                toShopId,
                customerName,
                source: sourceCustomer,
              });

              if (isExist) {
                return this.log.push({
                  type: 'skipped',
                  message: this.$t('SEND_MESSAGE_CUSTOMER_SKIPPED', { name: customerName }),
                });
              }

              if (isAdded) {
                this.log.push({
                  type: 'success',
                  message: this.$t('SEND_MESSAGE_ADD_CUSTOMER_SUCCESS', { name: customerName }),
                });
              }
            } catch (error) {
              this.log.push({
                type: 'error',
                message: this.$t('SEND_MESSAGE_ADD_CUSTOMER_ERROR', {
                  name: customerName,
                  error: error.message,
                }),
              });
            }
          },
          {
            concurrency: 2,
          },
        );
      }
    },
    async fetchCustomers() {
      this.loadingCustomer = true;

      try {
        const skip = (this.paggingCustomer.current - 1) * this.paggingCustomer.limit;
        const where = {
          collectId: this.collectId,
        };

        const listCustomer = await ShopeeMarketingSenderCustomer.findMany(
          where,
          this.paggingCustomer.limit,
          skip,
        );

        listCustomer.sort((a, b) => {
          const timeA = a.createdAt || 0;
          const timeB = b.createdAt || 0;
          return timeB - timeA;
        });

        const collectData = await ShopeeMarketingSenderCollect.getId(this.collectId);

        let totalCount = collectData.totalCustomers;
        const actualCount = await ShopeeMarketingSenderCustomer.count(where);

        if (actualCount !== totalCount) {
          totalCount = actualCount;
          await this.setTotalCustomers(actualCount);
        }

        this.listCustomer = listCustomer;
        this.countCustomer = totalCount;
        this.collectName = collectData.name;
        this.collectData = collectData;
        this.paggingCustomer.total = totalCount;
      } catch (error) {
        this.$Message.error(this.$t('ERROR_GET_DATA'));
        this.loggerApi.error('Fetch customers error:', error);
      } finally {
        this.loadingCustomer = false;
      }
    },
    onPaggingCustomerChange(page) {
      this.paggingCustomer.current = page;
      this.fetchCustomers();
    },
    onPaggingCustomerSize(limit) {
      this.paggingCustomer.limit = limit;
      this.paggingCustomer.current = 1;
      this.fetchCustomers();
    },
    setTotalCustomers(totalCustomers) {
      return ShopeeMarketingSenderCollect.updateId(
        this.collectId,
        {
          totalCustomers,
        },
        false,
      );
    },
    async addCustomer({
      toUserId, toShopId, customerName, source, username,
    }) {
      const collectId = this.collectId;

      const customerId = username
        ? [collectId, 'u', username].join('-')
        : [collectId, toUserId].join('-');

      const customerExist = await ShopeeMarketingSenderCustomer.getId(customerId);

      if (customerExist) {
        return {
          isExist: true,
          collectId,
          customerId,
          ...customerExist,
        };
      }

      const payloadCustomer = {
        collectId,
        toUserId,
        toShopId,
        customerName,
        source,
        message: '',
        active: true,
        status: 'pending',
        error: '',
        sentAt: null,
        username: username || '',
      };

      await ShopeeMarketingSenderCustomer.insert(payloadCustomer, customerId);

      this.countCustomer++;

      await this.setTotalCustomers(this.countCustomer + 1);

      return {
        isAdded: true,
        collectId,
        customerId,
        ...payloadCustomer,
      };
    },
    async onToggleActive(row, value) {
      row.active = value;

      return ShopeeMarketingSenderCustomer.updateId(
        row._id,
        {
          active: value,
        },
        false,
      );
    },
    onRemoveCustomer(row) {
      this.$Modal.confirm({
        title: this.$t('REMOVE_CONFIRM'),
        content: this.$t('SEND_MESSAGE_REMOVE_CUSTOMER_CONFIRM', { name: row.customerName }),
        onOk: async () => {
          try {
            await ShopeeMarketingSenderCustomer.removeId(row._id);
            await this.setTotalCustomers(Math.max(0, this.countCustomer - 1));
            this.$Message.success(this.$t('REMOVE_SUCCESS'));
            await this.fetchCustomers();
          } catch (error) {
            this.$Message.error(this.$t('REMOVE_ERROR'));
            this.loggerApi.error('Remove customer error:', error);
          }
        },
      });
    },
    formatDate(timestamp) {
      if (!timestamp) {
        return '-';
      }
      const date = new Date(timestamp);
      return date.toLocaleString('vi-VN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
    },
    getCustomerStatusColor(status) {
      const colorMap = {
        pending: 'default',
        sent: 'success',
        failed: 'error',
      };
      return colorMap[status] || 'default';
    },
    getLogIconType(type) {
      const iconMap = {
        success: 'ios-checkmark-circle',
        error: 'ios-close-circle',
        skipped: 'ios-information-circle',
      };
      return iconMap[type] || 'ios-information-circle';
    },
    getLogColorType(type) {
      const colorMap = {
        success: 'success',
        error: 'error',
        skipped: 'warning',
      };
      return colorMap[type] || 'default';
    },
  },
  created() {
    this.fetchCustomers();

    ShopeeMarketingSenderCollect.syncRemote();
    ShopeeMarketingSenderCustomer.syncRemote();
  },
  computed: {
    tableCustomerColumns() {
      return [
        {
          title: '#',
          slot: 'index',
          width: 80,
          align: 'center',
        },
        {
          title: this.$t('ORDER_BUYER_NAME'),
          key: 'customerName',
          minWidth: 150,
        },
        {
          title: 'User ID',
          key: 'toUserId',
          width: 120,
        },
        {
          title: 'Shop ID',
          key: 'toShopId',
          width: 120,
        },
        {
          title: this.$t('MARKETING_SENDER_COLUMN_ACTIVE'),
          slot: 'active',
          width: 100,
          align: 'center',
        },
        {
          title: this.$t('MARKETING_SENDER_COLUMN_STATUS'),
          slot: 'status',
          width: 120,
          align: 'center',
        },
        {
          title: this.$t('PRODUCT_TIME_CREATE'),
          slot: 'createdAt',
          width: 150,
        },
        {
          title: this.$t('TABLE_COLUM_ACTION'),
          slot: 'action',
          width: 100,
          align: 'center',
        },
      ];
    },
    collectorList() {
      return [
        {
          type: 'orderRating',
          name: this.$t('SEND_MESSAGE_COLLECTOR_BY_ORDER_RATING'),
        },
        {
          type: 'import',
          name: this.$t('SEND_MESSAGE_COLLECTOR_BY_IMPORT'),
        },
        // {
        //   type: 'orderStatus',
        //   name: this.$t('SEND_MESSAGE_COLLECTOR_BY_ORDER_STATUS'),
        // },
      ];
    },
    logStats() {
      const success = this.log.filter((item) => item.type === 'success').length;
      const error = this.log.filter((item) => item.type === 'error').length;
      const skipped = this.log.filter((item) => item.type === 'skipped').length;
      return {
        success,
        error,
        skipped,
        total: this.log.length,
      };
    },
  },
};
</script>

<style scoped>
  .mt-20 {
    margin-top: 20px;
  }

  .ml-5 {
    margin-left: 5px;
  }

  .ml-10 {
    margin-left: 10px;
  }

  .mb-10 {
    margin-bottom: 10px;
  }

  .text-success {
    color: #19be6b;
  }

  .text-error {
    color: #ed4014;
  }

  .stat-item {
    text-align: center;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
  }

  .stat-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .log-container {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px;
    background-color: #fafafa;
    border-radius: 4px;
  }

  .log-item {
    padding: 8px 12px;
    margin-bottom: 8px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    font-size: 14px;
    line-height: 1.5;
  }

  .log-success {
    background-color: #f0f9ff;
    border-left: 3px solid #19be6b;
  }

  .log-error {
    background-color: #fff1f0;
    border-left: 3px solid #ed4014;
  }

  .log-skipped {
    background-color: #fffbe6;
    border-left: 3px solid #ff9900;
  }

  .text-warning {
    color: #ff9900;
  }

  .empty-customer {
    text-align: center;
    padding: 48px 24px;
    color: #999;
  }

  .empty-customer .empty-icon {
    color: #ddd;
    margin-bottom: 16px;
  }

  .empty-customer .empty-text {
    margin: 0;
    font-size: 16px;
  }

  .mb-20 {
    margin-bottom: 20px;
  }

  .mr-10 {
    margin-right: 10px;
  }

  .empty-log {
    text-align: center;
    padding: 48px 24px;
    color: #999;
  }

  .empty-log .empty-icon {
    color: #ddd;
    margin-bottom: 16px;
  }

  .empty-log .empty-text {
    margin: 0;
    font-size: 16px;
  }
</style>
