<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, ref } from 'vue'
import { getAllProduct } from '/@/views/productCenter/productList/api'
import emitter from '/@/utils/emitter'

const profile = <any>inject('profile')
const activeName = ref('search')

const searchInp = ref('')
const textarea = ref('')

const data = ref([])
const selectedData = ref([])
const activeNames = ref([])
const infiniteLoad = ref(false)
let currentPage = 1
let total = 0
let limit = 10

async function handleSearch() {
  infiniteLoad.value = true
  const query = {
    profile_id: profile.value.profile_id,
    asin: searchInp.value,
  }
  try {
    const response = await getAllProduct(query)
    data.value = response.data
  } catch (error) {
    console.log('error:', error)
  } finally {
    checkParentItems()
    infiniteLoad.value = false
  }
}

function handleKeydown(event) {
  if (event.$event.key === 'Enter') {
    handleSearch()
  }
}

function load() {
  if (currentPage * limit < total) {
    currentPage++
    fetchAllProduct()
  }
}

async function fetchAllProduct() {
  infiniteLoad.value = true
  const query = {
    profile_id: profile.value.profile_id,
    page: currentPage,
    limit: limit,
  }
  try {
    const res = await getAllProduct(query)
    if (res && res.data) {
      // 转换数据并更新data, 如果不是第一页的数据就追加, 否则替换
      const newData = res.data
      if (currentPage > 1) {
        data.value.push(...newData)
      } else {
        data.value = newData
      }
      total = res.total
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    infiniteLoad.value = false
    checkParentItems()
    activeNames.value = data.value.map((_, index) => String(index))
  }
}

// 当选中或取消选中父级复选框时
function checkAll(parent, checked) {
  parent.childAsin.forEach((child) => {
    child.checked = checked
  })
}

// 当选中或取消选中单个子项复选框时
function checkSingle(parent) {
  const allChecked = parent.childAsin.every((child) => child.checked)
  parent.checked = allChecked
}

// 添加所有选中的项
function getSelectedItems() {
  const selectedItems = []
  data.value.forEach((parentItem) => {
    if (parentItem.checked) {
      // 如果父项被选中，添加父项的值，并包含所有子项的完整数据
      const children = parentItem.childAsin.map((childItem) => {
        return { ...childItem } // 复制整个childItem对象
      })
      selectedItems.push({ parentAsin: parentItem.parentAsin, childAsin: children, num: parentItem.num })
    } else {
      // 如果父项未被选中，仅添加被选中的子项的完整数据
      const selectedChildren = parentItem.childAsin
        .filter((childItem) => childItem.checked)
        .map((childItem) => {
          return { ...childItem } // 复制整个childItem对象
        })
      if (selectedChildren.length > 0) {
        selectedItems.push({ parentAsin: parentItem.parentAsin, childAsin: selectedChildren, num: selectedChildren.length })
      }
    }
  })
  return selectedItems
}

function handleSelectedItems() {
  const newSelectedItems = getSelectedItems().map((item) => ({
    ...item,
    checked: false, // 取消父项勾选状态
    num: item.childAsin.length, // 更新子项数量
    childAsin: item.childAsin.map((child) => ({ ...child, checked: false })), // 取消子项勾选状态
  }))

  newSelectedItems.forEach((newItem) => {
    const existingItemIndex = selectedData.value.findIndex((item) => item.parentAsin === newItem.parentAsin)
    if (existingItemIndex !== -1) {
      // 已存在的子项
      const existingChildren = selectedData.value[existingItemIndex].childAsin

      // 新的子项，确保不重复
      const newChildren = newItem.childAsin
      const updatedChildren = existingChildren.slice() // 创建现有子项的副本

      // 添加新的子项，如果它们不存在于现有子项中
      newChildren.forEach((newChild) => {
        if (!updatedChildren.some((child) => child.Asin === newChild.Asin)) {
          updatedChildren.push(newChild)
        }
      })

      // 更新现有项的子项和子项数量
      selectedData.value[existingItemIndex].childAsin = updatedChildren
      selectedData.value[existingItemIndex].num = updatedChildren.length
    } else {
      // 如果不存在相同的父Asin，则添加新项
      selectedData.value.push(newItem)
    }
  })

  clearShowListSelections()
  updateAsinList()
}

// 清除左侧list的选中状态
function clearShowListSelections() {
  data.value.forEach((parentItem) => {
    parentItem.checked = false // 取消父项的选中状态
    parentItem.childAsin.forEach((childItem) => {
      childItem.checked = false // 取消子项的选中状态
    })
  })
}

// 清除已添加的选中状态
function clearAddedSelections() {
  selectedData.value.forEach((parentItem) => {
    parentItem.checked = false
    parentItem.childAsin.forEach((childItem) => {
      childItem.checked = false
    })
  })
}

// 更新asinList并发射事件
function updateAsinList() {
  const asinList = selectedData.value.map((item) => ({
    parentAsin: item.parentAsin,
    childAsin: item.childAsin.map((child) => ({
      Asin: child.Asin,
      Image: child.Image,
      Title: child.Title,
    })),
  }))
  emitter.emit('ProductList-asinList', asinList)
}

function removeAllItems() {
  selectedData.value.splice(0)
}

function removeSelectedItems() {
  selectedData.value = selectedData.value.filter((parentItem) => {
    parentItem.childAsin = parentItem.childAsin.filter((childItem) => !childItem.checked)
    return parentItem.childAsin.length > 0 // 仅保留有子项的父项
  })

  // 重置剩余的所有项的勾选状态
  clearAddedSelections()
}

function checkParentItems() {
  data.value.forEach((parentItem) => {
    // 检查是否每个子项的isExist都为true
    const allExist = parentItem.childAsin.every((child) => child.isExist)
    parentItem.allChildrenExist = allExist // 新增属性，用于控制父Asin的checkbox是否禁用
  })
}

// 判断是否有选中的项 给模板提供用来判断是否显示删除已选中的按钮
const hasSelectedItems = computed(() => {
  return selectedData.value.some((parentItem) => {
    return parentItem.childAsin.some((childItem) => childItem.checked)
  })
})

// 计算有多少已添加的项
const addedItem = computed(() => {
  let totalChildItems = 0

  // 遍历每个父项的childAsin数组，并累加长度
  selectedData.value.forEach((parentItem) => {
    totalChildItems += parentItem.childAsin.length
  })
  return totalChildItems
})

emitter.on('ProductLineDialog-sendDetailData', (value: any) => {
  selectedData.value = value.data
})

emitter.on('ProductLineDialog-reloading', (value: any) => {
  if (value.reloading) {
    data.value.splice(0)
    currentPage = 1
    fetchAllProduct()
    removeAllItems()
    emitter.emit('ProductList-updateCardData', { isUpdate: true })
  }
})

onMounted(() => {
  fetchAllProduct()
  emitter.on('ProductLineDialog-closeDialog', (value: any) => {
    if (value.clear === true) {
      removeAllItems()
    }
  })
})

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

<template>
  <div class="product-select">
    <div class="left-part" v-loading="infiniteLoad">
      <el-tabs v-model="activeName">
        <el-tab-pane label="搜索" name="search">
          <div class="product-search">
            <vxe-input
              v-model="searchInp"
              @search-click="handleSearch"
              @keydown="handleKeydown"
              placeholder="请输入商品名称"
              type="search"
              class="search-input" />
          </div>
          <div class="padding-0-10">
            <div class="list-bar">
              <span class="padding-0-10">商品列表</span>
              <vxe-button class="custom-vxe-btn" type="text" content="添加" icon="vxe-icon-add" @click="handleSelectedItems" />
            </div>
          </div>
          <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
            <div>
              <el-collapse v-model="activeNames" class="padding-0-10 border-none">
                <el-collapse-item v-for="(item, index) in data" :key="item.parentAsin" :name="String(index)">
                  <template #title>
                    <el-checkbox v-model="item.checked" @click.stop="" @change="checkAll(item, item.checked)" :disabled="item.allChildrenExist">
                      {{ item.parentAsin }}
                    </el-checkbox>
                    <!-- <p style="margin-left: 10px">111---{{ item.allChildrenExist }}</p> -->
                    <el-tag style="margin-left: 8px" effect="plain" size="small" round
                      >{{ item.num }}
                      <span v-if="item.num == '1'">ASIN</span>
                      <span v-else>ASINs</span>
                    </el-tag>
                  </template>
                  <ul class="list-container">
                    <li v-for="child in item.childAsin" :key="child.asin">
                      <div class="list-content">
                        <el-checkbox v-if="child.isExist == false" v-model="child.checked" @change="checkSingle(item)" />

                        <img :src="child.Image" class="image-item" />
                        <div>
                          <el-tooltip effect="dark" :content="child.Title" placement="top-start">
                            <span class="list-item-title">{{ child.Title }}</span>
                          </el-tooltip>
                          <div>
                            <span class="item-font">${{ child.Price ? child.Price : '--' }}</span>
                            | <span class="item-quantity">{{ child.Quantity ? '有库存' : '缺货' }}</span>
                          </div>
                          <div>
                            <span class="item-asin">ASIN:</span> {{ child.Asin }}
                            <span v-if="child.isExist" class="exist-item">此商品已存在</span>
                          </div>
                        </div>
                      </div>
                    </li>
                  </ul>
                </el-collapse-item>
              </el-collapse>
            </div>
          </ul>
        </el-tab-pane>
        <el-tab-pane label="输入" name="input">
          <div class="textarea-part">
            <el-input
              disabled="true"
              v-model="textarea"
              style="width: 100%"
              :rows="15"
              type="textarea"
              placeholder="请输入ASIN, 多个ASIN使用逗号、空格或换行符分隔" />
            <div class="custom-button">
              <el-button :disabled="!textarea" type="primary" text bg>添加</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="right-part">
      <div>
        <div class="right-top-part">
          <span>已添加: {{ addedItem }}</span>
          <span>
            <vxe-button
              v-if="hasSelectedItems"
              type="text"
              status="warning"
              content="删除选中项"
              icon="vxe-icon-delete"
              @click="removeSelectedItems"></vxe-button>
            <vxe-button type="text" status="danger" content="删除所有" icon="vxe-icon-delete" @click="removeAllItems"></vxe-button>
          </span>
        </div>
        <el-scrollbar height="540px">
          <el-collapse v-model="activeNames" class="padding-0-10 border-none">
            <el-collapse-item v-for="(item, index) in selectedData" :key="item.parentAsin" :name="String(index)">
              <template #title>
                <el-checkbox v-model="item.checked" @click.stop="" @change="checkAll(item, item.checked)">{{ item.parentAsin }}</el-checkbox>
                <el-tag style="margin-left: 8px" effect="plain" size="small" round>{{ item.childAsin.length }}ASIN</el-tag>
              </template>
              <ul class="list-container">
                <li v-for="child in item.childAsin" :key="child.asin">
                  <div class="list-content">
                    <el-checkbox v-model="child.checked" @change="checkSingle(item)"></el-checkbox>
                    <img :src="child.Image" class="image-item" />
                    <div>
                      <el-tooltip effect="dark" :content="child.Title" placement="top-start">
                        <span class="list-item-title">{{ child.Title }}</span>
                      </el-tooltip>
                      <div>
                        <span class="item-font">${{ child.Price ? child.Price : '--' }}</span>
                        | <span class="item-quantity">{{ child.Quantity ? '有库存' : '缺货' }}</span>
                      </div>
                      <div><span class="item-asin">ASIN:</span> {{ child.Asin }}</div>
                    </div>
                  </div>
                </li>
              </ul>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<style scoped>
.product-select {
  display: flex;
  border: 1px solid #dde0eb;
  border-radius: 4px;
  color: #4e5969;
}
.left-part {
  width: 50%;
  border-right: 1px solid #e5e7ec;
}
.right-part {
  width: 50%;
}
.right-top-part {
  height: 40px;
  padding: 0 10px;
  border-top-right-radius: 4px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.infinite-list {
  height: 458px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}
.list-item-title {
  font-weight: 500;
  color: #1d2129;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: var(--line-clamp);
  white-space: pre-wrap;
  --line-clamp: 1;
}
/* Tab栏 */
::v-deep(.el-tabs__nav-scroll) {
  overflow: hidden;
  margin-left: 10px;
}
::v-deep(.el-table__inner-wrapper::before) {
  background-color: white;
}
.search-input {
  width: 100%;
  margin: 10px 0;
}
.list-content {
  display: flex;
  align-items: center;
  /* margin-bottom: 10px; */
}
.image-item {
  width: 50px;
  height: 50px;
  margin: 0 5px;
}
.list-bar {
  width: 100%;
  height: 30px;
  background-color: #f5f5f5;
  position: relative;
}
.list-container {
  padding-left: 20px;
}
.padding-0-10 {
  padding: 0 10px;
}
.item-asin {
  color: #6b7785;
}
.item-font {
  font-weight: 600;
}
.item-quantity {
  color: #6b7785;
}
/* 折叠面板底部间距 */
::v-deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
.textarea-part {
  padding: 15px 20px;
}
.custom-button {
  display: flex;
  flex-direction: row-reverse;
}
.exist-item {
  margin-left: 20px;
  color: #86909c;
  font-weight: 700;
}
.custom-vxe-btn {
  position: absolute;
  margin: 3px;
  right: 0;
  color: #3c59b0;
}
.product-search {
  margin: 0 10px;
}
.border-none {
  border: none;
}
:deep(.el-collapse-item:last-child .el-collapse-item__wrap) {
  border-bottom: none;
}
</style>
