<script lang="ts" setup>
/**
 * @Name: index.vue
 * @Description: 特征词下载页
 * @Author: Cheney
 */

import enLocale from 'element-plus/es/locale/lang/en';
import dayjs from 'dayjs';
import { usePagination } from '/@/utils/usePagination';
import FileDownLoader from '/@/components/FileDowlander/index.vue';
import * as api from './api';
import { useElTableData } from '/@/utils/useElTableData';
import { Download, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { marketplaceIdMap } from '/@/views/featureWord/queryPage/marketplaceIdMap';


const date = ref(calculateLastMonthFirstWeek());
const dateRange = ref(date.value[0]);
const loading = ref(false);
const btnLoading = ref(false);
const { tableData, total, currentPage, pageSize, handlePageChange } = usePagination(handleQuery);

const filter = ref({
  search_term: 'zosi',
  marketplace_Ids: 'ATVPDKIKX0DER',
  report_type: 'WEEKLY',
  reportDate: date
});

onMounted(() => {
  handleQuery();
});

/**
 * 计算上个月第一周的日期
 */
function calculateLastMonthFirstWeek() {
  const lastMonth = dayjs().subtract(1, 'month');
  const firstDayOfLastMonth = lastMonth.startOf('month');
  const firstSundayOfLastMonth = firstDayOfLastMonth.day(0); // 获取上个月第一个星期日
  const firstSaturdayOfLastMonth = firstSundayOfLastMonth.add(6, 'day'); // 获取对应的星期六

  return [
    firstSundayOfLastMonth.format('YYYY-MM-DD'),
    firstSaturdayOfLastMonth.format('YYYY-MM-DD')
  ];
}

/**
 * 判断当前日期类型 并 计算起始和结束日期
 */
function calculateDate() {
  if (filter.value.report_type === 'WEEKLY') {
    date.value[0] = dateRange.value;
    date.value[1] = dayjs(dateRange.value).add(6, 'day').format('YYYY-MM-DD');
  } else if (filter.value.report_type === 'MONTHLY') {
    const selectedMonth = dayjs(dateRange.value);
    date.value[0] = selectedMonth.startOf('month').format('YYYY-MM-DD');
    date.value[1] = selectedMonth.endOf('month').format('YYYY-MM-DD');
  }
}

async function handleQuery() {
  const query = {
    ...filter.value,
    date_start: date.value[0],
    date_end: date.value[1],
    reportDate: undefined,
    page: currentPage.value,
    limit: pageSize.value,
    display: 'yes'
  };
  await useElTableData(api.wordDownload, query, tableData, total, loading);
}

function handleDownload(row: any) {
  const url = row.Url;
  const fileName = url.split('/').pop();

  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

async function queryDownload() {
  btnLoading.value = true;
  const query = {
    ...filter.value,
    date_start: date.value[0],
    date_end: date.value[1],
    reportDate: undefined,
    page: currentPage.value,
    limit: pageSize.value,
  };
  try {
    const response = await api.wordDownload(query);
    if (response.code === 2000) ElMessage.success(response.msg);
  } catch(error) {
    console.log('Error==>', error);
  } finally {
    btnLoading.value = false;
    await handleQuery();
  }
}

async function handleRefresh(row: any) {
  const query = {
    search_term: row.searchTerm,
    marketplace_Ids: row.marketplace_id,
    report_type: row.tableName.split('_').pop(),
    date_start: row.daterange.slice(0, 10),
    date_end: row.daterange.slice(10),
  };
  try {
    const { code, msg } = await useElTableData(api.wordDownload, query, tableData, total, loading);
    if (code === 2000) ElMessage.success({ message: msg, plain: true })
  } catch(error) {
    console.log('Error==>', error);
  } finally {
    await handleQuery();
  }
}
</script>

<template>
  <div class="py-2 px-2.5">
    <el-card body-class="flex justify-between gap-3.5" shadow="hover" style="border: none; margin-bottom: 10px">
      <div class="flex flex-wrap gap-7">
        <div>
          <span class="font-bold mr-2" style="color: #303133">关键词:</span>
          <el-input v-model="filter.search_term" style="width: 180px"></el-input>
        </div>
        <div>
          <span class="font-bold mr-2" style="color: #303133">市场ID:</span>
          <el-select v-model="filter.marketplace_Ids" style="width: 180px">
            <el-option v-for="item in marketplaceIdMap" :label="item.Country" :value="item.MarketplaceId"
                       :key="item.MarketplaceId"></el-option>
          </el-select>
        </div>
        <div>
          <span class="font-bold mr-2" style="color: #303133">报告类型:</span>
          <el-select v-model="filter.report_type" style="width: 100px" @change="calculateDate">
            <el-option label="月度" value="MONTHLY"></el-option>
            <el-option label="周度" value="WEEKLY"></el-option>
          </el-select>
        </div>
        <div>
          <span class="font-bold mr-2" style="color: #303133">报告日期:</span>
          <el-config-provider v-if="filter.report_type === 'WEEKLY'" :locale="enLocale">
            <el-date-picker
                v-model="dateRange"
                :clearable="false"
                :disabled-date="(time: Date) => time > new Date()"
                :format="`${date[0]} To ${date[1]}`"
                type="week"
                value-format="YYYY-MM-DD"
                @change="calculateDate"
            />
          </el-config-provider>
          <el-date-picker
              v-else
              v-model="dateRange"
              :clearable="false"
              :disabled-date="(time: Date) => time > new Date()"
              :format="`${date[0]} To ${date[1]}`"
              type="month"
              value-format="YYYY-MM-DD"
              @change="calculateDate"
          />
        </div>
      </div>
      <div class="flex gap-3.5">
        <el-button @click="queryDownload" :icon="Download" plain round type="success" :loading="btnLoading">
          文件下载
        </el-button>
      </div>
    </el-card>
    <el-card shadow="hover" style="border: none; margin-bottom: 10px">
      <el-table v-loading="loading" :data="tableData" height="600" style="width: 100%">
        <el-table-column align="center" type="index" width="60">
          <template #header>
            <span>序号</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作时间" prop="OperateTime">
          <template #default="{ row }">
            <span class="font-semibold">{{ row.OperateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关键词" prop="searchTerm">
          <template #default="{ row }">
            <span class="font-semibold">{{ row.searchTerm }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="日期范围" prop="daterange">
          <template #default="{ row }">
            <span class="font-semibold">{{ row.daterange.slice(0, 10) }} To {{ row.daterange.slice(10) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="表名" prop="tableName">
          <template #default="{ row }">
            <span class="font-semibold">{{ row.tableName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="State">
          <template #default="{ row }">
            <span class="font-semibold">{{ row.State }}</span>
            <el-button :icon="Download" class="ml-2" link type="success" :disabled="row.State!='success'" @click="handleDownload(row)"></el-button>
            <el-button :icon="Refresh" type="primary" link @click="handleRefresh(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3.5 flex justify-end">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50, 100, 200]"
            :total="total"
            layout="sizes, prev, pager, next, total"
            @change="handlePageChange"/>
      </div>
    </el-card>
  </div>
</template>

<style scoped>

</style>
