<template>
    <div class="order-index">
        <el-card shadow="never">
            <el-tabs v-model="activeName" @tab-change="tabChange">
                <el-tab-pane label="全部餐桌" name="all"></el-tab-pane>
                <el-tab-pane
                    v-for="item in areaList"
                    :key="item.id"
                    :label="item.name"
                    :name="item.name"
                ></el-tab-pane>
            </el-tabs>
            <div
                v-for="i in deskList"
                :key="i"
                class="p-1 flex-wrap float-left text-center md:w-28 h-28 w-1/3"
            >
                <a href="javascript:void(0);" @click="order_(i)"
                    ><div
                        class="rounded w-full h-full pt-3 relative"
                        :style="
                            i.status == 2
                                ? 'background-color: rgba(243, 244, 246);color:rgba(75, 85, 99)'
                                : 'background-color: rgba(91,136,73);color:rgba(255, 255, 255)'
                        "
                    >
                        <p class="font-semibold text-xl">
                            {{ i.name }}
                        </p>
                        <el-tag round>{{
                            i.status == 2 ? '空闲' : i.status == 0 ? '点餐中' : '就餐中'
                        }}</el-tag>
                        <div class="text-xl font-semibold">
                            <!-- {{ i.status == 2 ? ' ' : '￥888.88' }} -->
                            {{ i.amount ? '￥' + i.amount.toFixed(2) : ' ' }}
                        </div>
                        <div
                            class="w-full"
                            :style="'background-color: rgba(255, 255, 255, 0.4);position: absolute;bottom: 0px;'"
                        >
                            {{ (i.userNum ? i.userNum : '0') + '/' + i.num }}
                        </div>
                    </div></a
                >
            </div>
        </el-card>
        <footer-btns v-perms="['setting:website:save']">
            <el-button icon="RefreshRight" :loading="isLoading" type="primary" @click="refresh()"
                >刷新桌台</el-button
            >
        </footer-btns>
        <el-dialog
            width="300px"
            v-model="dialogVisible"
            :show-close="false"
            center
            top="0px"
            :title="currentDeskStatus == 2 ? '选择就餐人数' : ''"
        >
            <div v-if="currentDeskStatus != 2">
                <el-button class="w-full" type="primary" plain @click="reorder()">
                    继续点餐
                </el-button>
                <br />
<!--                <el-button-->
<!--                    class="w-full mt-1"-->
<!--                    plain-->
<!--                    :disabled="currentDeskStatus == 2"-->
<!--                    @click="checkout()"-->
<!--                >-->
<!--                    结账-->
<!--                </el-button>-->
<!--                <br />-->
            </div>
            <div v-if="currentDeskStatus == 2">
                <el-radio-group v-model="data.userNum" size="small">
                    <el-radio
                        class="!mr-1 mb-1"
                        v-for="item in currentDeskMaxNum"
                        :key="item"
                        :label="item"
                        border
                        :v-text="item"
                    ></el-radio>
                </el-radio-group>
                <el-button class="w-full" plain @click="order()">开始点餐</el-button>
            </div>
            <el-button v-if="currentDeskStatus != 2" class="w-full mt-1" plain @click="rockover()"
                >翻台</el-button
            >
        </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">金额 {{ currentDeskAmount }} 元</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>
    </div>
    <console @init="init()" ref="consoleRef"></console>
</template>
<script lang="ts" setup>
// 在 script setup 部分添加
import { Loading } from '@element-plus/icons-vue'
import { postAll } from '@/api/org/post'
import {
    orderDeskList,
    createOrders,
    orderCheckout,
    orderPay,
    queryPayStatus,
    cancelOrder,
    rockoverDesk
} from '@/api/order'
import Console from './console.vue'
import { getOrdersCurrent } from '@/api/orders'
import feedback from '@/utils/feedback'
import useUserStore from '@/stores/modules/user'
const userStore = useUserStore()
console.log(userStore.userInfo.id + '开始链接客户端')
// const socketClient = new WebSocket('ws://localhost:8082/backSocket/' + userStore.userInfo.id)
const activeName = ref<any>('all')
const dialogVisible = ref(false)
const isLoading = ref(false)
const currentDeskStatus = ref()
const currentDeskMaxNum = ref<number>()
const currentDeskAmount = ref<number>()
const areaList = ref<any[]>([])
const deskList = ref<any[]>([])
let currentDesk: any = {}
let deskListAll: any[] = []
const consoleRef = ref<InstanceType<typeof Console>>()
const data = reactive({
    userNum: 1, //当前就餐人数
    deskId: null,
    type: 0, //后台点餐类型：0
    canScan: false
})
const order_ = (i: any) => {
    dialogVisible.value = true
    currentDesk = i
    currentDeskStatus.value = i.status
    data.deskId = i.id
    currentDeskMaxNum.value = i.num
}
const order = () => {
    dialogVisible.value = false
    createOrders(data).then((res) => {
        consoleRef.value?.open(currentDesk, data.userNum, res)
        init()
    })
    console.warn('***order***', currentDesk)
    // router.push({ path: '/order/console', query: { deskID: id } })
}
const rockover = () => {
    feedback
        .confirm('将重置桌号状态, 确定翻台吗？')
        .then(() => {
            rockoverDesk(data).then(() => {
                feedback.notifySuccess('翻台成功!')
                dialogVisible.value = false
                init()
            })
        })
        .catch(() => {
            dialogVisible.value = false
        })
}
const reorder = () => {
    dialogVisible.value = false
    consoleRef.value?.open(currentDesk) //继续下单时会把当前餐桌上的订单号ordersId传进去
    console.warn('***reorder***', currentDesk)
}
const refresh = () => {
    isLoading.value = true
    init()
}
const scanDialogVisible = ref(false)
const scanCode = ref('')

// 添加支付中对话框的控制变量
const payingDialogVisible = ref(false)

// 添加扫码事件监听函数
const handleScanInput = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    const code = scanCode.value
    console.log('扫码内容：', code)
    if (!data.canScan) {
      feedback.notifyWarning('正在处理支付，请勿重复扫码')
      return
    }
    data.canScan = false
    payingDialogVisible.value = true // 显示支付中对话框

    document.removeEventListener('keydown', handleScanInput)
    // 修改支付处理逻辑
    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.confirm('支付失败，请重试').then(() => {
            data.canScan = true
            scanDialogVisible.value = true
            // 添加键盘事件监听
            document.addEventListener('keydown', handleScanInput)
          })
        })
    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 checkout = () => {
    refresh()
    //结账
    console.warn('***结账***', currentDesk)
    if (currentDesk && !currentDesk.amount) {
        feedback.notify('当前桌未出单，无法结账')
        return false
    }
    orderCheckout({ did: currentDesk.id }).then((res) => {
        console.log('结账', res)
        currentDesk.oid = res.id
        feedback
            .confirm(currentDesk.name + ' 结账金额为' + currentDesk.amount + '，确定要结账吗？')
            .then(() => {
                data.canScan = true
                currentDeskAmount.value = currentDesk.amount
                scanDialogVisible.value = true
                // 添加键盘事件监听
                document.addEventListener('keydown', handleScanInput)
            })
    })
}

// 在组件卸载时移除事件监听
onUnmounted(() => {
    document.removeEventListener('keydown', handleScanInput)
})
const tabChange = (name: any) => {
    if (name != 'all') {
        deskList.value = deskListAll.filter((ele: any) => {
            return ele.area == name
        })
    } else {
        deskList.value = deskListAll
    }
}
const init = async () => {
    let _list: any[] = []
    await orderDeskList().then((res: any) => {
        // deskList.value = res
        deskListAll = res
        _list = res
        getOrdersCurrent().then((res) => {
            deskList.value = _list.map((item) => {
                res.forEach((element: any) => {
                    if (item.id == element.deskId) {
                        item.status = element.status
                        item.userNum = element.userNum
                        // item.amount = element.amount
                        item.ordersId = element.number
                        if (item.amount) {
                            item.amount += Number.parseFloat(element.amount)
                        } else {
                            item.amount = Number.parseFloat(element.amount)
                        }
                    }
                })

                return item
            })
        })
    })
    await postAll().then((res) => {
        areaList.value = res
    })
    // socketClient.onopen = () => {
    //     console.log('websocket成功连接服务器')
    // }
    // socketClient.onmessage = (msg: any) => {
    //     console.log('收到消息：' + msg.data)
    //     const message = JSON.parse(msg.data)
    // }
    isLoading.value = false
}
onMounted(() => {
    init()
})
</script>
<style scoped>
.scan-dialog ::v-deep(.el-dialog__header) {
    margin-right: 0;
    padding: 20px;
    text-align: center;
}

.scan-dialog ::v-deep(.el-dialog__title) {
    font-size: 16px;
    font-weight: 500;
}
</style>
