<template>
    <z-paging ref="paging" safe-area-inset-bottom v-model="list">
        <template #top>
            <ut-navbar title="加工工艺及步骤" :fixed="false"></ut-navbar>
            <view class="pd-24 bg-#fff">
                <view class="c-#333 f-s-26 f-w-5 pb-10">已选择工艺步骤</view>
                <scroll-view scroll-y v-if="ptechTransit?.length > 0" style="max-height: 360rpx" class="border-#37A954 b-radius">
                    <view style="max-height: 360rpx" class="d-flex flex-wrap pd-24 a-c gap-10">
                        <template v-for="(item, index) in ptechTransit?.split(',')" :key="index">
                            <image v-if="index !== 0" src="@/static/images/common/craftArrow.png" class="mr-10 ml-10" style="width: 44rpx; height: 44rpx"> </image>
                            <view class="p-rtv">
                                <up-icon color="red" name="close-circle-fill" @click="removePtech(index)" style="position: absolute; right: -10rpx; top: -10rpx"></up-icon>
                                <view class="pd-16 bg-#37A9541A c-primary b-radius mb-10"> {{ item }}</view>
                            </view>
                        </template>
                    </view>
                </scroll-view>
                <view v-else class="pd-24 a-c border-#37A954 b-radius h-84">
                    <view class="f-s-26 c-#ccc">请按照顺序，点击下方工艺或者自填进行添加工艺</view>
                </view>
                <view class="h-16"></view>
                <up-button type="primary" @click="changePtech">确认</up-button>
            </view>
            <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="unAddPtech(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">{{ 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="addPtech(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">加工工艺名称</view>
                        <view class="d-flex flex-wrap gap-16 f-s-28">
                            <up-input v-model="temPtech" clearable border="bottom" placeholder="请输入加工工艺名称">
                                <template #suffix>
                                    <up-button type="primary" @click="addPtech(temPtech)" 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 ptechTransit = ref<string>('');
const activetab = ref<number>(0);
const STORAGE_KEY = 'pro-process-steps-cache';
const temPtech = ref<string>('');
const list1 = reactive([
    { name: '常用', value: 0 },
    { name: '工艺库', value: 1 },
    { name: '自行填写工艺', value: 2 },
]);
const changeType = (tabItem: any) => {
    console.log(tabItem, 'tabItem');

    activetab.value = tabItem?.value;
};
const commonly = ref<string[]>([]);
const ptechData = ref<any[]>([]);
const removePtech = (index: number) => {
    if (!ptechTransit.value) return;
    const lists = ptechTransit.value.split(',');
    lists.splice(index, 1);
    ptechTransit.value = lists.join(',');
};
const addPtech = (item: string) => {
    // 从缓存读取现有数据
    let cached = uni.getStorageSync(STORAGE_KEY) || '';
    let items = cached ? cached.split(',') : [];
    // 去重：如果已存在相同的 item，先移除
    const index = items.indexOf(item);
    if (index > -1) {
        items.splice(index, 1);
    }
    // 添加新的 item
    items.push(item);

    // 限制最多40个：如果超过，移除最旧的（第一个）
    const MAX_ITEMS = 40;
    if (items.length > MAX_ITEMS) {
        items.splice(0, items.length - MAX_ITEMS); // 移除超出部分
    }

    // 更新缓存和UI
    const newCached = items.join(',');
    uni.setStorageSync(STORAGE_KEY, newCached);
    commonly.value = items;
    ptechTransit.value = ptechTransit.value ? `${ptechTransit.value},${item}` : item;
    temPtech.value = '';
};
//不存储在缓存中
const unAddPtech = (item: string) => {
    ptechTransit.value = ptechTransit.value ? `${ptechTransit.value},${item}` : item;
};
const query = async () => {
    const res = await useClientRequest.get(`/plt-api/app/process/tech/listAllGroup`);
    ptechData.value = res?.data;
};

const changePtech = () => {
    uni?.$emit('updatePtechTransit', {
        data: ptechTransit.value,
    });
    setTimeout(() => {
        uni.navigateBack({
            delta: 1,
        });
    }, 1000);
};

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