<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { getMonthlyData } from '/@/views/reportManage/dataCenter/api';
import { getLineData, getLineForMonth, getLineForWeek, } from '/src/views/reportManage/dataCenter/api';
import { universal } from '../../../utils/columns';
import MonthlyDatePicker from '/src/views/reportManage/dataCenter/combinedDisplay/components/monthDatePicker/index.vue';
import { monthCompareMetricsEnum } from '/src/views/reportManage/dataCenter/utils/enum';
import chartDateTendency
  from '/src/views/reportManage/dataCenter/combinedDisplay/components/chartDateTendency/index.vue';
import Selector from '/@/views/reportManage/dataCenter/normalDisplay/components/Selector/index.vue';

const selectorRef = ref(null);
const taskIds = ref({});
const monthCurrentDate = ref({});

const monthQueryParams = ref({
  taskIds,
  monthCurrentDate,
});

const tableColumns = ref([]);
const tableData = ref([]);

const monthStartDate = ref(null);
const monthEndDate = ref(null);

const gridOptions = reactive({
  border: 'inner',
  height: 800,
  align: null,
  round: true,
  loading: false,
  id: 'monthlyCustomStorage',
  customConfig: {
    storage: {
      visible: true,
    }
  },
  columnConfig: {
    isCurrent: true,
    resizable: true,
  },
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  toolbarConfig: {
    custom: true,
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
  },
  columns: tableColumns,
  data: tableData,
});

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

async function fetchMonthlyData(taskIds, resetPage = false) {
  if (resetPage) {
    gridOptions.pagerConfig.currentPage = 1; // 重置页码为第一页
  }
  try {
    gridOptions.loading = true;
    const response = await getMonthlyData({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      task_ids: taskIds,
      month_start_date: monthStartDate.value,
      month_end_date: monthEndDate.value,
    });
    if (response.data && response.data.length > 0) {
      tableData.value = response.data;
      gridOptions.pagerConfig.total = response.total;

      const allColumns = new Set();
      response.data.forEach(row => {
        Object.keys(row).forEach(key => {
          if (key.includes('的销售额') || key.includes('的周销售额')) {
            allColumns.add(key);
          }
        });
      });

      const dynamicColumns = Array.from(allColumns).map(key => ({
        field: key,
        title: key,
        minWidth: 120,
        align: 'center',
        formatter: formatEmptyCell,
      }));

      tableColumns.value = [
        ...universal,
        ...dynamicColumns
      ];
    } else {
      tableData.value = [];
      gridOptions.pagerConfig.total = 0;
    }

  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    gridOptions.loading = false;
  }
}

const handelDateChange = (date) => {
  monthCurrentDate.value = date;
  monthStartDate.value = date.startDate;
  monthEndDate.value = date.endDate;
  if (taskIds.value && Object.keys(taskIds.value).length > 0) {
    fetchMonthlyData(taskIds.value, true);
  }
};

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

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

const cellStyle = () => {
  return {
    fontSize: '12px',
    fontWeight: '600',
    padding:0,
  };
};

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

const rowStyle = () => {
  return{
    padding:0,
    height: '50px',
  }
}

</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" />
        <MonthlyDatePicker @monthDateChange="handelDateChange"></MonthlyDatePicker>
      </div>
    </el-card>
    <el-card>
      <chartDateTendency
          :fetch-line-month="getLineForMonth"
          :fetch-line-week="getLineForWeek"
          :fetchLine="getLineData"
          :metricEnum="monthCompareMetricsEnum"
          :query="monthQueryParams"
      >
      </chartDateTendency>
    </el-card>
    <el-card class="mt-3">
      <slot name="table-header"></slot>
      <vxe-grid :cell-style="cellStyle" :header-cell-style="headerCellStyle" v-bind="gridOptions" v-on="gridEvents" :row-style="rowStyle">
        <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>
: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;
}

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