<template>
    <div class="order-console">
        <el-drawer
            v-model="showOrderConsole"
            title="开始点餐"
            direction="rtl"
            size="100%"
            :before-close="beforeClose"
        >
            <div class="p-2 md:w-2/6 w-full md:h-full h-auto float-left">
                <el-card shadow="never" :body-style="{ padding: '10px' }">
                    <template #header>
                        <div
                            class="justify-between items-center flex text-xl font-semibold font-mono"
                        >
                            <span>{{ (data.deskId > 0 ? '餐桌号：': '取餐号：') + data.deskName }}</span>
                            <div class="flex items-center">
                                <span v-if="data.deskId > 0">{{ data.currentNum + '/' + data.deskCap }}</span>
                                <el-icon class="ml-2 cursor-pointer" @click="refreshdishes">
                                    <Refresh />
                                </el-icon>
                            </div>
                        </div>
                    </template>
                    <el-input
                        v-model="params.remark"
                        maxlength="100"
                        placeholder="订单备注"
                        show-word-limit
                        type="textarea"
                    />
                    <el-divider />
                    <el-scrollbar ref="scrollbarRef" class="scrollbar">
                        <div ref="innerRef" v-loading="orderLoading">
                            <el-empty
                                v-if="data.selectGoods.length == 0 ? true : false"
                                description="啥也没有，快点击商品添加吧"
                            />
                            <!-- 已选商品 -->
                            <goods-item
                                v-for="item in data.selectGoods"
                                :key="item"
                                class="scrollbar-demo-item"
                                :goods-item="item"
                                @add="add"
                                @reduce="reduce"
                            >
                            </goods-item>
                        </div>
                    </el-scrollbar>
                    <div class="flex justify-between items-center mt-2">
                        <div
                            class="flex-1 h-12 border rounded-md flex items-center justify-center cursor-pointer relative mr-2"
                            :class="{
                                'border-primary text-primary bg-[#EDEFFF]':
                                    params.diningMethods === 1
                            }"
                            @click="params.diningMethods = 1"
                        >
                            <span>店内就餐</span>
                            <el-icon
                                v-if="params.diningMethods === 1"
                                class="absolute right-0 bottom-0 text-primary"
                                style="font-size: 16px"
                            >
                                <Check />
                            </el-icon>
                        </div>
                        <div
                            class="flex-1 h-12 border rounded-md flex items-center justify-center cursor-pointer relative ml-2"
                            :class="{
                                'border-primary text-primary bg-[#EDEFFF]':
                                    params.diningMethods === 2
                            }"
                            @click="params.diningMethods = 2"
                        >
                            <span>打包外带</span>
                            <el-icon
                                v-if="params.diningMethods === 2"
                                class="absolute right-0 bottom-0 text-primary"
                                style="font-size: 16px"
                            >
                                <Check />
                            </el-icon>
                        </div>
                    </div>
                </el-card>
            </div>

            <div class="p-2 md:w-1/6 w-full md:h-full h-auto float-left flex-wrap">
                <el-scrollbar>
                    <div class="flex flex-col space-y-2 p-2">
                        <el-button
                            size="large"
                            :type="buttonType == 'all' ? 'primary' : ''"
                            @click="clickSortButton('all')"
                            text
                            bg
                            >全部商品</el-button
                        >
                        <el-button
                            class="cate-button"
                            v-for="button in dishCate"
                            :key="button.name"
                            size="large"
                            style="margin-left: 0"
                            :type="buttonType == button.name ? 'primary' : ''"
                            @click="clickSortButton(button.name)"
                            text
                            bg
                            >{{ button.name }}</el-button
                        >
                    </div></el-scrollbar
                >
            </div>
            <div class="p-2 md:w-1/2 w-full md:h-full h-auto float-left flex-wrap">
                <div class="w-full h-auto">
                    <div class="justify-end flex">
                        <el-input
                            v-model="search"
                            class="md:w-40 w-1/2 m-2"
                            placeholder="搜索菜品名字"
                            :suffix-icon="Search"
                        />
                    </div>
                </div>
                <div class="w-full md:h-5/6 h-auto inline-block" style="height: calc(100% - 40px)">
                    <!-- 菜单内容 -->
                    <el-scrollbar height="100%">
                        <div
                            v-for="item in dishList"
                            :key="item.id"
                            class="float-left md:w-40 w-1/2 md:h-38 h-auto p-1"
                            style="user-select: none"
                        >
                            <a
                                href="javascript:void(0);"
                                @click="addGoods(item)"
                                :class="{ 'pointer-events-none': item.isShow == 0 }"
                                ><el-card
                                    shadow="never"
                                    :body-style="{ padding: '0px' }"
                                    :class="{ relative: item.isShow == 0 }"
                                >
                                    <div
                                        v-if="item.isShow == 0"
                                        class="absolute inset-0 bg-white z-10 pointer-events-none flex items-center justify-center select-none"
                                        style="opacity: 0.5; color: red; font-size: 25px"
                                    >
                                        <span class="text-gray-600 font-medium">已售罄</span>
                                    </div>
                                    <el-image
                                        style="width: 100%; height: 100px"
                                        :src="item.image"
                                        fit="cover"
                                    />
                                    <div class="text-2xs font-semibold p-1">
                                        <p>{{ item.title }}</p>
                                        <p style="color: coral">
                                            {{ item.summary + '元/份' }}
                                        </p>
                                    </div>
                                </el-card></a
                            >
                        </div>
                    </el-scrollbar>
                </div>
            </div>
            <template #footer>
                <div class="flex items-center px-4 space-x-5">
                    <div class="relative mr-auto">
                        <el-badge :value="orderData.sumNumSum" :max="99" class="mr-3">
                            <el-icon size="50" style="width: 32px; height: 32px; font-size: 32px"
                                ><ShoppingCart
                            /></el-icon>
                        </el-badge>
                        <span class="ml-5 text-base"
                            >合计: ¥{{ orderData.sumPriceSum.toFixed(2) }}</span
                        >
                    </div>
                    <el-button
                        type="primary"
                        class="action-btn !w-[50px] !h-[40px]"
                        @click="toEmpty()"
                        :disabled="data.selectGoods.length <= 0"
                        >清空</el-button
                    >
                    <el-badge :value="params.couponId ? 1 : ''" :hidden="!params.couponId">
                        <el-button
                            type="primary"
                            class="action-btn !w-[200px] !h-[40px]"
                            @click="showCouponDialog = true"
                        >
                            优惠 {{ params.couponAmount !== '-' ? `¥${params.couponAmount}` : '' }}
                        </el-button>
                    </el-badge>
                    <el-button
                        type="danger"
                        class="submit-btn !w-[300px] !h-[40px]"
                        @click="submit()"
                        >去结算 ¥{{ orderData.payAmount }}</el-button
                    >
                </div>
            </template>
        </el-drawer>
    </div>

    <el-dialog
        v-model="specDialogVisible"
        title="选择规格"
        width="50%"
        :before-close="handleSpecDialogClose"
    >
        <div v-if="currentItem">
            <div
                v-for="(specs, name) in groupSpecsByName(currentItem.specsList)"
                :key="name"
                class="mb-4"
            >
                <div class="font-bold mb-2">{{ name }}</div>
                <div class="flex flex-wrap gap-2">
                    <div
                        v-for="spec in specs"
                        :key="spec.id"
                        class="flex-1 h-12 border rounded-md flex items-center justify-center cursor-pointer relative"
                        :class="{
                            'border-primary text-primary bg-[#EDEFFF]':
                                selectedSpecs[name] === spec.id
                        }"
                        @click="selectedSpecs[name] = spec.id"
                    >
                        <span>{{ spec.value }}</span>
                        <el-icon
                            v-if="selectedSpecs[name] === spec.id"
                            class="absolute right-0 bottom-0 text-primary"
                            style="font-size: 16px"
                        >
                            <Check />
                        </el-icon>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="specDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSpecConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 优惠券弹框 -->
    <el-dialog
        v-model="showCouponDialog"
        title="选择优惠券"
        width="50%"
        :close-on-click-modal="false"
    >
        <div class="mb-4" style="margin-top: 5px">
            <div class="flex items-center">
                <el-input
                    v-model="data.phone"
                    placeholder="请输入手机号查询优惠券"
                    class="flex-1"
                    maxlength="11"
                >
                    <template #append>
                        <el-button
                            :icon="Search"
                            @click="searchUserCoupons"
                            :loading="searchLoading"
                        />
                    </template>
                </el-input>
            </div>
        </div>
        <div class="mt-2 coupon-container" v-loading="searchLoading">
            <el-scrollbar height="200px">
                <el-empty
                    v-if="!data.couponList.length"
                    description="暂无可用优惠券"
                    :image-size="60"
                />
                <div v-else class="coupon-list" style="padding: 7px">
                    <div
                        v-for="coupon in data.couponList"
                        :key="coupon.id"
                        class="coupon-item"
                        :class="{
                            'is-selected': params.couponId === coupon.ticketRecordId,
                            'is-disabled': orderData.sumPriceSum < (coupon.consumeScore / 100) || orderData.sumPriceSum < (coupon.useThreshold / 100)
                        }"
                        @click="handleCouponClick(coupon)"
                    >
                        <div class="left-part">
                            <div class="amount-wrapper">
                                <div class="amount">{{ coupon.consumeScore / 100 }}</div>
                            </div>
                            <!-- <div class="condition">满{{ coupon.consumeScore / 100 }}可用</div> -->
                        </div>
                        <div class="right-part">
                            <div class="name">
                              {{ coupon.productName }}
                              <el-tag v-if="coupon.useThreshold">满{{coupon.useThreshold  / 100}}减</el-tag>
                            </div>
                            <div class="date">券码:{{ coupon.ticketNo }}</div>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="ticketConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog
        v-model="scanDialogVisible"
        title="请引导顾客扫码支付"
        width="300px"
        center
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <div class="text-center">
            <img
                src="@/assets/images/scan.gif"
                alt="扫码"
                class="mx-auto mb-4"
                style="width: 150px"
            />
            <b style="font-size: 20px">金额 {{ orderData.payAmount }} 元</b>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="scanDialogVisible = false">取消支付</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="payingDialogVisible"
        title="支付处理中"
        width="300px"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <div class="flex flex-col items-center justify-center py-4">
            <el-icon class="is-loading mb-4" :size="32">
                <Loading />
            </el-icon>
            <p class="text-gray-600">正在支付中，请不要关闭或退出界面</p>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ElScrollbar } from 'element-plus'
import { Search, ShoppingCart } from '@element-plus/icons-vue'
import goodsItem from './goodsItem.vue'
import {
    dishAdd,
    dishCateAll,
    dishDec,
    dishDel,
    dishInc,
    dishListAll,
    toEmptyy,
    orderSubmit,
    deskOrderedDishListAll,
    searchCoupons,
    orderPay,
    queryPayStatus,
    cancelOrder
} from '@/api/order'
import feedback from '@/utils/feedback'
// const route = useRoute()
const innerRef = ref<HTMLDivElement>()
const dishCate = ref<any[]>([])
const dishList = ref<any[]>([])
const showCouponDialog = ref(false)
let dishListall: any[] = []
const orderLoading = ref(false)
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()
const search = ref('')
const emit = defineEmits(['init'])
const buttonType = ref('all')
const showOrderConsole = ref(false)

const scanDialogVisible = ref(false)
const scanCode = ref('')

// 添加支付中对话框的控制变量
const payingDialogVisible = ref(false)
const data = reactive<any>({
    deskId: null,
    deskName: '',
    deskCap: 0,
    currentNum: 0,
    selectGoods: [],
    oldGoods: [],
    phone: '', // 手机号
    couponList: [], // 优惠券列表
    canScan: false
})
const orderData = reactive<any>({
    priceSum: 0,
    sumPriceSum: 0,
    numSum: 0,
    sumNumSum: 0,
    payAmount: 0 // 新增支付金额
})
const params = reactive({
    remark: '', //订单备注
    number: '', //订单id
    userId: '', //用户id
    couponId: '', //优惠券id
    couponAmount: '-',
    diningMethods: 1, // 就餐方式：1店内就餐 2打包外带
})
const submit = () => {
    //出单
    if (data.selectGoods.length == 0) {
        feedback.alert('未点菜品！')
        return false
    }
    if (orderData.payAmount <= 0) {
        feedback.alert('支付金额需大于0！')
        return false
    }
    feedback.loading('正在出单...')
    orderSubmit({
        ...params,
        userId: params.userId || null,
        couponId: params.couponId || null,
        mealCode: data.deskName || null
    })
        .then(() => {
            // data.selectGoods.length = 0
            // orderData.priceSum = 0
            // orderData.numSum = 0
            //把所有餐品的状态修改为出单
            data.selectGoods.forEach((good: { status: number }) => {
                good.status = 1
            })
            // emit('init')
            feedback.closeLoading()
            // feedback.notifySuccess('出单成功')
            checkout()
        }).catch((e)=>{
          if (e.msg === "券不存在" || e.msg === "券不存在或已过期") {
            params.couponId = null
            params.couponAmount = '-'
            // 计算支付金额
            orderData.payAmount = Number(orderData.sumPriceSum).toFixed(2)
            searchUserCoupons()
          }

    })
        .finally(() => {
            feedback.closeLoading()
        });
}

// 添加扫码事件监听函数
const handleScanInput = (event: KeyboardEvent) => {

  console.log("event.key", event.key)
  if (event.key === 'Enter') {
    document.removeEventListener('keydown', handleScanInput)
    if (!data.canScan) {
      feedback.notifyWarning('正在处理支付，请勿重复扫码')
      return
    }
    const code = scanCode.value
    console.log('扫码内容：', code)
    payingDialogVisible.value = true // 显示支付中对话框

    // 修改支付处理逻辑
    orderPay({ oid: params.number, code: code })
        .then((res) => {
          console.log(res)
          // 实际上支付成功之后,res返回的是[],如果不是实时成功,返回的是个对象, 形如:{orderId: '123456789', sn: '7895004131583689'}
          if (res == null || res.length == 0) {
            feedback.notifySuccess('成功结账' + orderData.payAmount + '元')
            scanDialogVisible.value = false
            payingDialogVisible.value = false // 隐藏支付中对话框
            showOrderConsole.value = false
            emit('init')
          } else {
            console.log('支付中')
            return queryPayStatusWithRetry(res)
                .then((paySuccess) => {
                  if (paySuccess) {
                    feedback.notifySuccess('成功结账' + orderData.payAmount + '元')
                    scanDialogVisible.value = false
                    payingDialogVisible.value = false // 隐藏支付中对话框
                    showOrderConsole.value = false
                    emit('init')
                  }
                })
          }
        })
        .catch((e) => {
          console.log("=====---", e)
          // 支付失败
          payingDialogVisible.value = false // 隐藏支付中对话框
          feedback.notifySuccess('支付失败，请重试!')
            data.canScan = true
            scanDialogVisible.value = true
            // 添加键盘事件监听
            setTimeout(()=>{
              scanCode.value = ''
              document.removeEventListener('keydown', handleScanInput)
              document.addEventListener('keydown', handleScanInput)
            }, 2000)
          })
    scanCode.value = ''
  } else {
    scanCode.value += event.key
  }
}

// 定义查询支付状态的函数
const queryPayStatusWithRetry = (data): Promise<boolean> => {
    const intervals = [3000, 5000, 10000, 10000, 10000, 10000, 10000]
    let currentIndex = 0
    payingDialogVisible.value = true

    const tryQuery = () => {
        return new Promise<boolean>((resolve) => {
            setTimeout(() => {
                queryPayStatus({ orderId: data.orderId, sn: data.sn })
                    .then((result) => {
                        if (
                            result.result_code == '200' &&
                            result.biz_response.data.order_status == 'SUCCESS'
                        ) {
                            resolve(true)
                        } else if (currentIndex < intervals.length - 1) {
                            currentIndex++
                            tryQuery().then(resolve)
                        } else {
                            resolve(false)
                        }
                    })
                    .catch(() => {
                        if (currentIndex < intervals.length - 1) {
                            currentIndex++
                            tryQuery().then(resolve)
                        } else {
                            resolve(false)
                        }
                    })
            }, intervals[currentIndex])
        })
    }

    return tryQuery().then((success) => {
        payingDialogVisible.value = false
        if (!success) {
            return cancelOrder({ orderId: data.orderId, sn: data.sn })
                .then(() => {
                    feedback.notifyWarning('支付超时，已自动撤销本次支付')
                    return false
                })
                .catch((error) => {
                    console.error('撤单失败:', error)
                    feedback.notifyError('支付失败，请重试')
                    return false
                })
        }
        return success
    })
}

const ticketConfirm = () => {
    if (data.phone == '') {
        params.couponId = null
        params.couponAmount = '-'
        params.userId = null
        // 计算支付金额
        orderData.payAmount = Number(orderData.sumPriceSum).toFixed(2)
    }
    showCouponDialog.value = false
}

const checkout = () => {
    refreshdishes()
    //结账
    console.warn('***结账***')
    // if (data.selectGoods || data.selectGoods.length == 0) {
    //     feedback.notify('请点击商品开始点单吧!')
    //     return false
    // }
    // feedback.confirm('结账金额为' + orderData.payAmount + '，确定要结账吗？').then(() => {

    scanCode.value = ''
    data.canScan = true
    scanDialogVisible.value = true
    // 添加键盘事件监听

    document.removeEventListener('keydown', handleScanInput)
    document.addEventListener('keydown', handleScanInput)
    // })
}
// 添加优惠券点击处理方法
const handleCouponClick = (coupon: any) => {
    if (orderData.sumPriceSum < coupon.consumeScore / 100 || orderData.sumPriceSum < (coupon.useThreshold / 100)) {
        return
    }
    if (params.couponId === coupon.ticketRecordId) {
        params.couponId = ''
        params.couponAmount = '-'
        orderData.payAmount = orderData.sumPriceSum
        return
    }
    params.couponId = coupon.ticketRecordId
    params.couponAmount = (coupon.consumeScore / 100).toFixed(2)
    // 计算支付金额
    orderData.payAmount = (
        Number(orderData.sumPriceSum) - Number(coupon.consumeScore / 100)
    ).toFixed(2)
}

const open = (item: any, num?: number, orderNumber?: any) => {
  console.log('***open***', item, num, orderNumber)
    data.couponList = []
    showOrderConsole.value = true
    data.deskId = item.id
    data.deskName = item.name
    data.deskCap = item.num
    data.currentNum = item.userNum ? item.userNum : num
    params.number = item.ordersId ? item.ordersId : orderNumber
    params.userId = ''
    params.couponId = ''
    //查询当前订单下的所有菜品
    deskOrderedDishListAll({ id: params.number }).then((res) => {
        res.forEach((good: { id: number; ordersDishId: number }) => {
            good.ordersDishId = good.id
        })
        console.log('***deskOrderedDishListAll***', res)
        data.selectGoods = res
        data.oldGoods = JSON.parse(JSON.stringify(res)) //记录下进入时当前餐桌已有的食物
        if (res.length > 0) {
            data.phone = res[0].mobile
            params.remark = res[0].remark
            params.userId = res[0].userId || null
            params.couponId = res[0].ticketId || null
            params.diningMethods = res[0].diningMethods || 1
            if (params.couponId && params.userId) {
                searchUserCoupons()
            }
            params.couponAmount = res[0].ticketAmount
                ? Number(res[0].ticketAmount / 100).toFixed(2)
                : '-'
            const _list = res.filter((it: { status: number }) => it.status != 1) //找到没有出单的餐品来计算价格
            orderData.priceSum = _list.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.summary * currentValue.num,
                0
            )
            orderData.numSum = _list.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.num,
                0
            )
            //所有餐品的总价以及总数量
            orderData.sumPriceSum = res.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.summary * currentValue.num,
                0
            )
            orderData.sumNumSum = res.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.num,
                0
            )
            orderData.payAmount = Number(
                orderData.sumPriceSum -
                    (params.couponAmount === '-' ? 0 : Number(params.couponAmount))
            ).toFixed(2)
        } else {
            orderData.priceSum = 0
            orderData.numSum = 0
            orderData.sumPriceSum = 0
            orderData.sumNumSum = 0
            data.phone = ''
            params.remark = ''
            params.userId = ''
            params.couponId = ''
            params.couponAmount = '-'
            orderData.payAmount = 0
            data.couponList = []
        }
    })
    dishList.value = dishListall //显示所有菜品
}

const refreshdishes = async () => {
    orderLoading.value = true
    await deskOrderedDishListAll({ id: params.number })
        .then((res) => {
            res.forEach((good: { id: number; ordersDishId: number }) => {
                good.ordersDishId = good.id
            })
            console.log('***refreshdishes***', res)
            data.selectGoods = res
            console.log('***res.length***', res.length)
            if (res.length > 0) {
                // const _list = res.filter((it: { status: number }) => it.status != 1) //找到没有出单的餐品来计算价格
                const _list = res
                orderData.priceSum = _list.reduce(
                    (accumulator: number, currentValue: { summary: number; num: number }) =>
                        accumulator + currentValue.summary * currentValue.num,
                    0
                )
                orderData.numSum = _list.reduce(
                    (accumulator: number, currentValue: { summary: number; num: number }) =>
                        accumulator + currentValue.num,
                    0
                )
                //所有餐品的总价以及总数量
                orderData.sumPriceSum = res.reduce(
                    (accumulator: number, currentValue: { summary: number; num: number }) =>
                        accumulator + currentValue.summary * currentValue.num,
                    0
                )
                orderData.sumNumSum = res.reduce(
                    (accumulator: number, currentValue: { summary: number; num: number }) =>
                        accumulator + currentValue.num,
                    0
                )
                console.log(
                    '***res[0].payAmount***',
                    res[0].payAmount,
                    Number(res[0].payAmount / 100).toFixed(2)
                )
                orderData.payAmount = res[0].payAmount
                    ? Number(res[0].payAmount / 100).toFixed(2)
                    : Number(orderData.sumPriceSum).toFixed(2)
                console.log('***orderData***', orderData)
            } else {
                orderData.priceSum = 0
                orderData.numSum = 0
                orderData.sumPriceSum = 0
                orderData.sumNumSum = 0
                orderData.payAmount = 0
            }
        })
        .finally(() => {
            orderLoading.value = false
        })
}
watch(search, (value) => {
    if (!value) {
        if (buttonType.value == 'all') {
            dishList.value = dishListall
        } else {
            dishList.value = dishListall.filter((ele) => {
                return ele.category == buttonType.value
            })
        }
        console.warn('***watch***', value, buttonType.value, dishList.value)
    } else {
        dishList.value = dishList.value.filter((ele) => {
            return ele.title.includes(value)
        })
    }
})
const clickSortButton = (name: any) => {
    //重复点击不处理
    if (buttonType.value == name) {
        return false
    }
    search.value = ''
    buttonType.value = name
    if (name == 'all') {
        dishList.value = dishListall
    } else {
        dishList.value = dishListall.filter((ele) => {
            return ele.category == name
        })
    }
}
//清空订单下的菜品
const toEmpty = () => {
    if (data.selectGoods.length != 0) {
        orderLoading.value = true
        toEmptyy({ id: params.number }).finally(() => {
            //清空未出单的餐品-保留出单餐品
            data.selectGoods = []
            orderData.sumPriceSum = data.selectGoods.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.summary * currentValue.num,
                0
            )
            orderData.sumNumSum = data.selectGoods.reduce(
                (accumulator: number, currentValue: { summary: number; num: number }) =>
                    accumulator + currentValue.num,
                0
            )
            // data.selectGoods.length = 0
            orderData.priceSum = 0
            orderData.numSum = 0
            // orderData.sumPriceSum = 0
            // orderData.sumNumSum = 0

            // 检查优惠券条件
            if (params.couponId && orderData.sumPriceSum < Number(params.couponAmount)) {
                // 如果订单金额小于优惠券金额，清空优惠券
                params.couponId = ''
                params.couponAmount = '-'
                orderData.payAmount = orderData.sumPriceSum
            }
            orderData.payAmount = Number(
                orderData.sumPriceSum -
                    (params.couponAmount === '-' ? 0 : Number(params.couponAmount))
            ).toFixed(2)
            orderLoading.value = false
        })
    }
}
const isEqual = (obj1: { [x: string]: any } | null, obj2: { [x: string]: any } | null) => {
    // 如果两个对象是同一个引用，直接返回 true
    if (obj1 === obj2) return true

    // 如果其中一个为 null 或者不是对象，返回 false
    if (obj1 === null || typeof obj1 !== 'object' || obj2 === null || typeof obj2 !== 'object') {
        return false
    }

    // 获取两个对象的键
    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)

    // 如果键的数量不同，返回 false
    if (keys1.length !== keys2.length) return false

    // 遍历所有键，递归比较每个键的值
    for (const key of keys1) {
        if (!keys2.includes(key) || !isEqual(obj1[key], obj2[key])) {
            return false
        }
    }

    // 如果所有键的值都相等，返回 true
    return true
}
const beforeClose = () => {
    //data.oldGoods
    // if(isEqual(data.selectGoods,data.oldGoods)){
    //     showOrderConsole.value = false;
    //     emit('init')
    //     return false;
    // }
    // if (data.selectGoods && data.selectGoods.length > 0) {
    //     feedback.confirm('所点菜品信息将不被保存，确认关闭？').then(() => {
    //         toEmpty()
    //     })
    // }
    showOrderConsole.value = false
    search.value = ''
    buttonType.value = 'all'
    emit('init')
}
const add = (item: any) => {
    // addGoods(item)
    console.log('***add***', item)
    orderLoading.value = true
    dishInc({ id: item.ordersDishId })
        .then(() => {
            data.selectGoods[data.selectGoods.indexOf(item)].num++
            addHandle(item)
        })
        .finally(() => {
            orderLoading.value = false
            nextTick(() => {
                scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
            })
        })
}
// 添加新的响应式变量
const specDialogVisible = ref(false)
const currentItem = ref<any>(null)
const selectedSpecs = ref<any>({})

// 添加新的方法
const groupSpecsByName = (specsList: any[]) => {
    const groups: any = {}
    specsList?.forEach((spec) => {
        if (!groups[spec.name]) {
            groups[spec.name] = []
        }
        groups[spec.name].push(spec)
    })
    return groups
}

const handleSpecDialogClose = () => {
    specDialogVisible.value = false
    currentItem.value = null
    selectedSpecs.value = {}
}

const handleSpecConfirm = () => {
    // 检查是否所有规格都已选择
    const allSpecsSelected = Object.keys(groupSpecsByName(currentItem.value.specsList)).every(
        (name) => selectedSpecs.value[name]
    )

    if (!allSpecsSelected) {
        feedback.msgError('请选择所有规格')
        return
    }

    // 将选中的规格ID添加到商品中
    const item = { ...currentItem.value, selectedSpecIds: Object.values(selectedSpecs.value) }
    handleAddGoods(item)
    handleSpecDialogClose()
}

// 修改 addGoods 方法
const addGoods = (item: any) => {
    if (item.specsList?.length > 0) {
        currentItem.value = item
        selectedSpecs.value = {}
        specDialogVisible.value = true
        return
    }
    handleAddGoods(item)
}

// 将原来的 addGoods 逻辑移到这个新方法中
const handleAddGoods = (item: any) => {
    console.log('handleAddGoods', item)
    orderLoading.value = true
    //查找未出单的餐品列表
    const list = data.selectGoods.filter((element: any) => {
        return element.status != 1
    })
    console.log('list', list)
    let tempGoods: string | any[] = []
    //先从历史下单但是没有结单的餐品中找出要操作的餐品
    tempGoods = list.filter((element: any) => {
        //如果有specsIds，说明是有规格的餐品
        const specsIds: number[] = []
        element.specsList?.forEach((spec: any) => {
            specsIds.push(spec.specsId)
        })
        return (
            element.artId &&
            element.artId == item.id &&
            specsIds.sort((a: number, b: number) => a - b).join(',') ==
                (item.selectedSpecIds || []).sort((a: number, b: number) => a - b).join(',')
        )
    })
    console.log('tempGoods', tempGoods)
    if (tempGoods.length == 0) {
        item.num = 1
        dishAdd({
            orderId: params.number,
            dishId: item.id,
            specsIds: (item.selectedSpecIds || []).join(',') // 将数组转换为逗号分隔的字符串
        })
            .then((res) => {
                //拿到orders_dish的id
                item.ordersDishId = res
                item.specsList = item.selectedSpecIds?.map((specId: any) => {
                    const o = item.specsList.find((spec: any) => spec.id == specId)
                    o.specsId = specId
                    return o
                })
                item.artId = item.id
                data.selectGoods.push(item)
                console.log('data.selectGoods', data.selectGoods)
                feedback.msgSuccess('成功添加商品' + item.title)
                addHandle(item)
            })
            .finally(() => {
                orderLoading.value = false
                nextTick(() => {
                    scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
                })
            })
    } else {
        dishInc({ id: tempGoods[0].ordersDishId })
            .then(() => {
                data.selectGoods[data.selectGoods.indexOf(tempGoods[0])].num++
                addHandle(item)
            })
            .finally(() => {
                orderLoading.value = false
                nextTick(() => {
                    scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
                })
            })
    }
}
//只有正常执行了接口才触发
const addHandle = (item: { summary: any }) => {
    console.warn('***addGoods-dish***', item, data.selectGoods)
    console.warn('***orderData***', orderData)
    orderData.numSum++
    orderData.sumNumSum++
    orderData.priceSum += Number(item.summary)
    orderData.sumPriceSum += Number(item.summary)
    orderData.payAmount = Number(
        orderData.sumPriceSum - (params.couponAmount === '-' ? 0 : Number(params.couponAmount))
    ).toFixed(2)
}
const reduce = (item: any) => {
    orderLoading.value = true
    //查找未出单的餐品列表
    // const list = data.selectGoods.filter((element: any) => {return element.status != 1})
    // let tempGoods: string | any[] = []
    // //先从历史下单但是没有结单的餐品中找出要操作的餐品
    // tempGoods = list.filter((element: any) => {
    //   const specsIds: number[] = [];
    //   element.specsList?.forEach((spec: any) => {
    //     specsIds.push(spec.specsId)
    //   })
    //   return element.artId && element.artId == item.artId &&
    //       specsIds.sort((a: number, b: number) => a - b).join(',') == (item.selectedSpecIds || []).sort((a: number, b: number) => a - b).join(',')
    // })
    // if(tempGoods.length==0){//历史没有，则从当次下单的餐品列表中找
    //     tempGoods = list.filter((element: any) => {
    //         return element.id == item.id && !element.artId
    //     })
    // }

    // console.log('tempGoods', tempGoods)
    console.log('data.selectGoods', data.selectGoods)
    const t = data.selectGoods.indexOf(item)
    // const n = data.selectGoods[t].num
    console.log('reduce', t, item)
    if (item.num > 1) {
        dishDec({ id: item.ordersDishId })
            .then(() => {
                data.selectGoods[t].num--
                reduceHandle(item)
            })
            .finally(() => {
                orderLoading.value = false
            })
    } else {
        //餐品数量为0，要删减该餐品
        dishDel({ id: item.ordersDishId })
            .then(() => {
                data.selectGoods.splice(t, 1)
                reduceHandle(item)
            })
            .finally(() => {
                orderLoading.value = false
            })
    }
}
//只有正常执行了接口才触发
const reduceHandle = (item: { summary: number }) => {
    console.warn('***reduce-dish***', item, data.selectGoods)
    orderData.numSum--
    orderData.sumNumSum--
    orderData.priceSum -= item.summary
    orderData.sumPriceSum -= item.summary
    orderData.payAmount = Number(
        (
            orderData.sumPriceSum - (params.couponAmount === '-' ? 0 : Number(params.couponAmount))
        ).toFixed(2)
    )
    if (orderData.priceSum <= 0) {
        orderData.priceSum = 0
    }
    if (orderData.numSum <= 0) {
        orderData.numSum = 0
    }
    if (orderData.sumPriceSum <= 0) {
        orderData.sumPriceSum = 0
    }
    if (orderData.sumNumSum <= 0) {
        orderData.sumNumSum = 0
    }
    if (orderData.payAmount <= 0) {
        orderData.payAmount = 0
    }
}
// 添加搜索用户优惠券的方法
// ... 其他代码保持不变 ...

// 添加 loading 变量
const searchLoading = ref(false)

// 修改搜索方法
const searchUserCoupons = () => {
    if (!data.phone) {
        feedback.msgError('请输入手机号')
        return
    }
    searchLoading.value = true
    searchCoupons({ mobile: data.phone })
        .then((res: any) => {
            if (res) {
                data.couponList = res ? res.couponList || [] : []
                params.userId = res ? res.userId || null : null
                if (data.couponList.length == 0) {
                    feedback.msgError('暂无可用优惠券')
                    return false
                }
            }
        })
        .finally(() => {
            searchLoading.value = false
        })
}

onMounted(() => {
    dishCateAll().then((res) => {
        dishCate.value = res
    })
    dishListAll().then((res) => {
        dishList.value = res
        dishListall = res
    })
})
defineExpose({
    open
})
</script>
<style lang="scss" scoped>
.el-alert__content {
    width: 100%;
}
.scrollbar {
    height: calc(100vh - 54px - 32px - 16px - 61px - 20px - 52px - 49px - 80px);
}

:deep(.el-divider--horizontal) {
    margin: 8px 0;
}

.cate-buttons :deep(.el-button) {
    margin: 0;
    width: 100%;
    justify-content: flex-start;
    padding-left: 1rem;
}

.cate-buttons :deep(.el-button.is-text:focus),
.cate-buttons :deep(.el-button.is-text:hover),
.cate-buttons :deep(.el-button.is-text.is-active) {
    color: var(--el-button-hover-border-color);
    border-color: transparent;
    background-color: var(--el-color-primary-light-9);
}

.cate-buttons :deep(.el-button.is-text) {
    color: var(--el-text-color-regular);
}
.price-summary {
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.el-button.el-button--danger {
    background-color: #ff4d4f;
    border-color: #ff4d4f;
}

.el-button.el-button--danger:hover {
    background-color: #ff7875;
    border-color: #ff7875;
}
</style>
<style>
.coupon-card {
    display: flex;
    align-items: center;
    padding: 8px;
}

.coupon-item {
    display: flex;
    margin-bottom: 12px;
    cursor: pointer;
    position: relative;
    background: #fff;
    border-radius: 4px;
    transition: all 0.3s;
    border: 1px solid #e8e8e8;

    &:last-child {
        margin-bottom: 0;
    }

    &.is-selected {
        border-color: coral;
        .left-part {
            background: coral;
        }
    }

    &.is-disabled {
        cursor: not-allowed;
        opacity: 0.6;

        .left-part {
            background: #999;
        }
    }
}

.left-part {
    width: 90px;
    background: coral;
    color: #fff;
    padding: 12px 8px;
    text-align: center;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .amount-wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }

    &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background-image: radial-gradient(circle at 0 6px, transparent 3px, #fff 3px);
        background-size: 4px 12px;
        background-repeat: repeat-y;
    }

    .amount {
        font-size: 24px;
        font-weight: bold;
        line-height: 1;
    }

    .unit {
        font-size: 12px;
        margin-top: 2px;
    }

    .condition {
        font-size: 12px;
        margin-top: 6px;
        opacity: 0.9;
    }
}

.right-part {
    flex: 1;
    padding: 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .name {
        font-size: 14px;
        color: #333;
        font-weight: 500;
    }

    .date {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
    }

    .check {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #cd8e5f;
        font-size: 12px;
    }
}

.coupon-container {
    border: 1px solid #ebeef5;
    border-radius: 4px;

    :deep(.el-scrollbar__wrap) {
        padding: 8px;
    }
}
.action-btn {
    height: 28px;
    padding: 5px 10px;
    font-size: 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: transparent;
    color: #606266;
}

.action-btn:hover {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
}

.submit-btn {
    width: 100%;
    height: 40px;
    background-color: #ff4d4f;
    border-color: #ff4d4f;
}

.submit-btn:hover {
    background-color: #ff7875;
    border-color: #ff7875;
}
</style>
