<script lang="ts" setup>
import { defineProps, onMounted, reactive, ref } from 'vue';
import {
  exportData,
  getDayTotalData,
  getMainData,
  getMonthTotalData,
  getWeekTotalData
} from '/@/views/reportManage/dataCenter/api';
import { universal } from '../../../utils/columns';
import { ElMessage } from 'element-plus';
import Selector from '/src/views/reportManage/dataCenter/normalDisplay/components/Selector/index.vue';
import DataPicker from '/@/views/reportManage/dataCenter/combinedDisplay/components/DatePicker/index.vue';
import { VxeGridInstance } from 'vxe-table';

const props = defineProps({
  taskIds: Object,
  dayDate: Object,
  weekDate: Object,
  monthDate: Object,
});

const taskIds = ref(null);
const tableColumns = ref([]);
const tableData = ref([]);
const totalRow = ref([]);// 汇总数据
const selectorRef = ref(null);

const dayStartDate = ref(null);
const dayEndDate = ref(null);
const weekStart = ref(null);
const weekEnd = ref(null);
const monthStartDate = ref(null);
const monthEndDate = ref(null);

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

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

const gridOptions = reactive({
  border: 'inner',
  keepSource: true,
  height: 800,
  align: null,
  round: true,
  loading: false,
  id: 'mainDataCustomStorage',
  columnConfig: {
    resizable: true,
    isCurrent: 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,
    }
  },
  customConfig: {
    storage: {
      visible: true,
    }
  },
  toolbarConfig: {
    custom: true,
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
    slots: {
      tools: 'toolbar_buttons',
    },
  },
  columns: tableColumns,
  data: tableData,
});

// 保存排序状态到 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 gridEvents = {
  pageChange({ currentPage, pageSize }) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
      sortStatus.value = false;
      fetchMainData(props.taskIds);
    }
  },
};

// 获取汇总数据
async function fetchTotalData(taskIds) {
  try {
    const dayTotalData = await getDayTotalData({
      data_start_date: dayStartDate.value,
      data_end_date: dayEndDate.value,
      dataType:'all',//权限控制
      task_ids: taskIds,
    });
    const weekTotalData = await getWeekTotalData({
      data_start_date: weekStart.value,
      data_end_date: weekEnd.value,
      dataType:'all',
      task_ids: taskIds,
    });
    const monthTotalData = await getMonthTotalData({
      data_start_date: monthStartDate.value,
      data_end_date: monthEndDate.value,
      dataType:'all',
      task_ids: taskIds,
    });
    totalRow.value = {
      ...dayTotalData.data[0],
      ...weekTotalData.data[0],
      ...monthTotalData.data[0],
    };
    totalRow.value.platformNumber = '汇总';
  } catch (error) {
    console.error('Error fetching total data:', error);
  }
}


// 获取数据
async function fetchMainData(taskIds, resetPage = false) {
  if (resetPage) {
    gridOptions.pagerConfig.currentPage = 1; // 重置页码为第一页
  }
  try {
    gridOptions.loading = true;
    await fetchTotalData(taskIds);
    const response = await getMainData({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      task_ids: taskIds,
      day_start_date: dayStartDate.value,
      day_end_date: dayEndDate.value,
      week_start_date: weekStart.value,
      week_end_date: weekEnd.value,
      month_start_date: monthStartDate.value,
      month_end_date: monthEndDate.value,
      sort: sortOrder.value,
      order_date: order_date.value,
      date_type: dateType.value,
      order_total_sales_current_monthly: totalSales.value,
    });
    gridOptions.data = [totalRow.value, ...response.data];
    gridOptions.pagerConfig.total = response.total;
    if (!sortStatus.value) {
      if (response.data && response.data.length > 0) {
        const dynamicColumns = [];
        const regex1 = /\d{2}-\d{2}/;
        const regex2 = /\d{4}-\d{2}-\d{2}/;
        const regex3 = /\d{4}-\d{2}/;
        const regex4 = /\d{4}-\d{2}-\d{2}~\d{4}-\d{2}-\d{2}/;
        const middleKeywords = ['~', '截止', '近90天平台退货率', '余额'];

        const allColumns = new Set();
        response.data.forEach(row => {
          for (const key in row) {
            if (regex1.test(key) || middleKeywords.some(kw => key.includes(kw))) {
              allColumns.add(key);
            }
          }
        });

        const firstColumns = [];
        const middleColumns = [];
        const lastColumns = [];

        allColumns.forEach(key => {
          let isSortable = false;
          if (key.includes('的销售额')&& !key.includes('增长率') || key.includes('当月累计销售额')&& !key.includes('广告销售额') && !key.includes('增长率')) {
            isSortable = true;
          }
          const column = {
            field: key,
            title: key, // 使用字段名作为列标题
            minWidth: key.includes('~') ? 94 : key.includes('截止') ? 94 : regex2.test(key) ? 95 : /\d{4}-\d{2}的销售额/.test(key) ? 127 : 76,
            align: 'center',
            formatter: formatEmptyCell,
            sortable: isSortable,
          };
          if (middleKeywords.some(kw => key.includes(kw))) {
            middleColumns.push(column);
          } else if (regex3.test(key) && !regex2.test(key)) {
            lastColumns.push(column);
          } else if (regex1.test(key)) {
            firstColumns.push(column);
          }
        });
        // 对 firstColumns 中包含‘的销售额’字段的日期进行排序
        const daySalesColumns = firstColumns.filter(column => column.field.includes('的销售额') && !column.field.includes('增长率'));
        daySalesColumns.sort((a, b) => {
          const dateA = a.field.match(/\d{4}-\d{2}-\d{2}/);
          const dateB = b.field.match(/\d{4}-\d{2}-\d{2}/);
          if (dateA && dateB) {
            return new Date(dateA[0]) - new Date(dateB[0]);
          }
          return 0;
        });

        const weekSalesColumns = middleColumns.filter(column => column.field.includes('的销售额') && !column.field.includes('增长率'));
        weekSalesColumns.sort((a, b) => {
          const dateA = a.field.match(regex4)[0].split('~')[0];
          const dateB = b.field.match(regex4)[0].split('~')[0];
          return new Date(dateA) - new Date(dateB);
        });

        const monthSalesColumns = lastColumns.filter(column => column.field.includes('的销售额'));
        monthSalesColumns.sort((a, b) => {
          const dateA = `${ a.field.match(regex3)[0] }-01`;
          const dateB = `${ b.field.match(regex3)[0] }-01`;
          return new Date(dateA) - new Date(dateB);
        });

        // 将排序后的列和其他列合并
        dynamicColumns.push(...daySalesColumns,
            ...firstColumns.filter(column => !column.field.includes('的销售额')),
            ...weekSalesColumns,
            ...middleColumns.filter(column => !regex4.test(column.field)),
            ...monthSalesColumns,
            ...lastColumns.filter(column => !column.field.includes('的销售额')));

        tableColumns.value = [
          ...universal,
          ...dynamicColumns,
        ];
      }
    }
    saveSortState();
    setTimeout(() => {
      handelCurrent();
    }, 0);
  } catch (error) {
    console.error('Error fetching task data:', error);
  } finally {
    gridOptions.loading = false;
  }
}

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

//排序
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];
      dateType.value = 'week';
      totalSales.value = '';
    } else if (match) {
      order_date.value = match[1];
      dateType.value = 'day';
      totalSales.value = '';
    } else if (matchMonth) {
      order_date.value = `${ matchMonth[1] }-01`;
      dateType.value = 'month';
      totalSales.value = '';
    }else if (matchTotal) {
      clearSort();
      dateType.value = 'week';
      totalSales.value = true;
    }
  }
  gridOptions.sortConfig.defaultSort.order = order;
  gridOptions.sortConfig.defaultSort.field = field;
  sortStatus.value = true;
  fetchMainData(taskIds.value, true);
}

// 导出数据接口
async function handleExport() {
  try {
    gridOptions.loading = true;
    const params = {
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      task_ids: taskIds.value,
      day_start_date: dayStartDate.value,
      day_end_date: dayEndDate.value,
      week_start_date: weekStart.value,
      week_end_date: weekEnd.value,
      month_start_date: monthStartDate.value,
      month_end_date: monthEndDate.value,
    };
    const response = await exportData(params);
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '合并数据展示.xlsx');
    document.body.appendChild(link);
    link.click();
    gridOptions.loading = false;
    ElMessage.success('导出数据成功');
  } catch (error) {
    console.error('导出数据失败:', error);
  }
}

const processingDateChange = (date) => {
  dayStartDate.value = date.dayDate.dailyStartDate;
  dayEndDate.value = date.dayDate.dailyTime;
  weekStart.value = date.weekDate.weekStartDate;
  weekEnd.value = date.weekDate.weekEndDate;
  monthStartDate.value = date.monthDate.startDate.value;
  monthEndDate.value = date.monthDate.endDate.value;
  if (taskIds.value) {
    fetchMainData(taskIds.value, true);
  }
};

function updateDataChange(newId) {
  if (selectorRef.value) {
    taskIds.value = newId.value;
    fetchMainData(newId.value, true);
  }
}

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


function handelCurrent() {
  const $grid = xGrid.value;
  $grid.setCurrentColumn(highlightedColumn.value);
}

//以下是表格样式
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: '2px 0',
  };
};

const cellStyleHandler = ({ column }) => {
  const columnName = column.field;
  const dayFormat = /\d{2}-\d{2}/;
  const dayDetailedFormat = /\d{4}-\d{2}-\d{2}/;
  const monthFormat = /\d{4}-\d{2}/;
  if (columnName.includes('~') || columnName.includes('截止') || columnName.includes('近90天平台退货率') || columnName.includes('余额')) {
    return { fontSize: '12px', padding: '2px 0', backgroundColor: '#e0f2fe' };
  }
  if (monthFormat.test(columnName) && !dayDetailedFormat.test(columnName)) {
    return { fontSize: '12px', padding: '2px 0', backgroundColor: 'rgba(186,230,253,0.9)' };
  }
  if (dayFormat.test(columnName)) {
    return { fontSize: '12px', padding: '2px 0', backgroundColor: '#f0f9ff' };
  }
  return { fontSize: '12px', };
};

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

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;
}

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

<template>
  <div class="px-3.5">
    <el-card body-style="padding: 10px" class="mb-3.5 mt-3.5">
      <div class="custom-card-style flex gap-1.5 justify-between my-1.5 mx-2"
           style="display: flex; align-items: center;">
        <Selector ref="selectorRef" @update:updateData="updateDataChange" />
      </div>
      <div>
        <DataPicker style="display: flex; align-items: center; gap: 16px" @changeDate="processingDateChange" />
      </div>
    </el-card>
    <el-card class="mt-3">
      <slot name="table-header"></slot>
      <vxe-grid ref="xGrid" :cell-style="cellStyle" :header-cell-style="cellStyleHandler" :row-style="rowStyle" v-bind="gridOptions" stripe
                v-on="gridEvents" @sort-change="handleSortChange" @header-cell-click="handelIsCurrent">
        <template #toolbar_buttons>
          <div class="mx-3.5">
            <vxe-button circle icon="vxe-icon-download" @click="handleExport"></vxe-button>
          </div>
        </template>
        <template #platformNumber_default="{ row }">
          <div class="font-semibold">{{ row.platformNumber }}</div>
        </template>
        <template #platformName_default="{ row }">
          <div class="font-semibold" style="color: #164285">{{ row.platformName }}</div>
        </template>
        <template #brandName_default="{ row }">
          {{ row.brandName }}
        </template>
      </vxe-grid>
    </el-card>
  </div>


</template>

<style scoped>
.toolbar-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

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

.el-card {
  border: none;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0px 0px 12px rgba(51, 89, 181, 0.16);
}
</style>