<script lang="ts" setup>
import { computed, defineProps, inject, onMounted, reactive, ref, Ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
  exportDayData,
  exportMonthData,
  exportWeekData,
  getDayData,
  getDayTotalData,
  getMonthData,
  getMonthTotalData,
  getWeekData,
  getWeekTotalData
} from '/src/views/reportManage/dataCenter/api';
import { dayDataColumns, monthDataColumns, weekDataColumns } from '../../utils/columns';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { VxeGridInstance } from 'vxe-table';


const router = useRouter();
const dateType = inject<Ref>('dateDimension');
const currentDate = inject<Ref>('currentDate');
const taskIdsAvailable = ref(false);
const props = defineProps({
  taskIds: Object,
});

const taskIds = ref(props.taskIds);
const totalSales = ref(null);

const dayStartDate = ref(null);
const dayEndDate = ref(null);
const weekStartDate = ref(null);
const weekEndDate = ref(null);
const monthStartDate = ref(null);
const monthEndDate = ref(null);

// 表格数据
const dayData = [];
const weekData = [];
const monthData = [];

// 排序
const order_date = ref('');
const sortOrder = ref('');
const salesOrder = ref(null);
const salesField = ref(null);
const sortStatus = ref(true);

const xGrid = ref<VxeGridInstance>();
const highlightedColumn = ref(null);

const gridOptions = reactive({
  border: 'inner',
  keepSource: true,
  height: 800,
  align: null,
  round: true,
  loading: false,
  id: 'normalCustomStorage',
  customConfig: {
    storage: {
      visible: true,
    }
  },
  columnConfig: {
    isCurrent: true,
    isHover: true,
    resizable: true,
  },
  rowConfig: {
    isHover: true,
    height: 48
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  sortConfig: {
    remote: true,
    defaultSort: {
      field: salesField,
      order: salesOrder,
    }
  },
  toolbarConfig: {
    custom: true,
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  day: {
    columns: dayDataColumns,
    data: dayData
  },
  week: {
    columns: weekDataColumns,
    data: weekData
  },
  month: {
    columns: monthDataColumns,
    data: monthData
  }
});

const currentGridOptions = computed(() => {
  const selectedGridOptions = gridOptions[dateType.value];
  return {
    ...gridOptions,
    ...selectedGridOptions,
  };
});

// 分页
const gridEvents = {
  pageChange({ currentPage, pageSize }) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
      fetchCurrentData(props.taskIds);
    }
  }
};

// 保存排序状态到 localStorage
const saveSortState = () => {
  localStorage.setItem('sortField', order_date.value);
  localStorage.setItem('sortOrder', sortOrder.value);
  localStorage.setItem('salesOrder', salesOrder.value);
  localStorage.setItem('salesField', salesField.value);
};

// 读取排序状态并应用
const loadSortState = () => {
  order_date.value = localStorage.getItem('sortField') || '';
  sortOrder.value = localStorage.getItem('sortOrder') || '';
  gridOptions.sortConfig.defaultSort.order = localStorage.getItem('salesOrder') || '';
  gridOptions.sortConfig.defaultSort.field = localStorage.getItem('salesField') || '';
};
const totalRow = ref({});

async function fetchTotalData(taskIds, apiFunc, startDate, endDate, dateTypeKey) {
  try {
    const resp = await apiFunc({
      data_start_date: startDate.value,
      data_end_date: endDate.value,
      task_ids: taskIds,
    });
    totalRow.value = resp.data[0] || {};
    totalRow.value.platformNumber = '汇总';
  } catch (error) {
    console.error('Error fetching total data:', error);
  }
}

async function fetchDayTotal(taskIds) {
  await fetchTotalData(taskIds, getDayTotalData, dayStartDate, dayEndDate, 'day');
}

async function fetchWeekTotal(taskIds) {
  await fetchTotalData(taskIds, getWeekTotalData, weekStartDate, weekEndDate, 'week');
}

async function fetchMonthTotal(taskIds) {
  await fetchTotalData(taskIds, getMonthTotalData, monthStartDate, monthEndDate, 'month');
}

async function fetchCurrentTotalData(taskIds) {
  if (dateType.value === 'day') {
    await fetchDayTotal(taskIds);
  } else if (dateType.value === 'week') {
    await fetchWeekTotal(taskIds);
  } else if (dateType.value === 'month') {
    await fetchMonthTotal(taskIds);
  }
}

async function fetchData(taskIds, apiFunc, startDate, endDate, dataColumns, dateTypeKey) {
  try {
    //loadSortState();
    const resp = await apiFunc({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      [`${ dateTypeKey }_start_date`]: startDate.value,
      [`${ dateTypeKey }_end_date`]: endDate.value,
      task_ids: taskIds,
      sort: sortOrder.value,
      order_date: order_date.value,
      order_total_sales_current_monthly: totalSales.value,
    });
    gridOptions[dateType.value].data = [totalRow.value, ...resp.data];
    gridOptions.pagerConfig.total = resp.total;
    if (sortStatus.value) {
      if (resp.data.length > 0) {
        const allColumns = new Set();
        const salesColumns = [];
        const otherColumns = [];
        //清空列名
        dataColumns.value = dataColumns.value.filter(column => !/\d{2}-\d{2}/.test(column.field) && !column.field.includes('余额币种') && !column.field.includes('退货率'));

        resp.data.forEach(row => {
          for (const key in row) {
            if (/\d{2}-\d{2}/.test(key) || key.includes('余额币种') || key.includes('退货率')) {
              allColumns.add(key);
            }
          }
        });

        //"的销售额"字段可以排序
        allColumns.forEach(key => {
          let isSortable = false;
          if (key.includes('的销售额')&& !key.includes('增长率') || key.includes('当月累计销售额') && !key.includes('增长率')) {
            isSortable = true;
          }
          const column = {
            field: key,
            title: key,
            minWidth: key.includes('~') ? 95 : /\d{4}-\d{2}-\d{2}的/.test(key) ? 93 : key.includes('截止') ? 90 : /\d{4}-\d{2}的销售额/.test(key) ? 127 : 79,
            align: 'center',
            formatter: formatEmptyCell,
            sortable: isSortable,
          };
          if (key.includes('的销售额') && !key.includes('增长率')) {
            salesColumns.push(column);
          } else {
            otherColumns.push(column);
          }
        });

        // 对 salesColumns 按日期排序
        if (dateType.value == 'day') {
          salesColumns.sort((a, b) => {
            const dateA = a.field.match(/\d{4}-\d{2}-\d{2}/)[0];
            const dateB = b.field.match(/\d{4}-\d{2}-\d{2}/)[0];
            return new Date(dateA) - new Date(dateB);
          });
        } else if (dateType.value == 'week') {
          salesColumns.sort((a, b) => {
            const dateA = a.field.match(/\d{4}-\d{2}-\d{2}~\d{4}-\d{2}-\d{2}/)[0].split('~')[0];
            const dateB = b.field.match(/\d{4}-\d{2}-\d{2}~\d{4}-\d{2}-\d{2}/)[0].split('~')[0];
            return new Date(dateA) - new Date(dateB);
          });
        } else if (dateType.value == 'month') {
          salesColumns.sort((a, b) => {
            const dateA = a.field.match(/\d{4}-\d{2}/)[0];
            const dateB = b.field.match(/\d{4}-\d{2}/)[0];
            return new Date(dateA) - new Date(dateB);
          });
        }
        const dynamicColumns = [...salesColumns, ...otherColumns];

        if (dateType.value === dateTypeKey) {
          dataColumns.value = [...dataColumns.value, ...dynamicColumns];
        } else {
          dataColumns.value = [];
          gridOptions.pagerConfig.total = 0;
        }
      }
    }
    saveSortState();
  } catch (error) {
    console.error('Error fetching task data:', error);
  }
}

async function fetchDayData(taskIds) {
  await fetchData(taskIds, getDayData, dayStartDate, dayEndDate, dayDataColumns, 'day');
}

async function fetchWeekData(taskIds) {
  await fetchData(taskIds, getWeekData, weekStartDate, weekEndDate, weekDataColumns, 'week');
}

async function fetchMonthData(taskIds) {
  await fetchData(taskIds, getMonthData, monthStartDate, monthEndDate, monthDataColumns, 'month');
}

async function fetchCurrentData(taskIds, resetPage = false) {
  gridOptions.loading = true;
  if (resetPage) {
    gridOptions.pagerConfig.currentPage = 1; // 重置页码为第一页
  }
  await fetchCurrentTotalData(taskIds);
  if (dateType.value === 'day') {
    await fetchDayData(taskIds);
  } else if (dateType.value === 'week') {
    await fetchWeekData(taskIds);
  } else if (dateType.value === 'month') {
    await fetchMonthData(taskIds);
  }
  if (highlightedColumn.value) {
    const $grid = xGrid.value;
    await $grid.setCurrentColumn(highlightedColumn.value); // 设置当前高亮列
  }
  gridOptions.loading = false;
}

function handleSortChange({ field, order }) {
  salesOrder.value = order;
  salesField.value = field;
  sortOrder.value = order === 'asc' ? 'smallfirst' : 'bigfirst';
  if (field) {
    const match = field.match(/(\d{4}-\d{2}-\d{2})的销售额/);
    const matchRange = field.match(/(\d{4}-\d{2}-\d{2})~(\d{4}-\d{2}-\d{2})的销售额/);
    const matchMonth = field.match(/(\d{4}-\d{2})的销售额/);
    const matchTotal = field.match(/当月累计销售额/);
    if (matchRange) {
      order_date.value = matchRange[2];
      totalSales.value = '';
    } else if (match) {
      order_date.value = match[1];
      totalSales.value = '';
    } else if (matchMonth) {
      order_date.value = `${ matchMonth[1] }-01`;
      totalSales.value = '';
    } else if (matchTotal) {
      clearSort();
      totalSales.value = true;
    }
  }
  saveSortState(); // 保存排序状态
  gridOptions.sortConfig.defaultSort.order = order;
  gridOptions.sortConfig.defaultSort.field = field;
  sortStatus.value = false;
  fetchCurrentData(props.taskIds, true);
}

function clearSort() {
  order_date.value = '';
  salesOrder.value = null;
}

const handleImport = () => {
  const url = router.resolve({
    name: 'DataEntry',
    query: {
      dateType: dateType.value,
    }
  }).href;
  window.open(url, '_blank');
};

const handelPlanSales = () => {
  const url = router.resolve({
    name: 'PlanningSales',
  }).href;
  window.open(url, '_blank');
};

async function handleExport(taskIds, apiFunc, startDate, endDate, dateTypeKey) {
  try {
    gridOptions.loading = true;
    const response = await apiFunc({
      [`${ dateTypeKey }_start_date`]: startDate.value,
      [`${ dateTypeKey }_end_date`]: endDate.value,
      task_ids: taskIds,
      sort: sortOrder.value,
      order_date: order_date.value,
      order_total_sales_current_monthly: totalSales.value,
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    // 根据 dateTypeKey 设置文件名
    let fileName = '';
    if (dateTypeKey === 'day') {
      fileName = `${ startDate.value }~${ endDate.value }日数据.xlsx`;  // 当为天时
    } else if (dateTypeKey === 'week') {
      fileName = `${ startDate.value }~${ endDate.value }周数据.xlsx`;  // 当为周时
    } else if (dateTypeKey === 'month') {
      fileName = `${ startDate.value }~${ endDate.value }月数据.xlsx`; // 当为月时
    }
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    gridOptions.loading = false;
    ElMessage.success('导出数据成功');
  } catch (error) {
    console.error('导出数据失败:', error);
  }
}

async function handleExportDay() {
  await handleExport(taskIds.value, exportDayData, dayStartDate, dayEndDate, 'day');
}

async function handleExportWeek() {
  await handleExport(taskIds.value, exportWeekData, weekStartDate, weekEndDate, 'week');
}

async function handleExportMonth() {
  await handleExport(taskIds.value, exportMonthData, monthStartDate, monthEndDate, 'month');
}

async function handelExportCurrent() {
  if (dateType.value === 'day') {
    await handleExportDay();
  } else if (dateType.value === 'week') {
    await handleExportWeek();
  } else if (dateType.value === 'month') {
    await handleExportMonth();
  }
}

function formatEmptyCell({ cellValue }) {
  if (cellValue === null || cellValue === undefined || cellValue === '') {
    return '--';
  }
  if (typeof cellValue === 'number') {
    const formatter = new Intl.NumberFormat('en-US', {
      minimumFractionDigits: 2,
    });
    return formatter.format(cellValue);
  }
  return cellValue;
}

const cellStyle = (row) => {
  if (row.$rowIndex === 0 && row.$columnIndex < 5) {
    return {
      position: 'sticky',
      top: 0,
      zIndex: 30,
      fontSize: '12px',
      fontWeight: '600',
    };
  }
  return {
    fontSize: '12px',
    fontWeight: '600',
    padding: 0,
  };
};

const headerCellStyle = () => {
  return {
    fontSize: '12px',
  };
};

const rowStyle = (row) => {
  if (row.$rowIndex === 0) {
    return {
      background: '#def6fe',
      position: 'sticky',
      top: 0,
      zIndex: 1,
    };
  }
  return {
    padding: 0,
    height: '50px',
  };
};

watch([() => props.taskIds, currentDate], async ([newTaskIds, newCurrentDate]) => {
  sortStatus.value = true;

  if (dateType.value === 'day') {
    dayStartDate.value = dayjs(newCurrentDate.dailyStartDate).format('YYYY-MM-DD');
    dayEndDate.value = dayjs(newCurrentDate.dailyTime).format('YYYY-MM-DD');
  } else if (dateType.value === 'week') {
    weekStartDate.value = dayjs(newCurrentDate.weekStartDate).format('YYYY-MM-DD');
    weekEndDate.value = dayjs(newCurrentDate.weekEndDate).format('YYYY-MM-DD');
  } else if (dateType.value === 'month') {
    monthStartDate.value = dayjs(newCurrentDate.startDate).format('YYYY-MM-DD');
    monthEndDate.value = dayjs(newCurrentDate.endDate).format('YYYY-MM-DD');
  }
  clearSort();
  if (newTaskIds) {
    taskIdsAvailable.value = true;
    taskIds.value = newTaskIds;
  }
  if (taskIdsAvailable.value && newTaskIds) {
    await fetchCurrentData(newTaskIds, true); // 使用 await 确保顺序
    taskIdsAvailable.value = false; // 调用后重置标记
  }
});

function handelIsCurrent({column}) {
  highlightedColumn.value= column.field;
}


onMounted(() => {
  //loadSortState();
});
</script>

<template>
  <div>
    <vxe-grid ref="xGrid" :cell-style="cellStyle" :header-cell-style="headerCellStyle" :row-style="rowStyle"
              stripe
              v-bind="currentGridOptions" v-on="gridEvents" @sort-change="handleSortChange"
              @header-cell-click="handelIsCurrent">
      <template #toolbar_buttons>
        <el-button icon="plus" target="_blank" type="primary" @click="handleImport">数据录入</el-button>
        <el-button v-if="dateType === 'month'" bg icon="plus"
                   target="_blank" text
                   @click="handelPlanSales">
          计划销售额
        </el-button>
      </template>
      <template #toolbar_tools>
        <div class="pr-2.5">
          <el-tooltip content="下载表格" placement="top">
            <vxe-button circle icon="vxe-icon-download" @click="handelExportCurrent"></vxe-button>
          </el-tooltip>
        </div>
      </template>
      <template #platformNumber_default="{ row }">
        <div class="font-semibold" style="padding: 0">{{ row.platformNumber }}</div>
      </template>
      <template #platformName_default="{ row }">
        <div class="font-semibold" style="color: #164285">{{ row.platformName }}</div>
      </template>
    </vxe-grid>
  </div>
</template>

<style scoped>
.vxe-grid {
  border-radius: 10px;
}

:deep(.vxe-table--header .vxe-header--row th .vxe-cell,
.vxe-table--body .vxe-body--row td .vxe-cell) {
  padding-left: 5px !important;
  padding-right: 0 !important;
}

</style>
