<template>
    <view class="relative px-[30rpx] pt-[30rpx] pb-[10rpx]" v-show="drawModel.is_open * 1">
        <view class="flex bg-page-base rounded-lg" style="border: 1px solid #ffffff">
            <scroll-view
                class="whitespace-nowrap w-[540rpx] px-3"
                :scroll-x="true"
                scroll-with-animation
                id="scroll-view"
                :scroll-left="scrollLeft"
            >
                <block v-for="(item, index) in drawModel.modelList" :key="item.id">
                    <view
                        class="tabs-item _tabs-query px-[10px] py-[16px]"
                        :class="{
                            'tabs-item__active': item.key == drawModel.current.key
                        }"
                        @click="handleClick(index)"
                    >
                        {{ item.alias }}
                    </view>
                </block>
            </scroll-view>
            <view
                class="inline-flex justify-center items-center w-[160rpx]"
                style="box-shadow: -3px 0 6px #0000000f"
                @click="toggleMore"
            >
                <span class="text-sm">更多</span>
            </view>
        </view>
        <template v-if="isUnfold">
            <view class="draw-tabs__mask" @click="toggleMore"></view>
            <view class="draw-tabs p-[30rpx]" @click="toggleMore">
                <view class="bg-white rounded-lg flex flex-wrap">
                    <view
                        v-for="(item, index) in drawModel.modelList"
                        :key="item.id"
                        class="tabs-item inline-block px-[10px] py-[16px] hover:bg-page-base rounded-lg text-center w-1/2"
                        :class="{
                            'tabs-item__active': item.key == drawModel.current.key
                        }"
                        @click="handleClick(index)"
                    >
                        {{ item.alias }}
                    </view>
                </view>
            </view>
        </template>
    </view>
</template>
<script setup lang="ts">
import { onMounted, nextTick, reactive, ref, watch, getCurrentInstance } from 'vue'
import { drawingModel } from '@/api/drawing'
import { useUserStore } from '@/stores/user'
import { getRect } from '@/utils/util'

const emit = defineEmits<{
    (event: 'update:modelValue', value: string): void
    (event: 'update:balance', value: string): void
}>()
const props = withDefaults(
    defineProps<{
        balance?: any
        modelValue?: any
    }>(),
    {
        balance: 0,
        modelValue: ''
    }
)

const userStore = useUserStore()

const isUnfold = ref(false)
const scrollLeft = ref(0)

// 绘画模型
interface DrawingModel {
    is_open: number
    current: {
        balance: number
        name: string
        model: string
    }
    modelList: Array<{
        id: number
        name: string
        model: string
        balance: number
        default?: boolean
    }>
}
const drawModel: DrawingModel = reactive({
    is_open: 0,
    current: {
        balance: 1,
        name: '',
        model: ''
    },
    modelList: []
})

// scroll-view 数据
let scrollViewWidth = 0
let scrollViewLeft = 0
let scrollViewChildrenInfo: Array<{ left: number; width: number }> = []
//@ts-ignore
const ctx = getCurrentInstance()

// 获取绘画模型数据
const getDrawModel = async () => {
    try {
        const { billing_is_open, list: data } = await drawingModel()
        drawModel.is_open = billing_is_open
        drawModel.modelList = data
        const current = data.find((item) => item.default) || data[0]
        drawModel.current = current

        // 获取滚动尺寸信息
        await getScrollView()

        emit('update:balance', current.balance)
        emit('update:modelValue', current.key)
    } catch (error) {
        console.error('获取绘画模型失败:', error)
        // 可以在这里添加更多的错误处理逻辑，比如用户提示
    }
}

const handleClick = async (index: number) => {
    // 等待反应时间，否则在v-show切换时scroll-view的scroll-left值时滚动会不生效
    await nextTick()
    // 操作数据
    drawModel.current = drawModel.modelList[index]

    //@ts-ignore
    emit('update:balance', drawModel.current.balance)
    emit('update:modelValue', drawModel.current.key)

    // 滚动到指定位置
    const tabInfo = scrollViewChildrenInfo[index]
    const offsetLeft = tabInfo.left - scrollViewLeft
    const left = offsetLeft - (scrollViewWidth - tabInfo.width) / 2
    // 不能负
    scrollLeft.value = left < 0 ? 0 : left
}

const getScrollView = async () => {
    await nextTick()
    // 获取父元素尺寸信息
    const { width, left }: any = await getRect('#scroll-view', false, ctx)
    scrollViewWidth = width
    scrollViewLeft = left

    //@ts-ignore
    scrollViewChildrenInfo = await getRect('._tabs-query', true, ctx)
}

watch(
    () => props.modelValue,
    (value) => {
        const index = drawModel.modelList.findIndex((item: any) => {
            return item.key === value
        })
        handleClick(index == -1 ? 0 : index)
    },
    { immediate: false }
)

watch(
    () => userStore.userInfo.drawLimit,
    async () => {
        await getDrawModel()
    }
)

onMounted(async () => {
    await getDrawModel()
})

defineExpose({
    getDrawModel
})

const toggleMore = () => {
    isUnfold.value = !isUnfold.value
}
</script>

<style lang="scss" scoped>
.tabs-item {
    display: inline-block;
    position: relative;
    font-size: 30rpx;
}
.tabs-item__active {
    color: #101010;
    font-weight: 500;
    &::after {
        content: '';
        position: absolute;
        transform: translateX(-50%);
        left: 50%;
        width: 30%;
        height: 3px;
        bottom: 14rpx;
        border-radius: 3px;
        background-color: var(--color-primary);
    }
}
.draw-tabs__mask {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 9;
}
.draw-tabs {
    position: absolute;
    top: 0;
    left: 0;
    box-sizing: border-box;
    width: 100%;
    z-index: 999;
}
</style>
