<script lang="ts" setup>
/**
 * @Name: index.vue
 * @Description: brandView
 * @Author: Cheney
 */

import { Refresh, Search } from '@element-plus/icons-vue';
import { onBeforeMount, reactive, ref, watch } from 'vue';
import dayjs from 'dayjs';
import { getTableData } from './api';
import { ElMessage } from 'element-plus';
import { brandColumns } from './useColumns';
import WeekRangePicker from '/@/components/WeekRangePicker/index.vue';
import MonthRangePicker from '/@/components/MonthRangePicker/index.vue';
import { useCustomHeight } from '/@/utils/useCustomHeight';


const topCard = ref();
const heightObj = { topBar: 50, topCard: topCard, cardMargin: 32 };
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 reportTypeSelect = ref('weekly');
const searchTermInp = ref('zosi');
const tableLoading = ref(false);

const gridOptions: any = reactive({
  height: 'auto',
  border: false,
  round: true,
  columnConfig: {
    resizable: true
  },
  toolbarConfig: {
    custom: true,
    slots: {
      buttons: 'toolbar_buttons'
    }
  },
  columns: brandColumns,
  data: []
});

const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 20
});

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

watch([ weekDate, monthDate ], () => {
  fetchTableData();
});

async function handlePageChange({ currentPage, pageSize }) {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  await fetchTableData();
}

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

async function refreshTable() {
  tablePage.currentPage = 1;
  tablePage.pageSize = 20;
  searchTermInp.value = '';
  reportTypeSelect.value = 'weekly';
  await fetchTableData();
}

async function fetchTableData() {
  tableLoading.value = true;
  const query = {
    page: tablePage.currentPage,
    limit: tablePage.pageSize,
    search_term: searchTermInp.value,
    report_type: reportTypeSelect.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 getTableData(query);
    tablePage.total = response.total;
    gridOptions.data = response.data;
  } catch (error) {
    console.error('==Error==:', error);
  } finally {
    tableLoading.value = false;
  }
}

/**
 * 输入框按下回车后触发
 */
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 calculateLastWeek() {
  const today = dayjs();
  const lastDay = today.subtract(1, 'day'); // 昨天
  const firstDay = lastDay.subtract(6, 'day'); // 一周前
  return [ firstDay.format('YYYY-MM-DD'), lastDay.format('YYYY-MM-DD') ];
}
</script>

<template>
  <div class="py-2 px-2.5" style="background-color: #f7f7f7">
    <div ref="topCard">
      <el-card class="mb-2.5" shadow="hover" style="border: none; margin-bottom: 10px">
        <div class="flex justify-between">
          <div class="flex gap-5 flex-wrap">
            <div>
              <span class="font-medium mr-0.5">报告类型 </span>
              <el-select v-model="reportTypeSelect" style="width: 90px" @change="handleSelectChange">
                <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"
                  @clear="handleSelectChange"
                  @keyup.enter="handleQueryChange"/>
            </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="Refresh" circle @click="refreshTable"></el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-card :body-style="{ height: tableHeight + 'px' }" shadow="hover" style="border: none;">
      <div v-loading="tableLoading" class="w-full h-full">
        <vxe-grid v-bind="gridOptions">
          <template #toolbar_buttons></template>
          <template v-for="col in brandColumns" #[`${col.field}_default`]="{ row }">
            <div v-if="col.field === 'clickedItemName'">
              <el-tooltip :content="row.clickedItemName" :show-after="300" effect="dark" placement="top">
                <div class="line-text">
                  {{ row.clickedItemName }}
                </div>
              </el-tooltip>
            </div>
            <div v-else class="font-medium">
              {{ row[col.field] ? row[col.field] : '-' }}
            </div>
          </template>
          <template #pager>
            <vxe-pager
                v-model:current-page="tablePage.currentPage"
                v-model:page-size="tablePage.pageSize"
                :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                :total="tablePage.total"
                @page-change="handlePageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.line-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
