<script setup lang="ts">
import { inject, reactive, ref, watch } from 'vue'
import DataTableCell from './DataTableCell.vue'
import DataTableCellFooter from './DataTableCellFooter.vue'
import emitter from '/@/utils/emitter'
import {
  getTableDataForASIN,
  getTableDataForParentASIN,
  getTableDataForProductLine,
  getTableDataForSKU,
} from '/@/views/productCenter/productList/api'
import useProductlineId from '/@/views/productCenter/productList/hooks/useProductlineId'
import useTableColumns from '/@/views/productCenter/productList/hooks/useTableColumns'
import { asinColumns, parentAsinColumns, productLineColumns, skuColumns } from '/@/views/productCenter/productList/utils/columns'

const profile = <any>inject('profile')
const dateRange = <any>inject('dateRange')
const activeButton = <any>inject('activeButton')

const searchItem = ref('')
emitter.on('TopFilters-searchItem', (value: any) => {
  searchItem.value = value.searchItem
})

const isCompare = ref(true)
const tableLoading = ref(false)

const { productlineId } = useProductlineId()
const { totalSummary, summaryFormats } = useTableColumns()

const dynamicCols = ref([])

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

const gridOptions = reactive({
  height: 'auto',
  border: false,
  round: true,
  showFooter: true,

  columnConfig: {
    resizable: true,
  },
  toolbarConfig: {
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  columns: [],
  data: [],

  footerMethod({ columns }) {
    // return [
    //   columns.map((column, columnIndex) => {
    //     if (columnIndex === 0) return '合计'
    //     if (summaryFormats[column.field]) return summaryFormats[column.field](totalSummary[column.field]) // 格式化后端返回的值
    //     return '-'
    //   }),
    // ]
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        } else if (totalSummary[column.field] !== undefined) {
          // 显示普通合计数据
          let totalValue = totalSummary[column.field]
          let gapField = `gap${column.field.charAt(0).toUpperCase()}${column.field.slice(1)}`
          let gapValue = totalSummary[gapField]
          return { totalValue, gapValue }
        } else {
          return '-'
        }
      }),
    ]
  },
})

async function fetchTableData(type) {
  tableLoading.value = true
  const query = {
    startDate: dateRange.value[0],
    endDate: dateRange.value[1],
    profileId: profile.value.profile_id,
    productlineId: productlineId.value,
    page: tablePage.currentPage,
    limit: tablePage.pageSize,
    searchItem: searchItem.value,
  }

  // 要用引号扩住key '产品线', 不扩也行 会自动转义
  const typeToApiAndColumns = {
    '产品线': { api: getTableDataForProductLine, columns: productLineColumns },
    '父ASIN': { api: getTableDataForParentASIN, columns: parentAsinColumns },
    'ASIN': { api: getTableDataForASIN, columns: asinColumns },
    'SKU': { api: getTableDataForSKU, columns: skuColumns },
  }
  // 根据类型获取对应的API函数和列配置
  const { api: apiFunction, columns } = typeToApiAndColumns[type] || {}

  // 确保apiFunction和columns都存在，否则直接返回
  if (!apiFunction || !columns) return

  // 若返回的数据没有对应的 列字段, 则会进入catch导致页面不更新
  try {
    const response = await apiFunction(query)
    Object.keys(summaryFormats).forEach((field) => {
      totalSummary[field] = response.data.sum[0][field]
    })
    tablePage.total = response.total
    gridOptions.data = response.data.list
    gridOptions.columns = columns
    dynamicCols.value = columns
  } catch (error) {
    console.log('error:', error)
  } finally {
    tableLoading.value = false
  }
}

// 监听tablePage变化，重新获取数据
function handlePageChange({ currentPage, pageSize }) {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  fetchTableData(activeButton.value)
}

// 监听activeButton, productlineId, dateRange, searchItem变化，重新获取数据
watch([activeButton, productlineId, dateRange, searchItem], async () => {
  tablePage.currentPage = 1
  isCompare.value = true
  await fetchTableData(activeButton.value)
})
</script>

<template>
  <div style="overflow: hidden; width: 100%; height: 800px" v-loading="tableLoading">
    <vxe-grid v-bind="gridOptions">
      <template #toolbar_buttons>
        <span>
          数据对比
          <vxe-switch v-model="isCompare" size="mini" />
        </span>
      </template>
      <template v-for="col in dynamicCols" #[`${col.field}_default`]="{ row }">
        <DataTableCell :value="row[col.field]" :field="col.field" :row="row" :isCompare="isCompare" />
      </template>
      <template v-for="col in dynamicCols" #[`${col.field}_footer`]="{ items, _columnIndex }">
        <DataTableCellFooter
          :totalValue="items[_columnIndex].totalValue"
          :gapValue="items[_columnIndex].gapValue"
          :isCompare="isCompare"
          :columnIndex="_columnIndex" />
      </template>
      <template #pager>
        <vxe-pager
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :total="tablePage.total"
          @page-change="handlePageChange">
        </vxe-pager>
      </template>
    </vxe-grid>
  </div>
</template>

<style scoped></style>
