<template>
  <Row>
    <Col
      :span="24"
    >
      <Card
        dis-hover
        class="mb-10"
      >
        <Row
          type="flex"
          align="middle"
          :gutter="12"
        >
          <Col :span="4">
            <Input
              v-model="filter.shopId"
              :placeholder="$t('PDF_LOG_FILTER_SHOP_ID')"
              clearable
              @on-enter="onFilterChange"
              @on-clear="onFilterChange"
            />
          </Col>
          <Col :span="4">
            <Select
              v-model="filter.platform"
              :placeholder="$t('PDF_LOG_FILTER_PLATFORM')"
              clearable
              @on-change="onFilterChange"
            >
              <Option
                v-for="item in listPlatform"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </Option>
            </Select>
          </Col>
          <Col :span="6">
            <DatePicker
              v-model="filter.createdAt"
              type="daterange"
              :placeholder="$t('PDF_LOG_FILTER_CREATED_AT')"
              clearable
              style="width: 100%"
              @on-change="onFilterChange"
            />
          </Col>
          <Col :span="5">
            <Input
              v-model="filter.search"
              :placeholder="$t('PDF_LOG_FILTER_SEARCH')"
              clearable
              @on-enter="onFilterChange"
              @on-clear="onFilterChange"
            />
          </Col>
          <Col :span="5">
            <Button
              type="primary"
              icon="ios-search"
              class="mr-5"
              @click="onFilterChange"
            >
              {{ $t('SEARCH_BTN') }}
            </Button>
            <Button
              type="default"
              icon="ios-refresh"
              :title="$t('PDF_LOG_REFRESH')"
              @click="onRefresh"
            />
          </Col>
        </Row>
        <Row
          :gutter="12"
          class="mt-10"
        >
          <Col :span="24">
            <span class="pdf-log-setting-label">{{ $t('SETTING_SAVE_HISTORY_PRINT') }}:</span>
            <Checkbox
              v-model="saveHistoryPrint.shopee"
              class="ml-10"
              @on-change="saveSaveHistoryPrint"
            >
              Shopee
            </Checkbox>
            <Checkbox
              v-model="saveHistoryPrint.tiktok"
              @on-change="saveSaveHistoryPrint"
            >
              TikTok
            </Checkbox>
            <Checkbox
              v-model="saveHistoryPrint.lazada"
              @on-change="saveSaveHistoryPrint"
            >
              Lazada
            </Checkbox>
          </Col>
        </Row>
      </Card>

      <div>
        <Row
          type="flex"
          align="middle"
          class="mb-10"
        >
          <Col :span="12">
            <span class="pdf-log-total">
              {{ $t('PDF_LOG_TOTAL_RECORD').replace('{total}', pagging.total) }}
            </span>
          </Col>
          <Col
            :span="12"
            style="text-align: right"
          >
            <Page
              v-model="pagging.current"
              :total="pagging.total"
              :page-size="pagging.limit"
              show-sizer
              show-total
              :page-size-opts="pagging.size"
              @on-change="onPaggingChange"
              @on-page-size-change="onPaggingSize"
            />
          </Col>
        </Row>

        <Table
          :loading="query.loading"
          :columns="tableColumns"
          :data="tablePdf.rows"
          border
          size="small"
          highlight-row
        >
          <template
            slot="index"
            slot-scope="{ index }"
          >
            {{ (pagging.current - 1) * pagging.limit + index + 1 }}
          </template>
          <template
            slot="platform"
            slot-scope="{ row }"
          >
            <Tag :color="getPlatformColor(row.platform)">
              {{ getPlatformLabel(row.platform) }}
            </Tag>
          </template>
          <template
            slot="size"
            slot-scope="{ row }"
          >
            {{ formatSize(row.size) }}
          </template>
          <template
            slot="createdAt"
            slot-scope="{ row }"
          >
            {{ formatDate(row.createdAt) }}
          </template>
          <template
            slot="search"
            slot-scope="{ row }"
          >
            <Tooltip
              v-if="row.search"
              :content="row.search"
              placement="top"
              max-width="300"
            >
              <span class="pdf-log-search-preview">{{ row.search }}</span>
            </Tooltip>
            <span v-else>-</span>
          </template>
          <template
            slot="action"
            slot-scope="{ row }"
          >
            <div
              v-if="row.s3Url"
              class="pdf-log-actions"
            >
              <Tooltip
                :content="$t('PDF_LOG_DOWNLOAD')"
                placement="top"
              >
                <Button
                  size="small"
                  type="primary"
                  ghost
                  icon="ios-download-outline"
                  @click="onDownload(row)"
                />
              </Tooltip>
              <Tooltip
                :content="$t('PDF_LOG_VIEW')"
                placement="top"
              >
                <Button
                  size="small"
                  type="info"
                  ghost
                  icon="ios-eye-outline"
                  @click="onView(row)"
                />
              </Tooltip>
              <Tooltip
                :content="$t('PDF_LOG_PRINT')"
                placement="top"
              >
                <Button
                  size="small"
                  type="warning"
                  ghost
                  icon="ios-print-outline"
                  @click="onPrint(row)"
                />
              </Tooltip>
            </div>
            <span v-else>-</span>
          </template>
        </Table>

        <div
          v-if="!query.loading && tablePdf.rows.length === 0"
          class="text-center mt-50 mb-50"
        >
          <p class="text-muted">
            {{ $t('PDF_LOG_EMPTY') }}
          </p>
        </div>

        <div
          v-if="tablePdf.rows.length > 0"
          class="mt-10 text-right"
        >
          <Page
            v-model="pagging.current"
            :total="pagging.total"
            :page-size="pagging.limit"
            show-sizer
            show-total
            :page-size-opts="pagging.size"
            @on-change="onPaggingChange"
            @on-page-size-change="onPaggingSize"
          />
        </div>
      </div>
    </Col>
  </Row>
</template>

<script>
import moment from 'moment';
import { PLATFORM_COLORS } from './mixin/constant';
import settingMixin from './mixin/setting';
import filterMixin from './mixin/filter';
import actionMixin from './mixin/action';
import cleanupMixin from './mixin/cleanup';

export default {
  name: 'PdfLogIndex',
  mixins: [settingMixin, filterMixin, actionMixin, cleanupMixin],
  data() {
    return {
      listPlatform: [
        { value: 'shopee', label: this.$t('SHOPEE') },
        { value: 'lazada', label: this.$t('LAZADA') },
        { value: 'tiktok', label: this.$t('TIKTOK') },
      ],
      query: {
        loading: false,
      },
      pagging: {
        total: 0,
        current: 1,
        limit: 50,
        size: [10, 20, 50, 100, 200],
      },
      tablePdf: {
        rows: [],
      },
    };
  },
  computed: {
    tableColumns() {
      return [
        {
          title: '#', key: 'index', width: 50, slot: 'index',
        },
        { title: this.$t('PDF_LOG_TABLE_SHOP_ID'), key: 'shopId', width: 150 },
        { title: this.$t('PDF_LOG_TABLE_SHOP_NAME'), key: 'shopName' },
        {
          title: this.$t('PDF_LOG_TABLE_PLATFORM'),
          key: 'platform',
          width: 110,
          slot: 'platform',
          align: 'center',
        },
        { title: this.$t('PDF_LOG_TABLE_PAGE'), key: 'page', width: 70 },
        {
          title: this.$t('PDF_LOG_TABLE_SIZE'), key: 'size', width: 110, slot: 'size',
        },
        {
          title: this.$t('PDF_LOG_TABLE_SEARCH'),
          key: 'search',
          slot: 'search',
        },
        {
          title: this.$t('PDF_LOG_TABLE_CREATED_AT'),
          key: 'createdAt',
          width: 150,
          slot: 'createdAt',
        },
        {
          title: this.$t('PDF_LOG_TABLE_ACTION'),
          key: 'action',
          width: 130,
          slot: 'action',
          fixed: 'right',
          align: 'center',
        },
      ];
    },
  },
  methods: {
    onPaggingChange(page) {
      this.pagging.current = page;
      this.applyFilter();
    },
    onPaggingSize(limit) {
      this.pagging.limit = limit;
      this.pagging.current = 1;
      this.applyFilter();
    },
    async onRefresh() {
      await this.fetchData();
    },
    getPlatformColor(platform) {
      return PLATFORM_COLORS[platform] || 'default';
    },
    getPlatformLabel(platform) {
      const labels = {
        shopee: this.$t('SHOPEE'),
        lazada: this.$t('LAZADA'),
        tiktok: this.$t('TIKTOK'),
      };
      return labels[platform] || platform;
    },
    formatSize(bytes) {
      if (!bytes) {
        return '-';
      }

      if (bytes < 1024) {
        return `${bytes} B`;
      }

      if (bytes < 1024 * 1024) {
        return `${(bytes / 1024).toFixed(2)} KB`;
      }

      return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
    },
    formatDate(date) {
      if (!date) {
        return '-';
      }

      return moment(date).format('DD/MM/YYYY HH:mm:ss');
    },
  },
  async created() {
    this.loadSaveHistoryPrint();

    await this.fetchData();

    this.cleanupOldData();
    this.setupSync();
  },
};
</script>

<style lang="scss" scoped>
.pdf-log-setting-label {
  font-size: 12px;
  color: #808695;
}

.pdf-log-total {
  font-size: 12px;
  color: #808695;
}

.pdf-log-search-preview {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
  font-size: 11px;
  color: #515a6e;
}

.pdf-log-actions {
  display: flex;
  gap: 4px;
  justify-content: center;
  flex-wrap: nowrap;
}
</style>
