<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" @query="query" hide-no-more-inside>
        <template #top>
            <ut-navbar title="码生成及管理" :fixed="false"></ut-navbar>
        </template>
        <template>
            <!-- 搜索栏 -->
            <view class="d-flex a-c pd-24 pb-0 bg-#f7f7f7">
                <view class="min-w-220 flex1">
                    <ut-action-sheet v-model="form.downloadFlag"
                        :tabs="[{ label: '全部', value: '' }, ...pt_code_downflag]" @change="onRefresh" title="选择类型">
                        <view class="d-flex search-select-item a-c">
                            <view class="flex1 ov-hd f-s-28 c-333 text-center f-w-5 w-s-no d-flex a-c j-c">
                                <view class="w-s-no">{{ selectDictLabel(pt_code_downflag, form?.downloadFlag) || '全部' }}
                                </view>
                            </view>
                            <up-icon size="24rpx" color="#333" name="arrow-down-fill" class="mr-5"></up-icon>
                        </view>
                    </ut-action-sheet>
                </view>
                <view class="h-86 pl-20 w-100%">
                    <ut-search ref="searchRef" v-model="form.keyword" @search="changeSeach" @change="changeSeach"
                        margin="0" :border="false" placeholder="搜生成批号、操作人" bgColor="#fff" height="86rpx"
                        borderRadius="10rpx"></ut-search>
                </view>
            </view>
            <!-- 列表 -->
            <view class="pd-24">
                <view v-for="(item, index) in list" :key="item.id || index">
                    <CodeItem :item="item" :showButtons="true" @refresh="handleRefresh" @download="handleDownload"
                        @findAgent="handleFindAgent" @viewOrder="handleViewOrder" @reDownload="handleReDownload"
                        @itemClick="handleItemClick" />
                </view>
            </view>
        </template>
        <template #empty>
            <view class="d-flex flex-cln a-c">
                <ut-empty class="mg-at" color="#ccc" size="28rpx"
                    image="https://yujin-szyy.oss-cn-chengdu.aliyuncs.com/szyy/images-plt/plant/noEmpty.png">暂无追溯码数据</ut-empty>
            </view>
        </template>
        <template #bottom>
            <ut-tabar activeTab="more"></ut-tabar>
        </template>
    </z-paging>

    <!-- 悬浮按钮 -->
    <ut-suspension v-if="sus?.left" :imageWidth="60" :imageHeight="60" :x="sus?.left" :y="sus?.bottom" :inertia="false"
        :snap-threshold="40">
        <image src="https://yujin-szyy.oss-cn-chengdu.aliyuncs.com/szyy/images-plt/common/btn_add_logo.png" mode="widthFix"
            class="w-120 h-120" @click="showGenerateDialog = true"></image>
    </ut-suspension>

    <!-- 生成追溯码弹框 -->
    <GenerateDialog v-model:show="showGenerateDialog" @success="handleGenerateSuccess" />
</template>

<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import CodeItem from './models/code-item.vue';
import GenerateDialog from './models/generate-dialog.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_code_downflag } = toRefs<any>(proxy?.useDict('pt_code_downflag'));
const paging = ref();
const list = ref<any[]>([]);

// 搜索表单
const form = ref({
    downloadFlag: '',
    keyword: '',
});

// 悬浮按钮位置
const sus = ref({
    left: 0,
    bottom: 0,
});

// 弹框显示状态
const showGenerateDialog = ref(false);

// 初始化悬浮按钮位置
const initSuspension = () => {
    const systemInfo = uni.getSystemInfoSync();
    const windowInfo = uni.getWindowInfo();
    sus.value.left = systemInfo.windowWidth - 10;
    sus.value.bottom = systemInfo.windowHeight - 200;
};

// 分页查询
const query = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...form.value,
    };
    try {
        const res = await useClientRequest.get('/plt-api/app/traceCodeLog/list', params);
        if (res) {
            const { rows } = res;
            paging.value.complete(rows);
        }
    } catch (error) {
        console.error('查询列表失败:', error);
        paging.value.complete([]);
    }
};

// 搜索
const changeSeach = () => {
    paging.value.reload();
};

// 刷新
const onRefresh = () => {
    paging.value.reload();
};

// 处理刷新按钮点击（单条数据刷新）
const handleRefresh = async (id: number) => {
    try {
        const res = await useClientRequest.get(`/plt-api/app/traceCodeLog/${id}`);
        if (res && res.code === 200) {
            const newData = res.data;
            // 找到对应项并更新
            const index = list.value.findIndex((item) => item.id === id);
            if (index !== -1) {
                list.value[index] = newData;
            }
            uni.showToast({
                title: '刷新成功',
                icon: 'success',
            });
        }
    } catch (error) {
        console.error('刷新失败:', error);
        uni.showToast({
            title: '刷新失败',
            icon: 'none',
        });
    }
};

// 处理下载按钮点击
const handleDownload = async (item: any) => {
    if (!item.id) {
        uni.showToast({
            title: '缺少下载参数',
            icon: 'none',
        });
        return;
    }
    try {
        const downloadUrl = `/plt-api/app/traceCodeLog/download/${item.id}`;
        await useClientRequest.down(
            {
                url: downloadUrl,
                fileName: `traceCode_${item.id}.xlsx`,
            },
            '下载中',
        );
    } catch (error) {
        console.error('下载失败:', error);
    }
};

// 处理找人代制作按钮点击
const handleFindAgent = (item: any) => {
    console.log('找人代制作:', item);
    uni.showToast({
        title: '代制作功能开发中',
        icon: 'none',
    });
};

// 处理查看代做订单按钮点击
const handleViewOrder = (item: any) => {
    console.log('查看代做订单:', item);
    uni.showToast({
        title: '订单功能开发中',
        icon: 'none',
    });
};

// 处理重新下载按钮点击（与下载使用同一接口）
const handleReDownload = (item: any) => {
    handleDownload(item);
};

// 处理 item 点击
const handleItemClick = (item: any) => {
    console.log('item 点击:', item);
    // 可以跳转到详情页
};

// 处理生成成功
const handleGenerateSuccess = () => {
    // 重新加载列表
    paging.value.reload();
};

onMounted(() => {
    initSuspension();
});
</script>

<style scoped lang="scss">
.search-select-item {
    height: 86rpx;
    background-color: #fff;
    border-radius: 10rpx;
    box-sizing: border-box;
    padding: 12rpx;
}
</style>
