<template>
    <z-paging ref="paging" safe-area-inset-bottom v-model="list">
        <template #top>
            <ut-navbar title="请选择/填写规格等级" :fixed="false"></ut-navbar>
            <view class="">
                <up-tabs :list="list1" @change="changeType" lineWidth="30" :current="activetab"></up-tabs>
            </view>
        </template>
        <view class="">
            <view class="pd-24 pt-0 d-flex flex-cln">
                <!-- 常用标签页 -->
                <template v-if="+activetab == 0">
                    <view v-if="commonly?.length > 0" class="pt-16 d-flex flex-wrap gap-16" style="justify-content: start">
                        <view v-for="(item, idnex) in commonly" :key="idnex" class="bg-#fff c-#333 radius-10 pd4-16-24-16-24 mb-16" @click="selectItem(item)">
                            {{ item }}
                        </view>
                    </view>
                    <template v-else>
                        <ut-empty class="mg-at mt-30" color="#ccc" size="28rpx">暂无常用规格等级</ut-empty>
                    </template>
                </template>
                <!-- 规格等级库标签页 -->
                <template v-if="+activetab == 1">
                    <view class="d-flex flex-cln" style="justify-content: start">
                        <view v-for="(item, idnexs) in ptechData" :key="idnexs">
                            <view class="pt-16 pb-16 f-s-28 f-w-5 c-#666">{{ item?.dictTypeLabel }}</view>
                            <view class="d-flex flex-wrap gap-16">
                                <view v-for="(items, idnex) in item?.childVos" :key="idnex" class="bg-#fff c-#333 radius-10 pd4-16-24-16-24 mb-10" @click="selectItem(items?.dictLabel)">
                                    {{ items?.dictLabel }}
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
                <!-- 自行填写标签页 -->
                <template v-if="+activetab == 2">
                    <view class="d-flex flex-cln">
                        <view class="pt-16 f-s-28 c-#333">规格等级</view>
                        <view class="d-flex flex-wrap gap-16 f-s-28 mt-16">
                            <up-input v-model="temPtech" clearable border="bottom" placeholder="请输入规格等级">
                                <template #suffix>
                                    <up-button type="primary" @click="confirmAdd()" style="height: 60rpx; width: 120rpx; font-size: 22rpx">确认添加</up-button>
                                </template>
                            </up-input>
                        </view>
                    </view>
                </template>
            </view>
        </view>
    </z-paging>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';

const list = ref<any>();
const activetab = ref<number>(0);
const STORAGE_KEY = 'specification-level-cache';
const temPtech = ref<string>('');

const list1 = reactive([
    { name: '常用', value: 0 },
    { name: '规格等级库', value: 1 },
    { name: '自行填写', value: 2 },
]);

const changeType = (tabItem: any) => {
    activetab.value = tabItem?.value;
};

const commonly = ref<string[]>([]);
const ptechData = ref<any[]>([]);

// 选中项并返回
const selectItem = (item: string) => {
    if (!item) return;

    // 添加到常用缓存
    let cached = uni.getStorageSync(STORAGE_KEY) || '';
    let items = cached ? cached.split(',') : [];

    // 去重
    const index = items.indexOf(item);
    if (index > -1) {
        items.splice(index, 1);
    }
    items.push(item);

    // 限制最多 40 个
    const MAX_ITEMS = 40;
    if (items.length > MAX_ITEMS) {
        items.splice(0, items.length - MAX_ITEMS);
    }

    // 更新缓存
    const newCached = items.join(',');
    uni.setStorageSync(STORAGE_KEY, newCached);
    commonly.value = items;

    // 返回选择结果
    uni?.$emit('updateSpecificationLevel', {
        data: item,
    });

    setTimeout(() => {
        uni.navigateBack({
            delta: 1,
        });
    }, 300);
};

// 确认添加（自行填写）
const confirmAdd = () => {
    if (!temPtech.value) {
        uni.showToast({
            title: '请输入规格等级',
            icon: 'none',
        });
        return;
    }

    // 添加到常用缓存
    let cached = uni.getStorageSync(STORAGE_KEY) || '';
    let items = cached ? cached.split(',') : [];

    // 去重
    const index = items.indexOf(temPtech.value);
    if (index > -1) {
        items.splice(index, 1);
    }
    items.push(temPtech.value);

    // 限制最多 40 个
    const MAX_ITEMS = 40;
    if (items.length > MAX_ITEMS) {
        items.splice(0, items.length - MAX_ITEMS);
    }

    // 更新缓存
    const newCached = items.join(',');
    uni.setStorageSync(STORAGE_KEY, newCached);
    commonly.value = items;

    // 返回选择结果
    uni?.$emit('updateSpecificationLevel', {
        data: temPtech.value,
    });

    setTimeout(() => {
        uni.navigateBack({
            delta: 1,
        });
    }, 300);
};

const query = async () => {
    const res = await useClientRequest.get(`/plt-api/app/process/tech/listAllGroup`, {
        groupType: 'specn_level',
    });
    ptechData.value = res?.data;
};

onLoad(() => {
    query();
    let cached = uni.getStorageSync(STORAGE_KEY) || '';
    commonly.value = cached ? cached.split(',') : [];
});
</script>
