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

const profile = <Ref>inject('profile')
const activeName = ref('search')
const options = ref<{ productlineId: number; productlineName: string }[]>([])
const textarea = ref('')
const activeNames = ref([])
const { receiveData, groupByParentAsin, resetReceiveData } = useAddedItem()

const productLineSelect = ref([])
const searchInput = ref('')
const searchResult = ref([])
const searchLoading = ref(false)
let page = 1
let limit = 8

// 监听选项变化, 发送请求
emitter.on('PopoverFilterTable-sendRequest', () => {
  fetchSearchResult()
})

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

// 获取搜索后的结果
async function fetchSearchResult() {
  if (searchLoading.value) {
    return // 如果已经在加载中，则不再发起新的加载
  }
  searchLoading.value = true
  const body = {
    profileId: profile.value.profile_id,
    page: page,
    limit: limit,
    productLineId: productLineSelect.value,
    searchItem: searchInput.value,
  }

  try {
    const response = await getSearchResult(body)
    const newData = response.data
    if (newData.length > 0) {
      searchResult.value.push(...newData)
      page += 1
    } else {
      emitter.emit('PopoverFilter-noMoreParenAsin')
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    searchLoading.value = false
  }
}

function handleSelectChange() {
  resetSearchResult()
  emitter.emit('PopoverFilter-productLineSelect', productLineSelect)
  fetchSearchResult()
}

function searchInputBlur() {
  resetSearchResult()
  fetchSearchResult()
}

function resetSearchResult() {
  page = 1
  searchResult.value = []
}

watch(
  searchResult,
  () => {
    emitter.emit('PopoverFilter-searchResult', searchResult)
  },
  { deep: true }
)

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" v-loading="searchLoading">
      <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"
              @blur="searchInputBlur"
              placeholder="输入产品标题/父ASIN/ASIN查询"
              :prefix-icon="Search"
              style="width: 360px" />
            <el-select v-model="productLineSelect" @change="handleSelectChange" 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 px-1.5">
        <el-scrollbar height="550px">
          <el-collapse v-model="activeNames" style="border: none">
            <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">
                <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="item.Image"
                    :src="item.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="item.Title" placement="top-start">
                      <div class="font-medium text-black display-line">{{ item.Title }}</div>
                    </el-tooltip>
                    <div>
                      <span class="text-black font-semibold">{{ item.price }}</span>
                      <span class="text-gray-300 mx-1">|</span>
                      <span>{{ item.quantity }}</span>
                    </div>
                    <el-tooltip
                      offset="0"
                      :show-arrow="false"
                      effect="dark"
                      :disabled="!item.sku"
                      :content="item.sku"
                      placement="top-end">
                      <div class="display-line">
                        ASIN:<span class="text-black">{{ item.asin }}</span>
                        <el-link
                          :href="item.amazonUrl"
                          target="_blank"
                          :disabled="!item.amazonUrl"
                          :underline="false"
                          :icon="Connection"
                          :style="{ marginLeft: '2px', marginBottom: '2px', color: item.amazonUrl ? '#3a83f7' : '#c0c4cc' }">
                        </el-link>
                        <span class="text-gray-300 mx-1">|</span>
                        SKU:<span class="text-black">{{ item.sku ? item.sku : item.skuNum }}</span>
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </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;
}

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

.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;
}
</style>
