<script setup lang="ts">
import { inject, onBeforeUnmount, reactive, Ref, ref } from 'vue'
import { getParentAsin, getSearchedItem } from '../api'
import { Connection, Picture as IconPicture } from '@element-plus/icons-vue'
import emitter from '/@/utils/emitter'
import useAddedItem from '../hooks/useAddedItem'

const profile = <Ref>inject('profile')
const parentLoading = ref(false)
const rightLoading = ref(false)

let searchType = ''
const vxeRef = ref()
const vxeRefRight = ref()
const selectedParentAsins = ref([])
const hasMore = ref(true)
const isScrollSelectAll = ref(false)
const { parentAsinsSet } = useAddedItem()
const productLineId = ref('')
const searchResult = ref([])
let page = 1
let rightPage = 1
let limit = 15
let hasMoreParentAsin = true
let isFirstTime = true

emitter.on('PopoverFilter-noMoreParenAsin', () => {
  hasMoreParentAsin = false
})

emitter.on('PopoverFilter-productLineSelect', (data: any) => {
  productLineId.value = data.value
  gridOptions.data.splice(0)
})

emitter.on('PopoverFilter-searchResult', (data: any) => {
  gridOptions.data = data.value
  isFirstTime = false
})

emitter.on('PopoverFilter-productLineSelect', () => {
  vxeRef.value.clearAll()
  // vxeRef.value.setAllCheckboxRow(false)
  isScrollSelectAll.value = false
})

emitter.on('TopFilter', (value: any) => {
  if (value.isVisible?.value) {
    fetchParentAsin()
    searchType = value.productFilterSelect.value
    updateGridColumnField()
  } else {
    resetSelected()
  }
})

emitter.on('TopFilter-confirm', () => {
  resetSelected()
})

// 父ASIN表格配置
const gridOptions = <any>reactive({
  height: 500,
  align: null,
  columns: [
    { type: 'checkbox', width: 30 },
    { field: 'parentAsin', title: '父ASIN', slots: { default: 'parentAsin_default' } },
  ],
  data: [],
})

// 右侧表格配置
const gridOptionsRight = <any>reactive({
  height: 500,
  align: null,
  columns: [
    { type: 'checkbox', width: 30 },
    { field: 'sku', title: 'SKU', width: '350' },
    { field: 'productLineName', title: '产品线', width: '150' },
    { field: 'ordersIn_14', title: '近14天SP广告订单数', width: '180' },
    { field: 'acosIn_14', title: '近14天SP广告ACOS', width: '180' },
  ],
  data: [],
})

// 左侧单选事件
async function selectChangeEvent(table: any) {
  if (table.checked) {
    rightPage = 1 // 仅当有新的选中项时重置页码和数据
    selectedParentAsins.value.splice(0) // 移除旧的选中项
    selectedParentAsins.value.push(table.row.parentAsin)
    gridOptionsRight.data.splice(0) // 在加载新数据之前清空现有数据
    await fetchSearchedItem(selectedParentAsins.value)
    await vxeRefRight.value.setAllCheckboxRow(true)
    // const data = vxeRefRight.value.getTableData()
    getRightSelectedItem()
  } else {
    // 移除singleSelect.value中对应的parentAsin
    const index = selectedParentAsins.value.indexOf(table.row.parentAsin)
    if (index !== -1) {
      selectedParentAsins.value.splice(index, 1)
    }
    // 从gridOptionsRight.data中移除对应的项
    gridOptionsRight.data = gridOptionsRight.data.filter((item: any) => item.parentAsin !== table.row.parentAsin)
    emitter.emit('PopoverFilterTable-needDelete', table.row.parentAsin)
  }
}

// 左侧全选事件
async function selectAllChangeEvent(table: any) {
  // await vxeRef.value.clearAll()
  // console.log('多选:', table)

  if (table.checked) {
    table.records.forEach((record: any) => {
      selectedParentAsins.value.push(record.parentAsin)
      isScrollSelectAll.value = true // 是否滚动全选
    })
    await fetchSearchedItem(selectedParentAsins.value)
    await vxeRefRight.value.setAllCheckboxRow(true)
    // const data = vxeRefRight.value.getTableData()
    getRightSelectedItem()
  } else {
    // 如果全选被取消，清空右侧数据或执行其他逻辑
    selectedParentAsins.value.splice(0)
    gridOptionsRight.data.splice(0)
  }
}

// 单元格点击事件
function handleCellClick(table: any) {
  // console.log(vxeRefRight.value.getTableData().tableData)
  // console.log('parentAsinsSet', parentAsinsSet.value)
  rightPage = 1
  selectedParentAsins.value.splice(0)
  selectedParentAsins.value.push(table.row.parentAsin)
  gridOptionsRight.data.splice(0)
  fetchSearchedItem(selectedParentAsins.value).then(() => {
    // 重新加载完右侧数据后，进行勾选
    checkRightTableRows()
  })
}

// 勾选右侧表格的行
function checkRightTableRows() {
  const rightData = vxeRefRight.value.getTableData().tableData
  rightData.forEach((row: any) => {
    const concatValue = searchType === 'sku' ? row.parentAsin + row.sku : row.parentAsin + row.asin
    if (parentAsinsSet.value.has(concatValue)) {
      vxeRefRight.value.setCheckboxRow(row, true)
    }
  })
}

// 右侧表格单选事件
async function selectChangeRight(table: any) {
  if (table.checked) {
    getRightSelectedItem()
    // 查找并选中左侧表格对应的条目
    const leftRow = findParentAsin(table.row.parentAsin)
    if (leftRow) {
      await vxeRef.value.setCheckboxRow(leftRow, true)
    }
  } else {
    emitter.emit('PopoverFilterTable-needDeleteBySearchType', searchType === 'sku' ? table.row.sku : table.row.asin)
    // 查找并取消选中左侧表格对应的条目
    const leftRow = findParentAsin(table.row.parentAsin)
    if (leftRow && table.records.length === 0) {
      await vxeRef.value.setCheckboxRow(leftRow, false)
    }
  }
}

// 查找左侧表格对应的条目
function findParentAsin(tableParentAsin: string) {
  const parentAsin = tableParentAsin
  const leftTableData = vxeRef.value.getTableData().tableData
  return leftTableData.find((row: any) => row.parentAsin === parentAsin)
}

// 右侧表格全选事件
async function selectAllChangeRight(table: any) {
  if (table.checked) {
    getRightSelectedItem()
    const rightTableData = vxeRefRight.value.getTableData().tableData
    // 勾选左侧表格中对应的条目
    for (const data of rightTableData) {
      const leftRow = findLeftCorrespondItem(data)
      if (leftRow) {
        await vxeRef.value.setCheckboxRow(leftRow, true)
      }
    }
  } else {
    // console.log('table.tableData', vxeRefRight.value.getTableData().tableData[0].parentAsin)
    emitter.emit('PopoverFilterTable-needDelete', vxeRefRight.value.getTableData().tableData[0].parentAsin)
    const rightTableData = vxeRefRight.value.getTableData().tableData
    for (const data of rightTableData) {
      const leftRow = findLeftCorrespondItem(data)
      if (leftRow) {
        await vxeRef.value.setCheckboxRow(leftRow, false)
      }
    }
  }
}

function findLeftCorrespondItem(data: any) {
  const leftTableData = vxeRef.value.getTableData().tableData
  return leftTableData.find((row: any) => row.parentAsin === data.parentAsin)
}

// 获取右侧表格选中的数据
function getRightSelectedItem() {
  const selectedData = vxeRefRight.value.getCheckboxRecords()
  // console.log('selectedData', selectedData)
  emitter.emit('PopoverFilterTable-tableData', selectedData)
}

// 获取父ASIN数据
async function fetchParentAsin() {
  parentLoading.value = true
  const body = {
    profileId: profile.value.profile_id,
    page,
    limit,
  }
  try {
    const response = await getParentAsin(body)
    gridOptions.data.push(...response.data)
  } catch (error) {
    console.log('error:', error)
  } finally {
    parentLoading.value = false
  }
}

// 获取右侧表格数据
async function fetchSearchedItem(parentAsin: Array<string>) {
  rightLoading.value = true
  const body = {
    profileId: profile.value.profile_id,
    searchType: searchType,
    parentAsin,
    page: rightPage,
    limit: 8,
  }
  try {
    const response = await getSearchedItem(body)
    hasMore.value = rightPage * body.limit < response.total // 计算是否还有更多数据
    if (rightPage == 1 && response.data.length > 0) {
      gridOptionsRight.data = response.data
    } else {
      gridOptionsRight.data.push(...response.data)
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    rightLoading.value = false
  }
}

async function handleScroll(event: any) {
  const target = event.$event.target
  // 计算是否达到底部：容器高度 + 滚动顶部距离 >= 滚动内容的总高度
  if (target.scrollHeight - (target.scrollTop + target.clientHeight) < 1) {
    if (hasMoreParentAsin) {
      // 只有在还有数据时才进行加载
      page += 1
      if (productLineId.value.length > 0) {
        emitter.emit('PopoverFilterTable-sendRequest')
      } else {
        await fetchParentAsin()
      }
      if (isScrollSelectAll.value) {
        await vxeRef.value.setAllCheckboxRow(true)
      }
    } else {
      // console.log('Reached the bottom, but no more data to load.')
    }
  }
}

async function handleRightScroll(event: any) {
  const target = event.$event.target
  if (target.scrollHeight - (target.scrollTop + target.clientHeight) < 1 && hasMore.value) {
    rightPage += 1 // 准备加载下一页
    await fetchSearchedItem(selectedParentAsins.value)
    await vxeRefRight.value.setAllCheckboxRow(true)
    getRightSelectedItem()
    // const data = vxeRef.value.getTableData()
    // getRightSelectedItem(data)
  }
}

function resetSelected() {
  gridOptions.data = []
  gridOptionsRight.data = []
}

// 切换搜索类型时，更新右侧表格字段
function updateGridColumnField() {
  // 直接映射现有的columns，只修改需要改变的部分
  gridOptionsRight.columns = gridOptionsRight.columns.map((column: any) => {
    if (column.field === 'sku' || column.field === 'asin') {
      const newField = searchType === 'sku' ? 'sku' : 'asin'
      const newTitle = searchType === 'sku' ? 'SKU' : 'ASIN'
      return { ...column, field: newField, title: newTitle, slots: { default: `${newField}_default` } }
    }
    // 不需要改变的列配置直接返回
    return column
  })
}

// 更改表头样式
function changeHeaderCellStyle() {
  return {
    padding: '3px',
  }
}

onBeforeUnmount(() => {
  emitter.all.clear()
})
</script>

<template>
  <div class="flex">
    <vxe-grid
      ref="vxeRef"
      v-loading="parentLoading"
      v-bind="gridOptions"
      :header-row-style="changeHeaderCellStyle"
      :header-cell-style="changeHeaderCellStyle"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
      @cell-click="handleCellClick"
      class="ml-2 mb-2 mt-0 border border-r-0 rounded-bl-md rounded-tl-md overflow-hidden"
      style="flex: 0 1 260px; overflow: auto"
      @scroll.native="handleScroll">
      <template #parentAsin_default="{ row }">
        <div style="display: flex">
          <el-image class="w-14 h-14 mr-1 border rounded" v-if="row.Image" :src="row.Image" alt="" fit="contain" />
          <el-image v-else class="w-12 h-12 mr-1 border rounded">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture />
                </el-icon>
              </div>
            </template>
          </el-image>
          <div class="flex flex-col justify-center">
            <div class="font-medium text-black">{{ row.parentAsin }}</div>
            <div>
              ASIN:<span class="text-black">{{ row.asinNum }}</span>
              <el-link
                :href="row.amazonUrl"
                target="_blank"
                :disabled="!row.amazonUrl"
                :underline="false"
                :icon="Connection"
                :style="{ marginLeft: '2px', marginBottom: '2px', color: row.amazonUrl ? '#3a83f7' : '#c0c4cc' }">
              </el-link>
              <span class="text-gray-300 mx-1">|</span>
              SKU:<span class="text-black">{{ row.skuNum }}</span>
            </div>
          </div>
        </div>
      </template>
    </vxe-grid>
    <!-- 右侧表格 -->
    <vxe-grid
      ref="vxeRefRight"
      v-loading="rightLoading"
      v-bind="gridOptionsRight"
      :header-cell-style="changeHeaderCellStyle"
      @checkbox-all="selectAllChangeRight"
      @checkbox-change="selectChangeRight"
      class="mr-2 mb-2 mt-0 border rounded-br-md rounded-tr-md overflow-hidden w-0"
      style="flex: 2 1 0; overflow: auto"
      @scroll.native="handleRightScroll">
      <template v-if="searchType === 'sku'" #sku_default="{ row }">
        <div style="display: flex; align-items: center">
          <el-image
            class="w-14 h-14 mr-1 border rounded"
            style="min-width: 56px; min-height: 56px"
            v-if="row.Image"
            :src="row.Image"
            alt=""
            fit="contain" />
          <el-image v-else class="w-12 h-12 mr-1 border rounded">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture />
                </el-icon>
              </div>
            </template>
          </el-image>
          <div>
            <el-tooltip class="box-item" effect="dark" :content="row.Title" placement="top-start">
              <div class="font-medium text-black display-line">{{ row.Title }}</div>
            </el-tooltip>
            <div>
              <span class="text-black font-semibold">{{ row.price }}</span>
              <span class="text-gray-300 mx-1">|</span>
              <span>{{ row.quantity }}</span>
            </div>
            <el-tooltip offset="0" :show-arrow="false" effect="dark" :disabled="!row.sku" :content="row.sku" placement="top-end">
              <div class="display-line">
                ASIN:<span class="text-black">{{ row.asin }}</span>
                <el-link
                  :href="row.amazonUrl"
                  target="_blank"
                  :disabled="!row.amazonUrl"
                  :underline="false"
                  :icon="Connection"
                  :style="{ marginLeft: '2px', marginBottom: '2px', color: row.amazonUrl ? '#3a83f7' : '#c0c4cc' }">
                </el-link>
                <span class="text-gray-300 mx-1">|</span>
                SKU:<span class="text-black">{{ row.sku }}</span>
              </div>
            </el-tooltip>
          </div>
        </div>
      </template>
      <!-- 表格显示ASIN相关-->
      <template v-if="searchType === 'asin'" #asin_default="{ row }">
        <div style="display: flex; align-items: center">
          <el-image
            class="w-14 h-14 mr-1 border rounded"
            style="min-width: 56px; min-height: 56px"
            v-if="row.Image"
            :src="row.Image"
            alt=""
            fit="contain" />
          <el-image v-else class="w-12 h-12 mr-1 border rounded">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture />
                </el-icon>
              </div>
            </template>
          </el-image>
          <div>
            <el-tooltip class="box-item" effect="dark" :content="row.Title" placement="top-start">
              <div class="font-medium text-black display-line">{{ row.Title }}</div>
            </el-tooltip>
            <div>
              <span class="text-black font-semibold">{{ row.priceMin }} ~ {{ row.priceMax }}</span>
              <span class="text-gray-300 mx-1">|</span>
              <span :style="{ color: row.quantity ? '#a26bf7' : '' }">
                {{ row.quantity ? '有库存' : '无库存' }}
              </span>
            </div>
            <div class="display-line">
              ASIN:<span class="text-black">{{ row.asin }}</span>
              <el-link
                :href="row.amazonUrl"
                target="_blank"
                :disabled="!row.amazonUrl"
                :underline="false"
                :icon="Connection"
                :style="{ marginLeft: '2px', marginBottom: '2px', color: row.amazonUrl ? '#3a83f7' : '#c0c4cc' }">
              </el-link>
              <span class="text-gray-300 mx-1">|</span>
              SKU:<span class="text-black">{{ row.skuNum }}</span>
            </div>
          </div>
        </div>
      </template>
    </vxe-grid>
  </div>
</template>

<style scoped>
/* 移除默认边框 */
:deep(.vxe-table--render-default .vxe-table--border-line) {
  border: none;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 65px;
  height: 65px;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.image-slot el-icon {
  font-size: 30px;
}

/* 修改表头填充颜色 默认会有空隙 */
:deep(.vxe-table--header-wrapper.body--wrapper) {
  background-color: #eef0f7;
}

.display-line {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: var(--line-clamp);
  /* white-space: pre-wrap; */
  --line-clamp: 1;
}
</style>
