<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { getProduct, getProductLineSelect } from '../api'
import useInfiniteScroll from '../hooks/useInfiniteScroll'
import useSelectItem from '../hooks/useSelectItem'
import emitter from '/@/utils/emitter'

const profile = <any>inject('profile')
const { allData, parentloading, currentPage, load, fetchProduct } = useInfiniteScroll()
const {
  visible,
  skuData,
  asinData,
  selectedIndex,
  selectedAsinIndex,
  selectedSkuIndex,
  selectPaAsin,
  selectAsin,
  selectSku,
  clickParentAsinBtn,
  clickAsinBtn,
} = useSelectItem()

const searchInp = ref('')
const filterSelect = ref('vague')

const productSelect = ref('ALL')
const options = ref([])

async function fetchProductLine() {
  try {
    const resp = await getProductLineSelect({ profileId: profile.value.profile_id })
    options.value = resp.data
    productSelect.value = options.value[0].productlineId
  } catch (error) {
    console.log('error:', error)
  }
}

async function handleChange() {
  parentloading.value = true
  const encodedSearchItem = encodeURIComponent(searchInp.value)
  const query = {
    profileId: profile.value.profile_id,
    productlineId: productSelect.value,
    searchItem: encodedSearchItem,
  }
  if (encodedSearchItem) {
    const res = await getProduct(query)
    allData.value = res.data
    emitter.emit('ExchangeProduct-allData', allData) // 让useSelectItem()中的allData得到正确更新, 否则无法正确选择parentAsin
  }
  parentloading.value = false
}

function searchClick() {
  console.log(123)
}

function resetProductList() {
  currentPage.value = 1
  fetchProduct()
  asinData.value = []
  skuData.value = []
  selectedIndex.value = -1
}

// 监听搜索框的变化并对搜索框的值编码
watch(searchInp, (newValue) => {
  const encodedSearchItem = encodeURIComponent(newValue)
  emitter.emit('ExchangeProduct-searchInp', encodedSearchItem)
  if (newValue === '') {
    resetProductList()
  }
})

// 若产品选择改变则 重置分页并清空其他的数据
watch(
  productSelect,
  (value) => {
    emitter.emit('ExchangeProduct-productSelect', value)
    resetProductList()
  },
  { immediate: true }
)

onMounted(() => {
  fetchProductLine()
})

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

<template>
  <el-popover placement="bottom-start" :width="1000" :visible="visible">
    <template #reference>
      <span class="exchange-btn" @click="visible = true">
        <el-icon><Switch /></el-icon>
        切换商品
      </span>
    </template>
    <div class="custom-top">
      <div class="exchange-popover__title">切换商品</div>
      <el-icon @click="visible = false" style="cursor: pointer"><CloseBold /></el-icon>
    </div>
    <div class="filter-bar">
      <el-input v-model="searchInp" @change="handleChange" clearable placeholder="请输入标题/父ASIN/ASIN/SKU查询商品" style="max-width: 600px">
        <template #prepend>
          <el-select v-model="filterSelect" class="filter-bar-select">
            <el-option label="模糊" value="vague" />
            <el-option label="精确" value="accurate" />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" @click="searchClick" />
        </template>
      </el-input>
      <el-select v-if="filterSelect == 'vague'" v-model="productSelect" class="filter-select">
        <el-option v-for="item in options" :key="item.productlineId" :label="item.productlineName" :value="item.productlineId" />
      </el-select>
    </div>
    <div class="asin-selector">
      <div class="asin-selector__part" v-loading="parentloading">
        <div class="part-title">父ASIN</div>
        <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
          <li
            v-for="(item, index) in allData"
            :key="index"
            class="infinite-list-item"
            @click="selectPaAsin(index)"
            :class="{ selectedItem: index === selectedIndex }">
            <el-button color="#3c58af" size="small" class="view-btn" @click.stop="clickParentAsinBtn(index)">查看</el-button>
            <div class="list-content">
              <img :src="item.Image" class="list-item-image" />
              <div>
                <el-tooltip effect="dark" :content="item.Title" placement="top-start" :show-after="300">
                  <span class="list-item-title">{{ item.Title }}</span>
                </el-tooltip>
                <div>
                  <span class="list-item-font">${{ item.priceMin ? item.priceMin : '--' }}</span>
                  ~
                  <span class="list-item-font">${{ item.priceMax ? item.priceMax : '--' }}</span>
                </div>
                <div>
                  <span class="li-label">父ASIN:</span>
                  {{ item.parentAsin ? item.parentAsin : '--' }}
                </div>
                <div>
                  <span class="li-label">ASIN:</span>
                  {{ item.asinNumbers ? item.asinNumbers : '--' }}
                  <span class="li-label">SKU:</span>
                  {{ item.skuNumbers ? item.skuNumbers : '--' }}
                </div>
              </div>
              <div style="position: relative">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="asin-selector__part">
        <div class="part-title">ASIN</div>
        <el-scrollbar height="450px">
          <li
            v-for="(item, index) in asinData"
            :key="index"
            class="infinite-list-item"
            @click="selectAsin(index)"
            :class="{ selectedItem: index === selectedAsinIndex }">
            <div class="list-content">
              <img :src="item.Image" class="asin-list-item-image" />
              <div>
                <el-tooltip effect="dark" :content="item.Title" placement="top-start" :show-after="300">
                  <span class="list-item-title">{{ item.Title }}</span>
                </el-tooltip>
                <div>
                  <span class="list-item-font">${{ item.price ? item.price : '--' }}</span>
                  |
                  <span>FBA库存:</span>
                  <span class="list-item-font">{{ item.FBAQuantity ? item.FBAQuantity : '--' }}</span>
                </div>
                <div>
                  <span class="li-label">ASIN:</span>
                  {{ item.Asin ? item.Asin : '--' }}
                  <span class="li-label">SKU:</span>
                  {{ item.skuNumbers ? item.skuNumbers : '--' }}
                </div>
              </div>
              <div>
                <el-button color="#3c58af" size="small" class="view-btn" @click.stop="clickAsinBtn(index)">查看</el-button>
              </div>
              <div style="position: relative">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </li>
        </el-scrollbar>
      </div>
      <div class="asin-selector__part sku">
        <div class="part-title">SKU</div>
        <el-scrollbar height="450px">
          <li
            v-for="(item, index) in skuData"
            :key="index"
            class="sku-list-item"
            @click="selectSku(index)"
            :class="{ selectedItem: index === selectedSkuIndex }">
            <div>{{ item.sku ? item.sku : '--' }}</div>
          </li>
        </el-scrollbar>
      </div>
    </div>
  </el-popover>
</template>

<style scoped>
.custom-top {
  display: flex;
  justify-content: space-between;
}
.exchange-btn {
  color: #3359b5;
  font-weight: 700;
  cursor: pointer;
  width: fit-content;
}
.exchange-popover__title {
  padding-bottom: 12px;
  color: #1d2129;
  font-size: 16px;
  font-weight: 700;
}
.filter-bar {
  display: flex;
  gap: 8px;
}
.filter-bar-select {
  width: 80px;
}
.asin-selector {
  display: flex;
  align-items: stretch;
  padding-top: 12px;
  color: #1d2129;
}
.asin-selector__part {
  position: relative;
  flex-grow: 1;
  width: 40%;
  border: 1px solid #e5e6eb;
}
.asin-selector__part.sku {
  width: 20%;
}
.part-title {
  padding: 8px 4px;
  color: #6b7785;
}
.infinite-list {
  height: 450px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list-item {
  display: flex;
  height: 80px;
  border: 1px solid transparent;
  cursor: pointer;
  position: relative;
}
.infinite-list-item:hover {
  background-color: #ecf5ff;
}
.list-item-image {
  min-width: 70px;
  height: 70px;
  margin: 0 5px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}
.asin-list-item-image {
  min-width: 55px;
  height: 55px;
  margin: 0 5px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}
.list-item-title {
  color: #6b7785;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  white-space: pre-wrap;
}
.list-item-font {
  font-weight: 700;
  color: #1d2129;
}
.item-asin {
  color: #6b7785;
}
.filter-select {
  width: 300px;
}
.list-content {
  display: flex;
  align-items: center;
  /* margin-bottom: 8px; */
}
.li-label {
  color: #6b7785;
}
.selectedItem {
  border: 1px solid #409eff;
  background-color: #ecf5ff;
}
.sku-list-item {
  list-style-type: none;
  text-align: center;
  margin-bottom: 8px;
  border: 1px solid transparent;
  cursor: pointer;
  border-bottom: 1px solid #e5e6eb;
}
.view-btn {
  position: absolute;
  right: 5%;
  top: 34%;
  display: none; /* 默认隐藏按钮 */
}

.infinite-list-item:hover .view-btn {
  display: block; /* 鼠标悬浮时显示按钮 */
}
.sku-list-item:hover {
  background-color: #ecf5ff;
}
</style>
