<script lang="ts" setup>
/**
 * @Name: index.vue
 * @Description: 搜索词-TopSearchTerm Rank
 * @Author: Cheney
 */

import { DataLine, Key, PictureRounded, Refresh, Search, TopRight } from '@element-plus/icons-vue';
import { nextTick, onBeforeMount, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { marketplaceIdEnum } from '/@/utils/marketplaceIdEnum';
import { usePagination } from '/@/utils/usePagination';
import { getTopSearchTermTable } from './api';
import { ElMessage } from 'element-plus';
import ColumnChart from '/src/views/searchTerm/topSearchTermRank/column-chart.vue';
import dayjs from 'dayjs';
import WeekRangePicker from '/@/components/WeekRangePicker/index.vue';
import MonthRangePicker from '/@/components/MonthRangePicker/index.vue';
import { useCustomHeight } from '/@/utils/useCustomHeight';


const titleContainer = ref();
const queryContainer = ref();
const heightObj = {
  a: 32 + 13 + 40 + 70 + 40 + 48 + 95
}
const { tableHeight } = useCustomHeight(heightObj);

const weekDate = ref([
  dayjs().subtract(2, 'week').day(0).format('YYYY-MM-DD'),
  dayjs().subtract(1, 'week').day(6).format('YYYY-MM-DD')
]);
const monthDate = ref([
  dayjs().subtract(2, 'month').startOf('month').format('YYYY-MM-DD'),
  dayjs().subtract(0, 'month').startOf('month').format('YYYY-MM-DD')
]);
const router = useRouter();
const { tableData, total, currentPage, pageSize, handlePageChange } = usePagination(fetchTableData);
const marketplaceSelect = ref(marketplaceIdEnum[0].value); // 当前只有美国区 默认第一个为美国
const marketplaceOptions = marketplaceIdEnum;
const reportTypeSelect = ref('weekly');
const searchTermInp = ref('');
const asinInp = ref('');
const tableLoading = ref(false);

onBeforeMount(() => {
  fetchTableData();
});

async function refreshTable() {
  currentPage.value = 1;
  pageSize.value = 10;
  asinInp.value = '';
  searchTermInp.value = '';
  reportTypeSelect.value = 'weekly';
  marketplaceSelect.value = marketplaceIdEnum[0].value;
  await fetchTableData();
}

async function fetchTableData(isQuery = false) {
  if (!validateSearchTermInput(searchTermInp.value)) {
    if (searchTermInp.value.length == 0) {
      return;
    } else {
      ElMessage.warning({ message: '搜索词只能输入数字和英文字母', plain: true });
      return;
    }
  }
  if (asinInp.value.length > 0 && !validateAsinInput(asinInp.value)) {
    ElMessage.warning({ message: '不符合匹配规范', plain: true });
    return;
  }
  // await fetchTableData();

  tableLoading.value = true;

  if (isQuery) {
    currentPage.value = 1;
  }

  const query = {
    page: currentPage.value,
    limit: pageSize.value,
    asin: asinInp.value,
    search_term: searchTermInp.value,
    report_type: reportTypeSelect.value,
    marketplace_Ids: marketplaceSelect.value,
    date_start: reportTypeSelect.value == 'weekly' ? weekDate.value[0] : monthDate.value[0],
    date_end: reportTypeSelect.value == 'weekly' ? weekDate.value[1] : monthDate.value[1]
  };
  try {
    const response = await getTopSearchTermTable(query);
    total.value = response.total;
    tableData.value = response.data;
  } catch (error) {
    console.error('==Error==:', error);
  } finally {
    tableLoading.value = false;
    await nextTick();
    // 触发窗口 resize 事件
    window.dispatchEvent(new Event('resize'));
  }
}

async function handleSelectChange() {
  await fetchTableData();
}

async function handleQueryChange() {
  if (!validateSearchTermInput(searchTermInp.value)) {
    if (searchTermInp.value.length == 0) {
      return;
    } else {
      ElMessage.warning({ message: '搜索词只能输入数字和英文字母', plain: true });
      return;
    }
  }
  if (asinInp.value.length > 0 && !validateAsinInput(asinInp.value)) {
    ElMessage.warning({ message: '不符合匹配规范', plain: true });
    return;
  }
  await fetchTableData();
}

/**
 * 校验SearchTerm输入是否合法
 * @param input 输入的字符串
 */
function validateSearchTermInput(input: string) {
  const regex = /^[a-zA-Z0-9\s]*$/;
  return regex.test(input);
}

/**
 * 校验Asin输入是否合法
 * @param input 输入的字符串
 */
function validateAsinInput(input: string) {
  const regex = /^[Bb]0[A-Za-z0-9\s]*$/i;
  return regex.test(input);
}

function handleJump() {
  router.push({ path: '/searchTerm/rootWordManage' });
}
</script>

<template>
  <div ref="titleContainer" class="mx-3">
    <el-divider>
      <div class="font-bold text-xl">
        <el-icon style="top: 3px">
          <DataLine/>
        </el-icon>
        Top Search Term - Rank
      </div>
    </el-divider>
  </div>
  <el-card v-loading="tableLoading" class="mx-3 mb-2.5" style="border: none">
    <!-- table筛选栏 -->
    <div ref="queryContainer" class="flex justify-between">
      <div class="flex gap-5 flex-wrap">
        <div>
          <span class="font-medium mr-0.5">市 场 </span>
          <el-select v-model="marketplaceSelect" style="width: 90px">
            <el-option
                v-for="item in marketplaceOptions"
                :key="item.value"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </div>
        <div>
          <span class="font-medium mr-0.5">报告类型 </span>
          <el-select v-model="reportTypeSelect" style="width: 90px">
            <el-option label="周度" value="weekly"/>
            <el-option label="月度" value="monthly"/>
          </el-select>
        </div>
        <div>
          <span class="font-medium mr-0.5">搜索词 </span>
          <el-input
              v-model="searchTermInp"
              :prefix-icon="Search"
              clearable
              placeholder="请输入"
              style="width: 240px" />
        </div>
        <div>
          <span class="font-medium mr-0.5">ASIN </span>
          <el-input
              v-model="asinInp"
              :prefix-icon="Search"
              clearable
              placeholder="请输入"
              style="width: 180px" />
        </div>
        <div>
          <span class="font-medium mr-0.5">报告日期 </span>
          <MonthRangePicker v-if="reportTypeSelect === 'monthly'" v-model="monthDate"/>
          <WeekRangePicker v-else v-model="weekDate"/>
        </div>
      </div>
      <div class="flex">
        <el-button :icon="Search" type="primary" @click="fetchTableData(true)">查 询</el-button>
        <el-button :icon="Refresh" @click="refreshTable">刷 新</el-button>
      </div>

    </div>
    <div class="mt-6">
      <el-button :icon="TopRight" plain type="primary" @click="handleJump">搜索词管理</el-button>
    </div>
    <!-- table -->
    <el-card class="mt-5" shadow="never">
      <div>
        <el-table :data="tableData" :height="tableHeight" stripe style="width: 100%">
          <el-table-column fixed label="搜索词" prop="searchTerm" width="260">
            <template #header>
              <el-icon style="top: 2px; margin-right: 3px">
                <Key/>
              </el-icon>
              <span>搜索词</span>
            </template>
            <template #default="{ row }">
              <el-link :underline="false" style="color: #5a6fc0" target="_blank">
                {{ row.searchTerm }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column align="center" label="搜索词搜索排名" prop="rank">
            <template #header>
              <el-icon style="top: 2px; margin-right: 4px">
                <PictureRounded/>
              </el-icon>
              <span>Tendency</span>
            </template>
            <template #default="{ row }">
              <ColumnChart :rowData="row"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <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="prev, pager, next, sizes, total"
            @change="handlePageChange"/>
      </div>
    </el-card>
  </el-card>
</template>

<style scoped>
:deep(.el-divider__text.is-center.el-divider__text) {
  background-color: #f8f8f8;
}
</style>
