<template>
    <view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden" :style="themeColor()">
        <view class="fixed top-0 left-0 right-0 z-200">
            <view class="tab-style-1 py-[20rpx] bg-[#fff] border-0  border-solid border-b-[1rpx] border-[#f6f6f6] ">
                <view class="tab-left text-[28rpx]">
                    <text>共</text>
                    <text class="text-primary">{{ browseTotal }}</text>
                    <text>条</text>
                </view>
                <view class="tab-right !items-center">
                    <view class="flex items-center" @click="handleSelect">
                        <view class="tab-right-date">日期</view>
                        <view class="nc-iconfont nc-icon-a-riliV6xx-36 tab-right-icon"></view>
                    </view>
                    <view class="w-[2rpx] h-[28rpx] mx-[20rpx] bg-gradient-to-b from-[#333] to-[#fff]"></view>
                    <view @click="isEdit = !isEdit" class="text-[#333] text-[28rpx]">{{ isEdit ? '完成' : '管理' }}</view>
                </view>
            </view>
        </view>
        <view class="bg-[#fff] mb-[20rpx] pt-[30rpx] px-[20rpx]" v-for="(item, index) in browseList" :key="index">
            <view class="flex items-center h-[34rpx]  mb-[20rpx]">
                <view class="self-center w-[58rpx]  flex items-center" v-if="isEdit" @click.stop="isSelectGroup(item)">
                    <view class="bg-[#fff] w-[34rpx] h-[34rpx] rounded-[17rpx] flex items-center justify-center">
                        <text
                            class=" iconfont text-primary text-[34rpx] w-[34rpx] h-[34rpx] rounded-[17rpx] overflow-hidden shrink-0"
                            :class="{ 'iconxuanze1': item.checked, 'bg-[#F5F5F5]': !item.checked }"></text>
                    </view>
                </view>
                <view class="text-[28rpx] font-500 text-[#333] ">{{ item.date }}</view>
            </view>
            <view class="flex flex-wrap">
                <view class="w-[230rpx] mb-[20rpx]" :class="{ 'mr-[10rpx]': (Number(subIndex) + 1) % 3 }"
                    v-for="(subItem, subIndex) in item.list" :key="subIndex" @click="toDetail(subItem)">
                    <view
                        class="relative w-[230rpx] h-[230rpx] rounded-[var(--goods-rounded-mid)] overflow-hidden mb-[10rpx]">
                        <u--image width="230rpx" height="230rpx" :radius="'var(--goods-rounded-mid)'"
                            :src="img(subItem.goods_cover_thumb_mid ? subItem.goods_cover_thumb_mid : '')"
                            mode="aspectFill">
                            <template #error>
                                <image class="w-[230rpx] h-[230rpx] rounded-[var(--goods-rounded-mid)] overflow-hidden"
                                    :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
                            </template>
                        </u--image>
                        <view v-if="subItem.productStatus == 0"
                            class="absolute left-0 top-0  w-[230rpx] h-[230rpx]  leading-[230rpx] text-center "
                            style="background-color: rgba(0,0,0,0.3);">
                            <text class="text-[#fff] text-[28rpx]">已失效</text>
                        </view>
                        <view
                            class="absolute top-0 left-0 right-0 bottom-0 p-[10rpx] flex justify-end items-start z-100"
                            v-if="isEdit" @click.stop="changeItem(item, subItem)">
                            <view
                                class="bg-[#fff] w-[34rpx] h-[34rpx] rounded-[17rpx] flex items-center justify-center">
                                <text
                                    class="iconfont text-primary text-[34rpx] w-[34rpx] h-[34rpx] rounded-[17rpx] overflow-hidden shrink-0"
                                    :class="{ 'iconxuanze1': subItem.checked, 'bg-[#F5F5F5]': !subItem.checked }"></text>
                            </view>
                        </view>
                    </view>
                    <view class="text-[var(--price-text-color)] price-font">
                        <text class="text-[24rpx] font-500">￥</text>
                        <text class="text-[40rpx] font-500">{{ parseFloat(subItem.show_price).toFixed(2).split('.')[0]
                            }}</text>
                        <text class="text-[24rpx] font-500">.{{ parseFloat(subItem.show_price).toFixed(2).split('.')[1]
                            }}</text>
                        <image v-if="subItem.show_type == 'member_price'" class="max-w-[50rpx] h-[28rpx] ml-[6rpx]"
                            :src="img('addon/shop/VIP.png')" mode="heightFix" />
                        <image v-else-if="subItem.show_type == 'newcomer_price'"
                            class="max-w-[60rpx] h-[28rpx] ml-[6rpx]" :src="img('addon/shop/newcomer.png')"
                            mode="heightFix" />
                        <image v-else-if="subItem.show_type == 'discount_price'"
                            class="max-w-[80rpx] h-[28rpx] ml-[6rpx]" :src="img('addon/shop/discount.png')"
                            mode="heightFix" />
                    </view>
                </view>
            </view>
        </view>
        <mescroll-empty v-if="!browseList.length && loading" :option="{ tip: '暂无浏览的商品' }"></mescroll-empty>
        <view v-if="browseList.length && isEdit" class="fixed left-0 right-0 bottom-0 z-200 bg-[#fff]  pb-ios">
            <view v-if="checkedNum"
                class="h-[66rpx] flex items-center justify-between pl-[30rpx] pr-[20rpx] border-0  border-b-[1rpx] border-solid border-[#f6f6f6]">
                <view class="text-[24rpx]">
                    <text>已选</text>
                    <text class="text-primary">{{ checkedNum }}</text>
                    <text>件宝贝</text>
                </view>
                <view class="text-[24rpx] text-[#999]" @click="clearBrowseFn">一键清空宝贝足迹</view>
            </view>
            <view class="flex h-[100rpx] items-center  justify-between pl-[30rpx] pr-[20rpx]">
                <view class="flex items-center" @click="allChange">
                    <text
                        class="self-center iconfont text-primary text-[34rpx] mr-[10rpx] w-[34rpx] h-[34rpx] rounded-[17rpx] overflow-hidden flex-shrink-0"
                        :class="{ 'iconxuanze1': isSelectAll, 'bg-color': !isSelectAll }"></text>
                    <text class="font-400 text-[#303133] text-[26rpx]">全选</text>
                </view>
                <button
                    class="w-[180rpx] h-[70rpx] font-500 text-[26rpx] leading-[70rpx] !text-[#fff] m-0 rounded-full primary-btn-bg remove-border"
                    @click="deleteBrowseFn">删除</button>
            </view>
        </view>

        <!-- 时间选择 -->
        <select-date ref="selectDateRef" @confirm="confirmFn" />
    </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { img, redirect } from '@/utils/common';
import { getBrowse, delBrowse } from '@/addon/shop/api/goods';
import selectDate from '@/components/select-date/select-date.vue';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app';

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'

const isEdit = ref(false)
let loading = ref<boolean>(false);
const optionLoading = ref(false)
const browseTotal = ref<number>(0);
let browseList = ref<any>([]);
const create_time = ref([])

onShow(() => {
    getBrowseListFn()
})
const getBrowseListFn = () => {
    loading.value = false;
    const data = {
        startTime: create_time.value.length > 1 ? create_time.value[0] : '',
        endTime: create_time.value.length > 1 ? create_time.value[1] : ''
    };
    browseList.value = [];
    getBrowse(data)
        .then((res: any) => {
            // 新接口返回的是 { "2026-04-30": [...], "2026-04-29": [...] }
            const groupedData = res.data || {}; // 假设总数据在 res.data
            browseTotal.value = Object.values(groupedData).flat().length; // 总条数

            // 转换为页面需要的格式：[{ date: '2026-04-30', list: [...] }, ...]
            const formattedData = Object.entries(groupedData).map(([date, list]) => ({
                date,
                list: (list as any[]).map(item => ({
                    ...item,
                    goods_id: item.id, // 页面使用 goods_id，但接口是 id
                    goods_cover_thumb_mid: item.productImage,
                    show_price: item.memberPrice ?? item.minSellingPrice ?? item.marketPrice,
                    status: item.productStatus === '1' ? 1 : 0, // 1=有效, 0=失效
                    browse_time: `${date} 00:00:00` // 补充 browse_time 用于兼容旧逻辑（如果需要）
                }))
            }));

            // 初始化选中状态
            formattedData.forEach((item: any) => {
                item.checked = false;
                item.list.forEach((subItem: any) => {
                    subItem.checked = false;
                });
            });

            formattedData.forEach(newItem => {
                const existingIndex = browseList.value.findIndex((item: any) => item.date === newItem.date);
                if (existingIndex !== -1) {
                    // 合并商品列表（去重可选）
                    const existingIds = new Set(browseList.value[existingIndex].list.map((g: any) => g.goods_id));
                    const newItemsToAdd = newItem.list.filter((g: any) => !existingIds.has(g.goods_id));
                    browseList.value[existingIndex].list.push(...newItemsToAdd);
                } else {
                    browseList.value.push(newItem);
                }
            });
            loading.value = true;
        })
        .catch(() => {
            loading.value = true;
        });
};

// 选择数量
const checkedNum = computed(() => {
    let num = 0
    browseList.value.forEach((item: any) => {
        item.list.forEach((subItem: any) => {
            subItem.checked && (num += 1)
        })
    })
    return num
})

/**
 * 全选
 */
//判断是否全选状态
const isSelectAll = ref(false)
const isallclick = () => {
    const isActive = browseList.value.every((item: any) => {
        return item.checked
    })
    if (isActive) {
        isSelectAll.value = true
    } else {
        isSelectAll.value = false
    }
}
// 选择每天的
const isSelectGroup = (data: any) => {
    data.checked = !data.checked
    data.list.forEach((item: any) => {
        item.checked = data.checked
    })
    isallclick()
}
// 全选
const allChange = () => {
    isSelectAll.value = !isSelectAll.value
    browseList.value.forEach((item: any) => {
        item.checked = isSelectAll.value
        item.list.forEach((subItem: any) => {
            subItem.checked = isSelectAll.value
        })
    })
}
// 选择单个商品
const changeItem = (data: any, value: any) => {
    value.checked = !value.checked
    const isActive = data.list.every((item: any) => {
        return item.checked
    })
    if (isActive) {
        data.checked = true
    } else {
        data.checked = false
    }
    isallclick()
}

// 删除
const deleteBrowseFn = () => {
    if (!checkedNum.value) {
        uni.showToast({ title: '还没有选择商品', icon: 'none' })
        return
    }
    if (optionLoading.value) return
    optionLoading.value = true

    let ids: any = []
    browseList.value.forEach((item: any) => {
        item.list.forEach((subItem: any) => {
            subItem.checked && ids.push(subItem.id)
        })
    })
    ids = ids.join(',')
    delBrowse(ids).then((res: any) => {
        optionLoading.value = false
        getBrowseListFn()
    })
}

const clearBrowseFn = () => {
    if (optionLoading.value) return
    optionLoading.value = true

    let ids: any = []
    browseList.value.forEach((item: any) => {
        item.list.forEach((subItem: any) => {
            ids.push(subItem.id)
        })
    })
    ids = ids.join(',')
    delBrowse(ids).then((res: any) => {
        getBrowseListFn()
        optionLoading.value = false
    })
}
//日期筛选
const selectDateRef = ref<any>(null)
const handleSelect = () => {
    selectDateRef.value.show = true
}
// 确定时间筛选
const confirmFn = (data: any) => {
    create_time.value = data;
    browseList.value = []
    getBrowseListFn()
}

const toDetail = (data: any) => {
    redirect({ url: '/addon/shop/pages/goods/detail', param: { goodsId: data.brandId } })
}
</script>

<style lang="scss" scoped>
.bg-color {
    background-color: #f5f5f5;
}
</style>
