<template>
    <uni-popup
        ref="popup"
        type="bottom"
        borderRadius="10px 10px 0 0"
        background-color="#FFFFFF"
        :mask-click="maskClick"
    >
        <view class="popup-content">
            <view class="popup-header">
                <view class="btn-cancel" @click="cancel">取消</view>
                <view class="title">{{ title }}</view>
                <view class="btn-confirm" @click="confirm">确认</view>
            </view>
            <view class="popup-list">
                <!-- 多选模式 -->
                <view v-if="multiSelect" class="multi-select-list">
                    <view v-if="!processedListData[0] || processedListData[0].length === 0" class="empty-tip">
                        暂无数据
                    </view>
                    <view
                        v-else
                        class="skill-tags-container"
                    >
                        <view
                            v-for="(item, index) in processedListData[0]"
                            :key="index"
                            class="skill-tag"
                            :class="{ 'skill-tag-active': selectedValues.includes(item[this.rowKey]) }"
                            @click.stop="toggleSelect(item)"
                            @touchstart.stop="toggleSelect(item)"
                        >
                            <text class="skill-tag-text">{{ getLabel(item) }}</text>
                        </view>
                    </view>
                </view>
                <!-- 单选模式 -->
                <picker-view
                    v-else
                    indicator-style="height: 84rpx;"
                    :value="selectedIndex"
                    @change="bindChange"
                    class="picker-view"
                >
                    <template v-for="(list, lsIndex) in processedListData" :key="lsIndex">
                        <picker-view-column>
                            <view
                                v-for="(item, index) in list"
                                :key="index"
                                class="item"
                                :class="{ 'item-active': selectedIndex[lsIndex] === index }"
                            >
                                <text>{{ getLabel(item) }}</text>
                                <text>{{ unit }}</text>
                            </view>
                        </picker-view-column>
                    </template>
                </picker-view>
            </view>
        </view>
    </uni-popup>
</template>

<script>
export default {
    name: 'selectPopup',
    data() {
        return {
            maskClick: false,
            title: '标题',
            confirmCallback: null,
            cancelCallback: null,
            changeCallback: null,
            listData: [],
            selectedIndex: [0, 0, 0],
            rowLabel: 'label',
            rowKey: 'value',
            selectedItems: [],
            unit: '',
            multiSelect: false,
            selectedValues: [],
        };
    },
    computed: {
        // 统一处理二维数组格式
        processedListData() {
            return this.listData.map((column) => {
                if (!Array.isArray(column)) return [];
                return column.map((item) => {
                    return typeof item === 'object' ? item : { [this.rowLabel]: item, [this.rowKey]: item };
                });
            });
        },
        // 计算选中的项目
        computedSelectedItems() {
            if (!this.multiSelect) return this.selectedItems;
            return this.processedListData[0] ? this.processedListData[0].filter(item => 
                this.selectedValues.includes(item[this.rowKey])
            ) : [];
        },
    },
    methods: {
        open(newConfig = {}) {
            const {
                title,
                success,
                cancel,
                change,
                data,
                unit = '',
                rowLabel = 'label',
                rowKey = 'value',
                maskClick = false,
                defaultIndex = [],
                multiSelect = false,
                defaultValues = [],
            } = newConfig;
            
            this.reset();
            if (title) this.title = title;
            if (typeof success === 'function') this.confirmCallback = success;
            if (typeof cancel === 'function') this.cancelCallback = cancel;
            if (typeof change === 'function') this.changeCallback = change;
            if (Array.isArray(data)) this.listData = data;

            this.rowLabel = rowLabel;
            this.rowKey = rowKey;
            this.maskClick = maskClick;
            this.unit = unit;
            this.multiSelect = multiSelect;

            if (multiSelect) {
                this.selectedValues = defaultValues || [];
            } else {
                this.selectedIndex =
                    defaultIndex.length === this.listData.length ? defaultIndex : new Array(this.listData.length).fill(0);
                this.selectedItems = this.selectedIndex.map((val, index) => this.processedListData[index][val]);
            }
            
            this.$nextTick(() => {
                this.$refs.popup.open();
            });
        },
        close() {
            this.$refs.popup.close();
        },
        bindChange(e) {
            this.selectedIndex = e.detail.value;
            this.selectedItems = this.selectedIndex.map((val, index) => this.processedListData[index][val]);
            this.changeCallback && this.changeCallback(e, this.selectedIndex, this.selectedItems);
        },
        cancel() {
            this.clickCallback(this.cancelCallback);
        },
        confirm() {
            this.clickCallback(this.confirmCallback);
        },
        getLabel(item) {
            return item?.[this.rowLabel] ?? '';
        },
        toggleSelect(item) {
            if (!item || !this.rowKey || !item[this.rowKey]) {
                return;
            }
            
            const value = item[this.rowKey];
            const index = this.selectedValues.indexOf(value);
            
            if (index > -1) {
                // 取消选中
                this.selectedValues.splice(index, 1);
            } else {
                // 选中
                this.selectedValues.push(value);
            }
        },
        setColunm(index, list) {
            if (index > this.listData.length) {
                return console.warn('最长' + this.listData.length);
            }
            if (!list.length) {
                return console.warn(list + '不能为空');
            }
            this.listData[index] = list;
            this.selectedIndex[index] = 0;
            this.selectedItems = this.selectedIndex.map((val, index) => this.processedListData[index][val]);
        },
        async clickCallback(callback) {
            if (typeof callback !== 'function') {
                this.$refs.popup.close();
                return;
            }

            try {
                let result;
                if (this.multiSelect) {
                    // 多选模式：传递 selectedValues 和 selectedItems
                    result = await callback(this.selectedValues, this.computedSelectedItems);
                } else {
                    // 单选模式：传递 selectedIndex 和 selectedItems
                    result = await callback(this.selectedIndex, this.selectedItems);
                }
                if (result !== false) {
                    this.$refs.popup.close();
                }
            } catch (error) {
                console.error('confirmCallback 执行出错:', error);
            }
        },
        reset() {
            this.maskClick = false;
            this.confirmCallback = null;
            this.cancelCallback = null;
            this.changeCallback = null;
            this.listData = [];
            this.selectedIndex = [0, 0, 0];
            this.rowLabel = 'label';
            this.rowKey = 'value';
            this.selectedItems = [];
            this.unit = '';
            this.multiSelect = false;
            this.selectedValues = [];
        },
    },
};
</script>

<style lang="scss" scoped>
.popup-content {
    color: #000000;
    height: 50vh;
}
.popup-list {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: space-evenly;
    flex: 1;
    overflow: hidden;
    .picker-view {
        width: 100%;
        height: calc(50vh - 100rpx);
        margin-top: 20rpx;
        .uni-picker-view-mask {
            background: rgba(0, 0, 0, 0);
        }
        .item {
            line-height: 84rpx;
            height: 84rpx;
            text-align: center;
            font-weight: 400;
            font-size: 32rpx;
            color: #cccccc;
        }
        .item-active {
            color: #333333;
        }
        .uni-picker-view-indicator:after {
            border-color: #e3e3e3;
        }
        .uni-picker-view-indicator:before {
            border-color: #e3e3e3;
        }
    }
    // .list {
    //     .row {
    //         font-weight: 400;
    //         font-size: 32rpx;
    //         color: #333333;
    //         line-height: 84rpx;
    //         text-align: center;
    //     }
    // }
}
.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 40rpx 10rpx 40rpx;
    .title {
        font-weight: 500;
        font-size: 36rpx;
        color: #333333;
        text-align: center;
    }
    .btn-cancel {
        font-weight: 400;
        font-size: 32rpx;
        color: #666d7f;
        line-height: 38rpx;
    }
        .btn-confirm {
            font-weight: 400;
            font-size: 32rpx;
            color: #256bfa;
        }
    }

.multi-select-list {
    padding: 20rpx 30rpx;
    max-height: calc(60vh - 120rpx);
    overflow-y: auto;
}

.empty-tip {
    text-align: center;
    padding: 60rpx 0;
    color: #999999;
    font-size: 28rpx;
}

.skill-tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    align-items: flex-start;
}

.skill-tag {
    display: inline-flex;
    align-items: center;
    padding: 12rpx 20rpx;
    border-radius: 20rpx;
    background-color: #f8f9fa;
    border: 2rpx solid #e8eaee;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 24rpx;
    color: #333333;
    white-space: nowrap;
    user-select: none;
    
    &:hover {
        background-color: #e9ecef;
        border-color: #d0d0d0;
        transform: translateY(-1rpx);
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
    
    &:active {
        transform: translateY(0);
        background-color: #dee2e6;
    }
    
    .skill-tag-text {
        font-size: 24rpx;
        color: inherit;
        line-height: 1.2;
        font-weight: 400;
    }
    
    &.skill-tag-active {
        background-color: #256bfa;
        border-color: #256bfa;
        color: #ffffff;
        box-shadow: 0 2rpx 8rpx rgba(37, 107, 250, 0.3);
        
        .skill-tag-text {
            color: #ffffff;
            font-weight: 500;
        }
        
        &:hover {
            background-color: #1e5ce6;
            border-color: #1e5ce6;
            transform: translateY(-1rpx);
            box-shadow: 0 4rpx 12rpx rgba(37, 107, 250, 0.4);
        }
    }
}
</style>
