<template>
    <view
        class="text-base text-main pb-[20rpx]"
    >
        <view class="text-base text-main mb-2 model-label">
            选择模型
        </view>
        <view
            v-if="chatModel.billing_is_open * 1"
            class="widget-select"
            @click="chatModel.show = true"
        >
            <view class="flex-1">
                <text class="flex items-center line-clamp-1 h-[70rpx]">
                    {{ chatModel.current.alias }} /
                    <text
                        v-if="!chatModel?.current?.member_free"
                        class="flex-1 min-w-0 text-muted"
                    >
                        <template v-if="chatModel?.current?.balance">
                            <text>消耗</text>
                            <text class="text-primary">
                                {{ chatModel?.current?.balance }}
                            </text>
                            <text>条对话次数</text>
                        </template>
                        <template v-else> 免费 </template>
                    </text>
                    <text v-else class="text-muted"> 会员免费 </text>
                </text>
            </view>
            <view
                class="text-muted arrow-icon"
                :class="{
                    'arrow-icon--top': chatModel.show
                }"
            >
                <u-icon name="arrow-down" />
            </view>
        </view>
        <view
            v-else
            class="widget-select"
        >
            <view class="text-[#415058] text-base flex items-center w-full h-[70rpx]">
                <text
                    v-if="!chatModel?.current?.member_free"
                    class="text-muted"
                >
                    <template v-if="chatModel?.current?.balance">
                        <text>消耗</text>
                        <text class="text-primary">
                            {{ chatModel?.current?.balance }}
                        </text>
                        <text>条对话次数</text>
                    </template>
                    <template v-else> 免费</template>
                </text>
                <text v-else class="text-muted"> 会员免费</text>
            </view>
        </view>
    </view>
    <u-popup
        v-model="chatModel.show"
        mode="bottom"
        border-radius="14"
        :safe-area-inset-bottom="true"
        height="980rpx"
        closeable
    >
        <view class="p-[20rpx] text-xl font-bold"> 切换模型通道 </view>

        <scroll-view class="h-[890rpx] box-border" scroll-y>
            <view class="pb-[120rpx] px-[30rpx]">
                <view
                    class="model-card"
                    v-for="(item, index) in chatModel.modelList"
                    :key="item.key"
                    :class="{
                        'model-card__active': chatModel.currentIndex === index
                    }"
                    @click="chatModel.currentIndex = index"
                >
                    <view>
                        <view class="flex items-center">
                            <view class="mr-2" v-if="item.image">
                                <u-image
                                    :src="item.image"
                                    width="40rpx"
                                    height="40rpx"
                                ></u-image>
                            </view>
                            <view class="text-lg font-bold">{{
                                item.alias || item.name
                            }}</view>
                        </view>
                        <view
                            v-if="item.describe"
                            class="text-base text-muted mt-2"
                        >
                            {{ item.describe }}
                        </view>
                    </view>
                    <view class="mt-4">
                        <view
                            class="mt-[30rpx] flex items-center justify-between"
                            v-for="citem in item.model_list"
                            :key="citem.key"
                            @click="handleChoiceModel(citem)"
                        >
                            <view class="mr-[6px] flex-1 min-w-0">
                                {{ citem.alias }}
                            </view>
                            <view class="ml-[10rpx] flex items-center">
                                <view
                                    class="text-muted mr-2"
                                    :class="{
                                        '!text-primary': modelKey == citem.key
                                    }"
                                >
                                    <text v-if="!citem.member_free">
                                        <template v-if="citem.balance">
                                            <text>消耗</text>
                                            <text class="text-primary">
                                                {{ citem.balance }}
                                            </text>
                                            <text>条对话次数</text>
                                        </template>
                                        <template v-else> 免费 </template>
                                    </text>
                                    <text v-else> 会员免费 </text>
                                </view>
                                <view
                                    class="text-muted ml-1 mr-[2px]"
                                    v-if="modelKey !== citem.key"
                                >
                                    <u-image
                                        :src="IconUnSelect"
                                        width="32rpx"
                                        height="32rpx"
                                    ></u-image>
                                </view>
                                <view class="text-primary mt-[3px]" v-else>
                                    <u-icon
                                        name="checkmark-circle-fill"
                                        size="40rpx"
                                    ></u-icon>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
    </u-popup>
</template>
<script setup lang="ts">
import { getChatModelApi } from '@/api/chat'
import IconUnSelect from '@/static/images/icon/icon_unselect.png'
import { computed, reactive, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import cache from '@/utils/cache'
import { CHAT_MODEL_KEY } from '@/enums/constantEnums'
const props = defineProps<{
    modelValue: any
}>()

const emit = defineEmits<{
    (event: 'update:modelValue', value: any): void
    (event: 'update:alias', value: any): void
}>()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const modelKey = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emit('update:modelValue', value)
    }
})

// 聊天模型数据
const chatModel = reactive({
    billing_is_open: 0,
    show: false,
    current: {
        balance: 1,
        key: '',
        member_free: false,
        model: '',
        default: false
    } as any,
    currentIndex: 0,
    modelList: [] as any[]
})

// 获取聊天模型数据
const getChatModelFunc = async () => {
    try {
        const { billing_is_open, model_list: data } = await getChatModelApi()
        chatModel.billing_is_open = billing_is_open
        chatModel.modelList = data

        const cacheModel = cache.get(CHAT_MODEL_KEY)
        // modelIndexes = [0,1] 模型所在索引
        const modelIndexes = findModelIndexes(data, cacheModel)
        // 如果有缓存的就使用缓存的模型，不然就使用默认的模型
        if (Array.isArray(modelIndexes)) {
            chatModel.currentIndex = modelIndexes[0]
            chatModel.current =
                data[modelIndexes[0]].model_list[modelIndexes[1]]
        } else {
            const first = data.find((item: any) => item.default) || data[0]
            chatModel.currentIndex =
                data.findIndex((item: any) => item.default) || 0
            chatModel.current =
                first.model_list.find((item: any) => item.default) ||
                first.model_list[0]
        }
    } catch (error) {
        console.log('获取聊天模型数据错误=>', error)
    }
}
getChatModelFunc()

const findModelIndexes = (
    arr: any[],
    keyToFind: string
): [number, number] | undefined => {
    // 判断如果没有值，则返回undefined
    if (!keyToFind) {
        return undefined
    }
    for (let i = 0; i < arr.length; i++) {
        const modelList = arr[i].model_list
        for (let j = 0; j < modelList.length; j++) {
            if (modelList[j].key === keyToFind) {
                return [i, j]
            }
        }
    }
    return undefined
}

// 选择聊天模型
const handleChoiceModel = (item: any) => {
    chatModel.current = item
    chatModel.show = false
}

watch(
    () => chatModel.current,
    (value) => {
        modelKey.value = value?.key
        emit('update:alias', value?.alias)
    }
)
</script>

<style lang="scss" scoped>
.model-card {
    margin-top: 20rpx;
    padding: 30rpx;
    border-radius: 16rpx;
    border-width: 1px;
    border-style: solid;
    border-color: transparent;
    box-shadow: 0px 1px 6px 0px rgba(230, 233, 237, 1);
}

.model-label {
    position: relative;
}
.model-label::before {
    content: '*';
    color: red;
    position: absolute;
    top: 50%;
    transform: translateY(-40%);
    left: -8px;
}

.widget-select {
    border-radius: 10rpx;
    padding: 10rpx 20rpx;
    flex: 1;
    display: flex;
    align-items: center;
    position: relative;
    @apply bg-page;
    .u-input {
        :deep(.u-input__input) {
            @apply text-base;
        }
    }
    .arrow-icon {
        transition: all 0.3s;
        &--top {
            transform: rotateZ((-180deg));
        }
    }
}

.model-card__active {
    border-width: 1px;
    border-style: solid;
    @apply border-primary bg-primary-light-9;
}
</style>
