<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { inject, onBeforeUnmount, onMounted, Ref, ref } from 'vue'
import { getProductline } from '../api'
import PopoverFilterTable from './PopoverFilterTable.vue'
import emitter from '/@/utils/emitter'

// 点击复选框就会触发, 用于处理从 PopoverFilterTable 组件传来的数据
emitter.on('PopoverFilterTable-tableData', (data: any) => {
  // 过滤出 parentAsin 和 sku 都不在 parentAsinsSet 中的数据,避免重复添加
  const uniqueData = data.filter((item: any) => !parentAsinsSet.value.has(item.parentAsin + item.sku))
  // 将过滤后的数据添加到 receiveData 中
  receiveData.value.push(...uniqueData)
  // 将新添加的 parentAsin 和 sku 添加到 parentAsinsSet 中
  uniqueData.forEach((item: any) => parentAsinsSet.value.add(item.parentAsin + item.sku))
})

// 删除指定 parentAsin 的数据
emitter.on('PopoverFilterTable-needDelete', (parentAsinToDelete: string) => {
  // 遍历 receiveData,找到 parentAsin 匹配的项
  receiveData.value = receiveData.value.reduce((acc: any[], item: any) => {
    if (item.parentAsin !== parentAsinToDelete) {
      acc.push(item)
    } else {
      // 从 parentAsinsSet 中删除该 parentAsin 和 sku 的组合
      parentAsinsSet.value.delete(item.parentAsin + item.sku)
    }
    return acc
  }, [])
})

emitter.on('PopoverFilterTable-needDeleteBySku', (skuToDelete: string) => {
  // 遍历 receiveData,找到 sku 匹配的项
  receiveData.value = receiveData.value.reduce((acc: any[], item: any) => {
    if (item.sku !== skuToDelete) {
      acc.push(item)
    } else {
      // 从 parentAsinsSet 中删除该 parentAsin 和 sku 的组合
      parentAsinsSet.value.delete(item.parentAsin + item.sku)
    }
    return acc
  }, [])
})

// 在 TopFilter 组件隐藏时清空 receiveData 和 parentAsinsSet
emitter.on('TopFilter', (value: any) => {
  if (!value.isVisible) {
    resetReceiveData()
  }
})

const profile = <Ref>inject('profile')
const activeName = ref('search')
const searchInput = ref('')
const options = <any>ref([])
const textarea = ref('')
const productLineSelect = ref('')
// 用于存储从 PopoverFilterTable 组件传来的数据
const receiveData = ref([])
// 用于存储已经添加的 parentAsin,避免重复添加
const parentAsinsSet = ref(new Set<string>())

// 根据 parentAsin 对 receiveData 数据进行分组
function groupByParentAsin(receiveData: any) {
  return receiveData.reduce((acc: any, item: any) => {
    if (!acc[item.parentAsin]) {
      acc[item.parentAsin] = []
    }
    acc[item.parentAsin].push(item)
    return acc
  }, {})
}

function resetReceiveData() {
  receiveData.value = []
  parentAsinsSet.value.clear()
}

// 获取产品线数据
async function fetchProductLine() {
  try {
    const response = await getProductline({ profileId: profile.value.profile_id })
    options.value = response.data
  } catch (error) {
    console.log('error:', error)
  }
}

// 在组件挂载时获取产品线数据
onMounted(() => {
  fetchProductLine()
})

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

<template>
  <div class="flex justify-between border border-solid border-inherit rounded-md">
    <div style="flex: 2 1 0; border-right: 1px solid #e6e6e6">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="搜索" name="search">
          <div class="flex gap-1 p-2">
            <el-input
              v-model="searchInput"
              placeholder="输入产品标题/父ASIN/ASIN查询"
              :prefix-icon="Search"
              style="width: 360px" />
            <el-select v-model="productLineSelect" multiple collapse-tags>
              <el-option
                v-for="item in options"
                :key="item.productlineId"
                :label="item.productlineName"
                :value="item.productlineId" />
            </el-select>
            <el-select></el-select>
          </div>
          <PopoverFilterTable></PopoverFilterTable>
        </el-tab-pane>
        <el-tab-pane label="输入" name="input" class="w-full p-2">
          <el-input v-model="textarea" :autosize="{ minRows: 10, maxRows: 100 }" type="textarea" placeholder="Please input" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <div style="flex: 1 1 0">
      <div class="h-10 flex justify-between" style="background-color: #edf0f8">
        <div class="my-auto ml-2">已添加:</div>
        <el-button link @click="resetReceiveData" class="mr-2" style="color: #3569d6">全部删除</el-button>
      </div>
      <div class="demo-collapse">
        <el-scrollbar height="550px">
          <el-collapse v-model="activeNames">
            <el-collapse-item
              v-for="(items, parentAsin) in groupByParentAsin(receiveData)"
              :key="parentAsin"
              :title="parentAsin"
              :name="parentAsin">
              <template #title>
                <span>{{ parentAsin }}</span>
              </template>
              <div v-for="item in items" :key="item.asin">
                ASIN: {{ item.asin }}
                <br />
                SKU: {{ item.sku }}
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Tab栏 */
:deep(.el-tabs__nav-scroll) {
  overflow: hidden;
  margin-left: 10px;
}
</style>
