<template>
  <div class="relative brand-list fn-flex fn-flex-column" style="height: 100%;">
    <div class="home-search ulib-r750 overflowhidden inner5 mt30 ml30 mr30 mb20" style="border:1px solid var(--van-button-danger-background)">
      <div class="fn-flex fn-flex-center">
        <div class="fn-flex-item pl20"><van-field v-model="keywords" label="" placeholder="请输入您想要的车型" style="padding:0" /></div>
        <div><van-button style="width:16vw;" type="danger" round size="small" @click="onSearch">搜索</van-button></div>
      </div>
    </div>
    <div v-if="0" class="absolute font-26 right-0 mr30 fn-flex fn-flex-center"><span>只看</span><span class="mr10" :style="'color:'+active_color">新能源</span><van-switch v-model="is_only_new" :active-color="active_color" inactive-color="#dcdee0" size="18px"/></div>
    <div class="fn-flex-item relative">
      <div class="absolute scroll-y" style="width: 100%;height:100%;left:0;top:0;">
        <van-index-bar :sticky="isSticky" ref="indexbar">
          <template v-for="(it,idx) in list" :key="idx">
            <van-index-anchor :index="idx" />
            <van-cell v-for="(item,index) in it" :key="index" @click="handleClickItem(item)">
              <template #title>
                <div :ref="'indexitem_'+idx+'_'+index" class="fn-flex fn-flex-center">
                  <van-image class="mr10" :src="item.logo" width="20" height="20" />
                  <span class="font-26">{{item.name}}</span>
                </div>
              </template>
              <template #value>
                <van-tag v-if="0" color="#fff4f4" text-color="#f84803" round >至高2万补贴<van-icon name="play" /></van-tag>
              </template>
            </van-cell>
          </template>
        </van-index-bar>
      </div>
    </div>
    
  </div>
</template>

<script>
import api from '@/utils/api.js';
import { useBrandStore } from '@/stores/brand';
import { showToast } from 'vant'
export default {
 name: 'BrandList',
 props: {
 },
 data() {
   return {
    list: [],
     keywords: '', // 搜索关键词
     is_only_new:false,
     active_color: '#79ccb9', // 选中颜色
     isSticky: true,
   }
 },
 mounted() {
   this.fetchCarBrands();
 },
 methods: {
  handleClickItem(item){
    this.$emit('brandItem',item) // 触发父组件的点击事件，并传递当前项作为参数
  },
  onSearch() { // 搜索事件处理
    console.log('搜索内容：', this.keywords,this.list.length)
    if (!this.keywords.trim()) {
      return;
    }
    
    // 在list中查找匹配的品牌
    let targetGroupIndex = -1;
    let targetItemIndex = -1;
    
    // for (let groupIndex = 0; groupIndex < this.list.length; groupIndex++) {
    for(let groupIndex in this.list){
      const group = this.list[groupIndex];
      console.log(groupIndex,group)

      for (let itemIndex = 0; itemIndex < group.length; itemIndex++) {
        const item = group[itemIndex];
        if (item.name && item.name.includes(this.keywords.trim())) {
          targetGroupIndex = groupIndex;
          targetItemIndex = itemIndex;
          break;
        }
      }
      if (targetGroupIndex !== -1) break;
    }
    
    // 如果找到匹配的品牌，滚动到对应位置
    if (targetGroupIndex !== -1) {
      console.log(targetGroupIndex,targetItemIndex)
      this.$nextTick(() => {
        // 使用van-index-bar的scrollTo方法滚动到指定索引
        const indexBar = this.$el.querySelector('.van-index-bar');
        if (indexBar && indexBar.__vue__) {
          indexBar.__vue__.scrollTo(targetGroupIndex);
        } else {
          // 备用方案：直接滚动到对应的锚点
          const anchor = this.$refs.indexbar;
          console.log(anchor)

          if (anchor) {
            anchor.scrollTo(targetGroupIndex);
          }
          // const anchor = this.$refs['indexitem_'+targetGroupIndex+'_'+targetItemIndex];
          // if (anchor) {
          //   if (anchor && typeof anchor.scrollIntoView === 'function') {
          //     anchor.scrollIntoView({ behavior: 'smooth', block: 'start' });
          //   }
          // }
        }
      });
    } else {
      // 没有找到匹配的品牌
      showToast('未找到匹配的品牌');
    }
  },
  async fetchCarBrands() {
    const brandStore = useBrandStore();
    // 检查store中是否已有数据
    if (brandStore.list && Object.keys(brandStore.list).length > 0) {
      this.list = brandStore.list;
      return brandStore.list;
    }
    
    // 没有缓存数据时请求接口
    try {
      const { data } = await api.get('/auto/car/brand');
      if (data) {
        this.list = data;
        // 将数据存储到store中
        brandStore.setList(data);
      }
      return data;
    } catch (error) {
      console.error('获取品牌数据失败:', error);
      return { code: 500, message: '接口请求异常' };
    }
  },
 }
}
</script>



<style lang="scss" scoped>
.brand-list {
  ::v-deep{
    .van-index-anchor--sticky{
      left: 0!important;
    }
  }
}
</style>