<template>
    <u-popup :show="show" @close="hideBrandList" mode="right" class="brand_list_popup">
        <view class="brand_list_page">
            <view class="brand_list">
                <u-navbar class="nav-bar" title="品牌" :autoBack="false" :placeholder="true" v-hideNav @leftClick="hideBrandList">
                    <!-- <view class="u-nav-slot" slot="right" @click="handleAddBrand">
                        <u-icon name="plus-circle" color="#2979ff" size="20"></u-icon>
                        <text>新增</text>
                    </view> -->
                </u-navbar>
                <u-search placeholder="搜索" v-model="keyword" @custom="handleSearch" @change="handleSearch"></u-search>
                <view class="suggest_list">
                    <view class="brand_item" v-for="item in adviceList" :key="item.id" @click="handleBrandClick(item)">
                        <image class="brand_img" :src="item.imgUrl ? item.imgUrl : '/static/no-img.png'" alt=""></image>
                        <view class="brand_name">{{ item.dictLabel }}</view>
                    </view>
                </view>
            </view>
            <u-index-list :index-list="indexList" class="index_list">
                <template v-for="(item, index) in brandList">
                    <!-- #ifdef APP-NVUE -->
                    <u-index-anchor :text="indexList[index]"></u-index-anchor>
                    <!-- #endif -->
                    <u-index-item>
                        <!-- #ifndef APP-NVUE -->
                        <u-index-anchor :text="indexList[index]"></u-index-anchor>
                        <!-- #endif -->
                        <view class="list-cell" v-for="cell in item" :key="cell.dictValue" @click="handleBrandClick(cell)">
                            <image class="brand_img" :src="cell.imgUrl ? cell.imgUrl : '/static/no-img.png'" alt=""></image>
                            {{ cell.dictLabel }}
                        </view>
                    </u-index-item>
                </template>
            </u-index-list>
            <!-- <view class="no_brand">
                <u-button type="primary" :plain="true" text="找不到品牌" color="#108cff"></u-button>
            </view> -->
        </view>
    </u-popup>

</template>
<script>
import { chineseToPinYin } from '@/utils/pinyin.js'
export default {
    components: {
    },
    props: {
    },
    emits: ['selectedBrand'],
    data() {
        return {
            show: false,
            keyword: '',
            adviceList: [],
            indexList: [],
            brandList: [],
            list: [],
        }
    },
    methods: {
        handleSearch() {
            const keyword = this.keyword.trim().toLowerCase();
            if (keyword) {
                const filteredList = this.list.filter(item => {
                    const brandName = (item.dictLabel || '').toLowerCase();
                    return brandName.includes(keyword);
                });
                this.filterData(filteredList);
            } else {
                this.filterData(this.list);
            }
        },
        handleBrandClick(brand) {
            this.$emit('selectedBrand', brand)
            this.hideBrandList()
        },
        // 显示品牌列表
        showBrandList() {
            this.getList()
            this.show = true;
        },
        // 隐藏品牌列表
        hideBrandList() {
            this.show = false;
        },
        getList() {
            this.$getDicts('crm_form_brand').then(res => {
                this.filterData(res)
                this.list = res
                this.adviceList = res.filter(item => item.recommend)
            })
        },
        filterData(res){
            const processedData = this.processBrandData(res)
            this.brandList = processedData.groupedList
            this.indexList = processedData.indexList
        },
        processBrandData(data) {
            // 1. 按每个字符的拼音首字母排序
            const sortedData = data.sort((a, b) => {
                const labelA = a.dictLabel || ''
                const labelB = b.dictLabel || ''
                const maxLength = Math.max(labelA.length, labelB.length)
                
                // 逐个字符比较
                for (let i = 0; i < maxLength; i++) {
                    const charA = labelA[i] || ''
                    const charB = labelB[i] || ''
                    
                    // 检查是否为英文字符
                    const isEnglishA = /[a-zA-Z]/.test(charA)
                    const isEnglishB = /[a-zA-Z]/.test(charB)
                    
                    if (isEnglishA && isEnglishB) {
                        // 都是英文，直接比较（忽略大小写）
                        const upperA = charA.toUpperCase()
                        const upperB = charB.toUpperCase()
                        if (upperA !== upperB) {
                            return upperA.localeCompare(upperB)
                        }
                    } else if (isEnglishA) {
                        // 只有A是英文，英文排在前面
                        return -1
                    } else if (isEnglishB) {
                        // 只有B是英文，英文排在前面
                        return 1
                    } else {
                        // 都不是英文，比较拼音首字母
                        let pinyinA = ''
                        let pinyinB = ''
                        
                        try {
                            pinyinA = chineseToPinYin(charA).charAt(0).toUpperCase()
                        } catch (error) {
                            pinyinA = '#'
                        }
                        
                        try {
                            pinyinB = chineseToPinYin(charB).charAt(0).toUpperCase()
                        } catch (error) {
                            pinyinB = '#'
                        }
                        
                        if (pinyinA !== pinyinB) {
                            if (pinyinA === '#') return 1
                            if (pinyinB === '#') return -1
                            return pinyinA.localeCompare(pinyinB)
                        }
                    }
                }
                
                // 如果所有字符都相同，则按长度排序
                return labelA.length - labelB.length
            })

            // 2. 按首字母分组
            const groupedData = {}
            const indexList = []

            for (const item of sortedData) {
                let firstLetter
                const label = item.dictLabel || ''
                
                try {
                    const firstChar = label.charAt(0) || ''
                    if (/[a-zA-Z]/.test(firstChar)) {
                        // 英文直接使用大写
                        firstLetter = firstChar.toUpperCase()
                    } else {
                        // 中文使用拼音首字母
                        const pinyin = chineseToPinYin(firstChar)
                        if (pinyin && pinyin.length > 0 && /[a-zA-Z]/.test(pinyin.charAt(0))) {
                            firstLetter = pinyin.charAt(0).toUpperCase()
                        } else {
                            firstLetter = '#'
                        }
                    }
                } catch (error) {
                    firstLetter = '#'
                }

                // 创建字母分组
                if (!groupedData[firstLetter]) {
                    groupedData[firstLetter] = []
                    indexList.push(firstLetter)
                }
                groupedData[firstLetter].push(item)
            }

            // 3. 按字母顺序排序索引列表
            indexList.sort((a, b) => {
                if (a === '#') return 1
                if (b === '#') return -1
                return a.localeCompare(b)
            })

            // 4. 将分组数据转换为数组格式
            const groupedList = indexList.map(letter => groupedData[letter])
            return {
                groupedList,
                indexList
            }
        },
    }
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>