<!-- 商品列表 -->
<template>
    <div class="header">
        <div class="menus scroll-x" ref="tabScrollRef">
            <div class="item tab-item" :class="{ active: goodsStore.categoryIndex == index }"
                v-for="(item, index) in goodsStore.categoryList" :key="item.id" @click="changeCategory(index)">
                <el-icon v-if="item.id === ''" class="icon" :class="{ active: goodsStore.goodsListLoading }">
                    <RefreshRight />
                </el-icon>
                <el-text>
                    {{ item.name }}
                </el-text>
                <svg t="1745301209207" class="svg_icon" viewBox="0 0 7281 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="5471" width="256" height="256">
                    <path
                        d="M150.839971 441.855385C1232.762051 829.913873 2369.633487 1024 3560.089077 1024c1188.862854 0 2377.043108-193.403527 3563.971927-579.983046A227.533561 227.533561 0 1 0 6983.21773 11.248122C5841.113022 383.265493 4700.373516 568.932879 3560.089077 568.932879 2421.511139 568.932879 1336.744889 383.72056 304.425124 13.40969a227.533561 227.533561 0 0 0-153.585153 428.445695z"
                        p-id="5472"></path>
                </svg>
            </div>
        </div>
        <el-popover trigger="click" :width="600" title="全部分类" :visible="showPopover">
            <template #reference>
                <div class="all" @click="showMoreMenu">
                    <el-icon class="icon" :class="{ active: showPopover }">
                        <Menu />
                    </el-icon>
                </div>
            </template>
            <template #default>
                <div class="popover_wrap">
                    <el-button :plain="goodsStore.categoryIndex != index" type="primary"
                        v-for="(item, index) in goodsStore.categoryList" :key="item.id" @click="changeCategory(index)">
                        {{ item.name }}
                    </el-button>
                </div>
            </template>
        </el-popover>
    </div>
    <div class="search_wrap">
        <div class="left">
            <el-button :type="showEditor ? 'warning' : ''" @click="showEditorChange">
                {{ showEditor ? '关闭编辑' : '编辑' }}
            </el-button>
            <el-button type="warning" icon="Food" @click="showTemporaryDish = true">临时菜</el-button>
        </div>
        <div class="right">
            <div class="input">
                <el-input placeholder="请输入商品名称查询" v-model="commdityName" clearable @input="inputChange"
                    style="width:200px"></el-input>
            </div>
            <el-button :loading="searchLoading" :icon="Search" @click="searchHandle">搜索</el-button>
        </div>
        <!-- <el-button :icon="shopListType == 'text' ? 'PictureRounded' : 'PriceTag'"
            @click="changeShopListType"></el-button> -->
    </div>
    <div class="shop_list" :class="{ img: shopListType == 'img' }" v-loading="loading">
        <!-- <swiper class="swiper_box" direction="vertical" @slideChange="onSlideChange"> -->
        <swiper ref="swiperRef" :loop="false" class="swiper_box" direction="vertical" :modules="[Mousewheel]"
            :simulate-touch="true" :allow-touch-move="true" :mousewheel="{
                enabled: true,
                forceToAxis: true,
                releaseOnEdges: true,
                invert: false,
            }">
            <swiper-slide class="slide_item" v-for="(goods, index) in goodsStore.goodsList" :key="index">
                <div class="item_wrap" v-for="item in goods" :key="item.id" @click="showSkuHandle(item)">
                    <div class="item">
                        <transition name="el-fade-in">
                            <div class="more" v-if="item.showMore" @click.stop>
                                <div class="ul">
                                    <template v-if="goodsStore.categoryList[goodsStore.categoryIndex].id == 'off_sale'">
                                        <div class="li" @click.stop="showPutawayHandle(item)">上架</div>
                                    </template>
                                    <template v-else>
                                        <div class="li" @click.stop="goodEditor(item, 0)">下架</div>
                                        <div class="li" @click.stop="goodEditor(item, 1)">售罄</div>
                                        <!-- <div class="li" @click.stop="goodStockNumberHandle(item)">修改库存</div> -->
                                    </template>
                                    <div class="li" @click.stop="item.showMore = false">取消</div>
                                </div>
                            </div>
                        </transition>
                        <div class="dot" v-if="item.number">{{ item.number }}</div>
                        <div class="cover" v-if="shopListType == 'img'">
                            <div class="xxzk" v-if="item.is_time_discount == 1">限时折扣</div>
                            <el-image :src="`${item.coverImg}?x-oss-process=image/resize,m_lfit,w_120,h_120`"
                                class="el_img" fit="cover"></el-image>
                            <!-- 已下架 -->
                            <div class="sell_out" v-if="!item.isSale">
                                <img class="sell_out_icon" src="@/assets/icon_goods_yxj.svg">
                            </div>
                            <!-- 未开售（不在可售时间内） -->
                            <div class="sell_out"
                                v-else-if="!isProductAvailable(item.days, item.startTime, item.endTime)">
                                <img class="sell_out_icon" src="@/assets/icon_goods_wks.svg">
                            </div>
                            <!-- 售罄 -->
                            <div class="sell_out" v-else-if="item.isSoldStock">
                                <img class="sell_out_icon" src="@/assets/icon_goods_sq.svg">
                            </div>
                            <!-- 库存不足 -->
                            <div class="sell_out" v-else-if="item.isStock && item.stockNumber <= 0">
                                <img class="sell_out_icon" src="@/assets/icon_goods_kcbz.svg">
                            </div>
                            <div class="weight" v-if="item.type == 'weight'">称重</div>
                            <div class="weight" v-if="item.type == 'package' && item.groupType == 1">可选套餐</div>
                            <div class="weight" v-if="item.type == 'package' && item.groupType == 0">固定套餐</div>
                        </div>
                        <div class="name"><el-text line-clamp="1">{{ item.name }}</el-text></div>
                        <div class="item_empty" v-if="shopListType == 'text'"></div>
                        <div class="price">
                            <div class="price_warp">
                                <template v-if="item.is_time_discount == 1">
                                    <el-text tag="del" class="del" size="small">￥{{ item.lowPrice }}</el-text>
                                    <el-text>￥{{ +item.time_discount_price }}</el-text>
                                </template>
                                <template v-else>
                                    <template v-if="goodsStore.showVipPrice && item.lowMemberPrice > 0">
                                        <el-text tag="del" class="del" size="small">
                                            ￥{{ item.lowPrice }}
                                        </el-text>
                                        <el-text>
                                            ￥{{ item.lowMemberPrice }}
                                        </el-text>
                                    </template>
                                    <template v-else>
                                        <el-text>￥{{ item.lowPrice }}</el-text>
                                    </template>
                                </template>
                            </div>
                            <div class="show_more_btn" v-if="showEditor">
                                <el-icon>
                                    <MoreFilled />
                                </el-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </swiper-slide>
            <swiper-slide v-if="!goodsStore.goodsList.length">
                <div class="goods_empty" style="padding-top: 15vh;">
                    <el-empty description="暂无商品~" v-if="!goodsStore.goodsList.length" />
                </div>
            </swiper-slide>
        </swiper>
    </div>
    <div class="empty">
        <el-empty description="空空如也~" v-if="!goodsStore.goodsList.length" />
    </div>
    <!-- 选择规格 -->
    <skuModal ref="skuModalRef" @success="skuConfirm" />
    <!-- 编辑商品 -->
    <el-dialog v-model="showGoodEditor" :title="`${goodEditorEmun[goodEditorType]}商品`">
        <div class="dialog">
            <div class="el-popover__title content">
                确定要{{ `${goodEditorEmun[goodEditorType]}商品：${goodEditorItem.name}？` }}
            </div>
            <div class="footer_wrap">
                <div class="btn">
                    <el-button style="width: 100%;" @click="showGoodEditor = false">取消</el-button>
                </div>
                <div class="btn">
                    <el-button type="primary" style="width: 100%;" :loading="goodEditorLoading"
                        @click="goodEditorConfirm">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 修改库存 -->
    <el-dialog v-model="showGoodsEditorStock" title="修改库存" width="400px">
        <div class="dialog">
            <el-form>
                <el-form-item label="库存">
                    <div>
                        <el-input-number v-model="goodsEditorStockNumber" :min="0"></el-input-number>
                        <div class="tips">修改前库存：{{ goodsEditorStockItem.stockNumber }}</div>
                    </div>
                </el-form-item>
            </el-form>
            <div class="footer_wrap">
                <div class="btn">
                    <el-button style="width: 100%;" @click="showGoodsEditorStock = false">取消</el-button>
                </div>
                <div class="btn">
                    <el-button type="primary" style="width: 100%;" :loading="goodsEditorStockLoading"
                        @click="goodsEditorStockConfirm">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 关闭售罄 -->
    <el-dialog v-model="showCloseSell" title="关闭售罄">
        <div class="dialog">
            <div class="el-popover__title content">
                确定要将{{ `【${goodEditorItem.name}】` }}关闭售罄吗？
            </div>
            <div class="footer_wrap">
                <div class="btn">
                    <el-button style="width: 100%;" @click="showCloseSell = false">取消</el-button>
                </div>
                <div class="btn">
                    <el-button type="primary" style="width: 100%;" :loading="closeSellLoading"
                        @click="closeSellHandle">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 上架商品 -->
    <el-dialog v-model="showPutaway" title="上架商品">
        <div class="dialog">
            <div class="el-popover__title content">
                确定要上架商品：{{ `${goodEditorItem.name}` }}吗？
            </div>
            <div class="footer_wrap">
                <div class="btn">
                    <el-button style="width: 100%;" @click="showPutaway = false">取消</el-button>
                </div>
                <div class="btn">
                    <el-button type="primary" style="width: 100%;" :loading="showPutawayLoading"
                        @click="putawayHandle">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 添加临时菜 -->
    <el-dialog v-model="showTemporaryDish" title="添加临时菜" top="3vh" @open="showTemporaryDishOpen"
        @closed="showTemporaryDishClosed">
        <div class="dialog">
            <div class="el-popover__title content">
                <el-form ref="temporaryFormRef" :model="temporaryForm" :rules="temporaryFormRules" label-width="100px"
                    label-position="left">
                    <el-form-item label="菜品名称" prop="product_name">
                        <el-input v-model="temporaryForm.product_name" placeholder="请输入菜品名称" />
                    </el-form-item>
                    <!-- <el-form-item label="菜品分类" prop="categoryId">
                        <el-select v-model="temporaryForm.categoryId" placeholder="请选择菜品分类">
                            <el-option v-for="item in goodsStore.originCategoryList" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="价格" prop="discount_sale_amount">
                        <el-input v-model="temporaryForm.discount_sale_amount" placeholder="请输入价格" @input="priceInput">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item label="单位" prop="unit">
                        <el-select v-model="temporaryForm.unit" placeholder="请选择单位">
                            <el-option v-for="item in units" :key="item.id" :label="item.name"
                                :value="item.name"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="下单数量">
                        <el-input-number v-model="temporaryForm.number" :min="1" />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="temporaryForm.remark" type="textarea" placeholder="请输入自定义备注" />
                        <div class="remark_list">
                            <div class="item" v-for="item in noteList" :key="item" @click="addNote(item)">
                                {{ item }}
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="footer_wrap">
                <div class="btn">
                    <el-button style="width: 100%;" @click="showTemporaryDish = false">取消</el-button>
                </div>
                <div class="btn">
                    <el-button type="primary" style="width: 100%;" :loading="temporaryFormLoading"
                        @click="temporaryFormSubmit">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 称重商品弹窗 -->
    <WeightModal ref="WeightModalRef" @success="skuConfirm" />
    <!-- 套餐商品弹窗 -->
    <GroupModal ref="GroupModalRef" @success="skuConfirm" />
</template>

<script setup>
import _ from 'lodash'
import { dayjs, ElMessage } from 'element-plus'
import isBetween from 'dayjs/plugin/isBetween';
dayjs.extend(isBetween);

import { Search } from '@element-plus/icons-vue'
import { ref, watch, onMounted } from 'vue'
import useStorage from "@/utils/useStorage";
import skuModal from '@/components/skuModal.vue'
import WeightModal from './weightModal.vue'
import GroupModal from './groupModal.vue'
import { productStock, getUnitList } from '@/api/product'
import { useUser } from "@/store/user.js"
import { useGoods } from '@/store/goods.js'
import { Swiper, SwiperSlide } from 'swiper/vue'
import "swiper/swiper-bundle.css";
import { staffPermission } from '@/api/user.js'
import { clearNoNum } from '@/utils/index.js'
import { productOnOff, markIsSoldOut } from '@/api/product_new.js'

import { Mousewheel } from 'swiper/modules'

const swiperRef = ref(null)

const store = useUser()
const goodsStore = useGoods()

const props = defineProps({
    masterId: {
        type: String,
        default: ''
    }
})

watch(() => goodsStore.categoryList, (newVal, oldVal) => {
    if (newVal.length) {
        setTimeout(() => {
            tabContentAni(goodsStore.categoryIndex)
        }, 300)
    }
})

const emit = defineEmits(['success', 'loading'])

const skuModalRef = ref(null)

const shopListType = ref('img')

const commdityName = ref('')

const loading = ref(false)

const showPopover = ref(false)

// 根据商品名字查询
const inputChange = _.debounce(function () {
    // updateGoods()
    goodsStore.filterNameGoods(commdityName.value)
}, 500)


/** 添加临时菜 start */
const temporaryCategorys = ref([]) // 分类列表
const showTemporaryDish = ref(false) // 显示添加临时菜
const units = ref([]) // 单位列表
const temporaryFormRef = ref(null)
const resetTemporaryForm = ref({})
const temporaryForm = ref({
    is_temporary: 1, // 是临时菜
    discount_sale_amount: '', // 临时菜价格
    product_name: '', // 临时菜名称
    number: 1, // 下单数量
    remark: '', // 备注
})
const temporaryFormLoading = ref(false)

const noteList = ref([
    '免葱',
    '免香菜',
    '不要辣',
])

function priceInput(e) {
    setTimeout(() => {
        temporaryForm.value.discount_sale_amount = clearNoNum({ value: e })
    }, 50)
}

// 添加快捷备注
function addNote(str) {
    if (!temporaryForm.value.remark.length) {
        temporaryForm.value.remark += str
    } else {
        temporaryForm.value.remark += `，${str}`
    }
}

const temporaryFormRules = ref({
    product_name: [
        {
            required: true,
            message: '请输入菜品名称',
            trigger: 'blur',
        }
    ],
    categoryId: [
        {
            required: true,
            message: '请选择菜品分类',
            trigger: 'change',
        }
    ],
    discount_sale_amount: [
        {
            required: true,
            message: '请输入价格',
            trigger: 'blur',
        }
    ],
    unit: [
        {
            required: true,
            message: '请选择单位',
            trigger: 'change',
        }
    ],
})

// 打开
function showTemporaryDishOpen() {
    resetTemporaryForm.value = { ...temporaryForm.value }
}

// 关闭
function showTemporaryDishClosed() {
    temporaryForm.value = { ...resetTemporaryForm.value }
    temporaryFormRef.value.resetFields()
}

// 获取单位列表
async function getUnitListAjax() {
    try {
        const res = await getUnitList({
            shopId: store.userInfo.shopId,
            page: 1,
            size: 100,
            name: ''
        })
        units.value = res.records
    } catch (error) {
        console.log(error);
    }
}

// 提交临时菜
function temporaryFormSubmit() {
    temporaryFormRef.value.validate(async valid => {
        try {
            if (valid) {
                temporaryFormLoading.value = true
                goodsStore.addCart(temporaryForm.value)
                showTemporaryDish.value = false
            }
        } catch (error) {
            temporaryFormLoading.value = false
            console.log(error);
        }
        temporaryFormLoading.value = false
    })
}

/** 添加临时菜 end */

/** 套餐 start */
const GroupModalRef = ref(null)
/** 套餐 end */

// 搜索
const searchLoading = ref(false)
function searchHandle() {
    // searchLoading.value = true
    // updateGoods()
    goodsStore.filterNameGoods(commdityName.value)
}

// 确认选择规格回调
function skuConfirm(params) {
    let goodsItem = goodsStore.cartList.find(goods => goods.product_id == params.productId && goods.sku_id == params.id)
    console.log('params===', params);
    // console.log('goodsItem===', goodsItem);
    if (goodsItem && goodsItem.id) {
        // 编辑新增
        if (params.goods_type == 'weight' || params.type == 'weight') {
            // 称重商品
            console.log('编辑称重商品', params);
            goodsStore.operateCart({ ...goodsItem, number: params.number }, 'edit')
        } else if (params.goods_type == 'package') {
            // 添加
            console.log('添加套餐商品');
            goodsStore.addCart({ ...params })
        } else {
            goodsStore.operateCart({ ...goodsItem, number: +goodsItem.number + 1 }, 'edit')
        }
    } else {
        // 添加
        console.log('直接添加');
        let goods = goodsStore.originGoodsList.find(goods => goods.id == params.productId)
        console.log('goods===', goods.isStock);

        if (params.type == 'weight') {
            goodsStore.addCart({ ...params, number: params.number })
        } else {
            // 先判断起售数量是否大于库存
            if (goods.isStock && params.suitNum > goods.stockNumber) {
                ElMessage({
                    type: 'error',
                    message: '库存不足',
                })
                return
            }
            goodsStore.addCart({ ...params, number: params.suitNum })
        }
    }
}

// 显示全部分类
function showMoreMenu() {
    showPopover.value = !showPopover.value
}

// 显示/隐藏编辑
async function showEditorChange() {
    try {
        // await staffPermission('yun_xu_xiu_gai_shang_pin')
        if (showEditor.value) {
            showEditor.value = false
            goodsStore.goodsList.map(item => {
                item.map(val => {
                    val.showMore = false
                })
            })
        } else {
            showEditor.value = true
        }
    } catch (error) {
        console.log(error);
    }
}

// 显示sku
const WeightModalRef = ref(null)
function showSkuHandle(item) {
    if (showEditor.value) {
        if (item.isSoldStock) {
            goodEditorItem.value = item
            showCloseSell.value = true
        } else {
            goodsStore.goodsList.map(item => {
                item.map(val => {
                    val.showMore = false
                })
            })
            item.showMore = true
        }
    } else {
        let cartItem = goodsStore.cartList.find(goods => goods.product_id == item.id)

        if (!item.isSale) {
            ElMessage({
                type: 'error',
                message: '该商品已下架，请编辑上架后操作',
            })
            return
        } else if (!isProductAvailable(item.days, item.startTime, item.endTime)) {
            ElMessage({
                type: 'error',
                message: '不在可售时间内',
            })
            return
        } else if (item.isSoldStock) {
            ElMessage({
                type: 'error',
                message: '该商品已售罄',
            })
            return
        } else if (item.isStock && (item.stockNumber <= 0 || (cartItem && cartItem.number >= item.stockNumber))) {
            ElMessage({
                type: 'error',
                message: '库存不足',
            })
            return
        }

        let goodsItem = goodsStore.cartList.find(goods => goods.product_id == item.id)
        if (item.type == 'sku') {
            // 多规格
            skuModalRef.value.show({ ...item })
        } else if (item.type == 'single') {
            // 单规格
            if (goodsItem && goodsItem.id) {
                goodsStore.operateCart({ ...goodsItem, number: +goodsItem.number + 1 }, 'edit')
            } else {
                goodsStore.addCart({ ...item.skuList[0], lowPrice: item.skuList[0].salePrice, number: item.skuList[0].suitNum })
            }
        } else if (item.type == 'weight') {
            // 称重商品
            WeightModalRef.value.show(item)
        } else if (item.type == 'package' && item.groupType == 1) {
            // 套餐-可选套餐
            GroupModalRef.value.show(item)
        } else if (item.type == 'package' && item.groupType == 0) {
            // 固定套餐当做单规格处理
            if (goodsItem && goodsItem.id) {
                // 编辑
                goodsStore.operateCart({ ...goodsItem, number: +goodsItem.number + 1 }, 'edit')
            } else {
                // 添加
                goodsStore.addCart({
                    ...item.skuList[0], lowPrice: item.skuList[0].salePrice, type: item.type,
                    goods_type: 'package',
                    pro_group_info: item.groupSnap,
                    number: item.skuList[0].suitNum
                })
            }
        }
    }
}

// 编辑显示可选套
function showPackage(item) {
    GroupModalRef.value.show(item, 'edit')
}

// 切换商品显示模式
function changeShopListType() {
    if (shopListType.value == 'text') {
        shopListType.value = 'img'
    } else {
        shopListType.value = 'text'
    }
    useStorage.set('shopListType', shopListType.value)
}

// 从本地更新商品显示模式
function localUpdateShopListType() {
    return new Promise((resolve, reject) => {
        let type = useStorage.get('shopListType')
        if (type != null) {
            shopListType.value = type
        }
        resolve()
    })
}

// 切换分类;
function changeCategory(index) {
    showPopover.value = false
    goodsStore.setCategoryIndex(index)
    tabContentAni(index)
}

// 使tab平滑居中
const tabScrollRef = ref(null);
const activeTab = ref(0)
function tabContentAni(index) {
    activeTab.value = index;
    const tabScroll = tabScrollRef.value;
    const tabItems = tabScroll.querySelectorAll('.tab-item');
    const clickedTab = tabItems[index];

    const containerWidth = tabScroll.offsetWidth;
    const tabWidth = clickedTab.offsetWidth;
    // 使用 getBoundingClientRect 获取更准确的位置
    const tabRect = clickedTab.getBoundingClientRect();
    const containerRect = tabScroll.getBoundingClientRect();
    const tabOffsetLeft = tabRect.left - containerRect.left + tabScroll.scrollLeft;

    // 计算需要滚动到的位置，使点击的 tab 居中
    let scrollTo = tabOffsetLeft - (containerWidth - tabWidth) / 2;

    // 确保滚动位置不会小于 0
    scrollTo = Math.max(0, scrollTo);
    // 确保滚动位置不会超过最大可滚动距离
    const maxScroll = tabScroll.scrollWidth - containerWidth;
    scrollTo = Math.min(scrollTo, maxScroll);

    // 平滑滚动到计算的位置
    tabScroll.scrollTo({
        left: scrollTo,
        behavior: 'smooth'
    });
}

// 更新商品数据
async function updateGoods() {
    goodsStore.getGoodsList()
}

// 订单已结算，清除商品所有数字
function clearDot() {
    goodsStore.goodsList.value.map(item => {
        item.map(val => {
            val.orderCount = 0
        })
    })
    updateGoods()
}

const showEditor = ref(false)
const goodEditorType = ref(0) // 0 上下架 1售罄
const goodEditorItem = ref({})
const goodEditorLoading = ref(false)
const showGoodEditor = ref(false)

const goodEditorEmun = ref({
    0: '下架',
    1: '售罄'
})

// 编辑商品
async function goodEditor(item, t) {
    try {
        // if (t == 0) {
        //     await staffPermission('yun_xu_shang_xia_jia_shang_pin')
        // } else if (t == 1) {
        //     await staffPermission('yun_xu_shou_qing_shang_pin')
        // }
        goodEditorItem.value = item
        if (item.isSoldStock) {
            showCloseSell.value = true
        } else {
            goodEditorType.value = t
            showGoodEditor.value = true
        }
    } catch (error) {
        console.log(error);
    }
}

// 关闭售罄
const showCloseSell = ref(false)
const closeSellLoading = ref(false)
async function closeSellHandle() {
    try {
        closeSellLoading.value = true
        await markIsSoldOut({
            type: 'product',
            id: goodEditorItem.value.id,
            isSoldOut: 0
        })
        showCloseSell.value = false
        ElMessage({
            type: 'success',
            message: '操作成功',
        })
        updateGoods()
    } catch (error) {
        console.log(error);
    }
    closeSellLoading.value = false
}

// 上架商品
const showPutaway = ref(false)
const showPutawayLoading = ref(false)

async function showPutawayHandle(item) {
    try {
        // await staffPermission('yun_xu_shang_xia_jia_shang_pin')
        goodEditorItem.value = item
        showPutaway.value = true
    } catch (error) {
        console.log(error);
    }
}

// 确认上架操作
async function putawayHandle(item) {
    try {
        showPutawayLoading.value = true
        await productOnOff({
            type: 'product',
            id: goodEditorItem.value.id,
            isSale: 1
        })
        showPutaway.value = false
        ElMessage({
            type: 'success',
            message: '操作成功',
        })
        updateGoods()
    } catch (error) {
        console.log(error);
    }
    showPutawayLoading.value = false
}

// 确认操作
async function goodEditorConfirm() {
    try {
        goodEditorLoading.value = true

        if (goodEditorType.value == 0) {
            // 下架商品
            await productOnOff({
                type: 'product',
                id: goodEditorItem.value.id,
                isSale: 0
            })
        } else if (goodEditorType.value == 1) {
            await markIsSoldOut({
                type: 'product',
                id: goodEditorItem.value.id,
                isSoldOut: 1
            })
        }

        showGoodEditor.value = false
        ElMessage({
            type: 'success',
            message: '操作成功',
        })
        updateGoods()
    } catch (error) {
        console.log(error);
    }
    goodEditorLoading.value = false
}

// 显示修改库存
const goodsEditorStockItem = ref(0)
const showGoodsEditorStock = ref(false)
const goodsEditorStockNumber = ref(0)
const goodsEditorStockLoading = ref(false)
async function goodStockNumberHandle(item) {
    // if (item.isDistribute == 0 && item.typeEnum == 'sku') {
    //     ElMessage({
    //         type: 'warning',
    //         message: '未开启共享库存无法修改',

    //         
    //     })
    // } else {
    //     goodsEditorStockItem.value = item
    //     goodsEditorStockNumber.value = item.stockNumber
    //     showGoodsEditorStock.value = true
    // }
    try {
        await staffPermission('yun_xu_xiu_gai_shang_pin_ku_cun')
        goodsEditorStockItem.value = item
        goodsEditorStockNumber.value = item.stockNumber
        showGoodsEditorStock.value = true
    } catch (error) {
        console.log(error);
    }
}

// 确认修改库存
async function goodsEditorStockConfirm() {
    try {
        goodsEditorStockLoading.value = true
        await productStock({
            shopId: store.userInfo.shopId,
            productId: goodsEditorStockItem.value.id,
            stock: goodsEditorStockNumber.value
        })
        showGoodsEditorStock.value = false
        ElMessage({
            type: 'success',
            message: '操作成功',

        })
        updateGoods()
    } catch (error) {
        console.log(error);
    }
    goodsEditorStockLoading.value = false
}

// 判断商品是否在可售时间内
function isProductAvailable(sellDaysStr, startTimeStr, endTimeStr) {
    // 将后端返回的字符串转换为数组
    const sellDays = sellDaysStr.split(',');
    const now = dayjs();
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    const currentDay = days[now.day()];

    // console.log('当前日期:', currentDay);
    // console.log('可售日期列表:', sellDays);

    // 检查当前周几是否在可售周几列表中 
    if (!sellDays.includes(currentDay)) {
        // console.log('当前日期不在可售日期列表中');
        return false;
    }

    const startTime = dayjs(`${now.format('YYYY-MM-DD')} ${startTimeStr}`);
    let endTime = dayjs(`${now.format('YYYY-MM-DD')} ${endTimeStr}`);

    // 处理跨天情况
    if (endTime.isBefore(startTime)) {
        endTime = endTime.add(1, 'day');
    }

    // console.log('当前时间:', now.format('YYYY-MM-DD HH:mm:ss'));
    // console.log('开始时间:', startTime.format('YYYY-MM-DD HH:mm:ss'));
    // console.log('结束时间:', endTime.format('YYYY-MM-DD HH:mm:ss'));

    const isInRange = now.isBetween(startTime, endTime, null, '[)');
    // console.log('当前时间是否在可售时间范围内:', isInRange);

    return isInRange;
}
defineExpose({
    updateGoods,
    clearDot,
    showPackage
})

onMounted(() => {
    if (goodsStore.categoryList.length) {
        tabContentAni(goodsStore.categoryIndex)
    }
    // console.log(isProductAvailable("Friday", '17:00:00', '02:00:00'));
})
</script>

<style scoped lang="scss">
.swiper_box {
    height: 100%;

    .slide_item {
        width: 100%;
        height: 100%;
    }
}

.loading_wrap {
    display: flex;
    justify-content: center;
    padding: 20px 0;
    color: #999;

    .loading {
        display: flex;
        align-items: center;

        .icon {
            font-size: 20px;
        }
    }
}

.popover_wrap {
    display: flex;
    flex-wrap: wrap;
    gap: var(--el-font-size-base);
    padding: var(--el-font-size-base) 0;

    :deep(.el-button) {
        margin-left: 0;
    }
}

.header {
    display: flex;
    height: var(--el-component-size-large);
    justify-content: space-between;
    border-bottom: 1px solid #ececec;
}

.menus {
    flex: 1;
    display: flex;
    padding: 0 10px;
    overflow-x: auto;
    width: 100px;

    .item {
        padding: 0 10px;
        display: flex;
        align-items: center;
        position: relative;
        white-space: nowrap;

        .icon {
            margin-right: 4px;
            animation: rotateAni 1s linear infinite;
            animation-play-state: paused;

            @keyframes rotateAni {
                0% {
                    transform: rotate(0deg);
                }

                100% {
                    transform: rotate(360deg);
                }
            }

            &.active {
                animation-play-state: running;
            }
        }

        .svg_icon {
            display: none;
            fill: var(--primary-color);
            width: 24px;
            height: 24px;
            position: absolute;
            bottom: -8px;
            left: 50%;
            margin-left: -12px;
        }

        span {
            font-size: var(--el-font-size-base);
        }

        &.active {
            .icon {
                color: var(--primary-color);
            }

            .svg_icon {
                display: block;
            }

            span {
                color: var(--primary-color);
            }
        }
    }
}

.all {
    width: calc(var(--el-component-size-large) + 10px);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    flex-shrink: 0;

    &::before {
        content: "";
        height: 60%;
        border-left: 1px solid #ececec;
        position: absolute;
        left: 0;
        top: 20%;
    }

    .icon {
        color: #555;
        font-size: 20px;
        transition: all .2s ease-in-out;

        &.active {
            transform: rotate(45deg)
        }
    }
}

.search_wrap {
    display: flex;
    justify-content: space-between;
    padding: var(--el-font-size-base);

    .left {
        display: flex;
    }

    .right {
        display: flex;
        gap: 10px;
    }
}

.shop_list {
    // max-height: calc(100vh - 40px - 80px - 40px);
    height: calc(100vh - 40px - 80px - 28px);
    // overflow-y: auto;
    // display: flex;
    // flex-wrap: wrap;
    padding: 0 10px;

    &.img {
        .item_wrap {
            width: 25%;
        }
    }

    .item_wrap {
        float: left;
        width: 20%;
        height: 33.333%;
        padding: 0 5px;
        padding-bottom: 10px;

        .item {
            height: 100%;
            border: 1px solid #ececec;
            border-radius: 10px;
            overflow: hidden;
            position: relative;

            .more {
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 999;
                background-color: rgba(0, 0, 0, .6);
                backdrop-filter: blur(2px);
                border-radius: 10px;

                .ul {
                    height: 100%;
                    padding: 20px;
                    display: flex;
                    justify-content: center;
                    flex-direction: column;

                    .li {
                        display: flex;
                        align-items: center;
                        color: #fff;
                        padding: 8px 0;

                        &:last-child {
                            border-top: 1px solid rgba(255 255 255 / 20%);
                            color: #ececec;
                        }
                    }
                }
            }

            &:hover {
                cursor: pointer;
            }

            .dot {
                padding: 0 8px;
                background-color: var(--el-color-danger);
                color: #fff;
                border-radius: 20px;
                position: absolute;
                top: 2px;
                right: 2px;
                z-index: 1;
                font-size: 12px;
            }

            .cover {
                width: 100%;
                height: 60%;
                position: relative;

                .xxzk {
                    padding: 1px 3px 2px 6px;
                    border-radius: 0 0 0 10px;
                    position: absolute;
                    top: 0;
                    right: 0;
                    z-index: 10;
                    font-size: 12px;
                    color: #fff;
                    background-color: var(--el-color-danger);
                }

                .weight {
                    position: absolute;
                    left: 4px;
                    bottom: 4px;
                    color: #fff;
                    font-size: 12px;
                    padding: 2px 6px;
                    background-color: rgba(250, 82, 82);
                    border-radius: 4px;
                }

                .el_img {
                    width: 100%;
                    height: 100%;
                    background-color: #efefef;
                    position: absolute;
                    top: 0;
                    left: 0;
                }

                .sell_out {
                    width: 100%;
                    height: 100%;
                    position: absolute;
                    top: 0;
                    left: 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: rgba(0, 0, 0, 0.5);
                    // backdrop-filter: blur(2px); 
                    z-index: 10;

                    .sell_out_icon {
                        $size: 80px;
                        width: $size;
                        height: $size;
                        object-fit: cover;
                    }
                }
            }

            .name {
                padding: 0 10px;
                height: 20%;
                display: flex;
                align-items: center;
                // margin-top: 20px;

                span {
                    font-weight: bold;
                }
            }

            .item_empty {
                height: 30px;
            }

            .price {
                height: 20%;
                padding: 6px 10px;
                background-color: var(--primary-color);
                position: relative;

                .price_warp {
                    display: flex;
                    align-items: center;

                    .del {
                        color: #fff;
                        position: relative;
                        top: 2px;
                        margin-right: 4px;
                    }
                }

                span {
                    color: #fff;
                    font-weight: bold;
                }

                .show_more_btn {
                    width: 40px;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    position: absolute;
                    top: 0;
                    right: 0;
                    z-index: 1;
                    color: #fff;
                }
            }
        }
    }
}

.dialog {

    .content {
        padding-bottom: 20px;
    }

    .footer_wrap {
        display: flex;
        gap: 20px;

        .btn {
            flex: 1;
        }
    }
}

.remark_list {
    display: flex;
    gap: 10px;
    margin-top: 10px;

    .item {
        padding: 0 10px;
        border: 1px solid #ddd;
        color: #999;
        border-radius: 4px;
    }
}
</style>