<template>
    <div class="order-console">
        <el-drawer
            v-model="showOrderConsole"
            title="开始点餐"
            direction="rtl"
            size="80%"
            :before-close="beforeClose"
        >
            <div class="p-2 md:w-1/4 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.deskName }}</span>
                            <span>{{ data.currentNum + '/' + data.deskCap }}</span>
                        </div>
                    </template>
                    <el-scrollbar ref="scrollbarRef" class="scrollbar">
                        <div ref="innerRef">
                            <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>
                    <el-input
                        v-model="params.remark"
                        maxlength="30"
                        placeholder="订单备注"
                        show-word-limit
                        type="textarea"
                    />
                    <el-divider />
                    <el-alert :closable="false" style="padding: 8px 0px;">
                        <template #title>
                            <div class="justify-between flex w-full">
                                <div class="text-xl" style="font-size: 14px;">
                                    出单价格：<b
                                        style="color: sandybrown"
                                        v-text="orderData.priceSum.toFixed(2)"
                                    ></b>
                                </div>
                                <div class="text-xl">
                                    总价格：<b
                                        style="color: sandybrown"
                                        v-text="orderData.sumPriceSum.toFixed(2)"
                                    ></b>
                                </div>
                            </div>
                        </template>
                        <template #default>
                            <div class="flex" style="justify-content: space-between;">
                                <div class="text-xl" style="font-size: 14px;">
                                    出单数量：<b v-text="orderData.numSum.toString()"></b>
                                </div>
                                <div class="text-xl">
                                    总数量：<b v-text="orderData.sumNumSum.toString()"></b>
                                </div>
                            </div> 
                        </template
                    ></el-alert>
                    <div class="pt-2 justify-between flex">
                        <el-button @click="toEmpty()">清空未出单菜品</el-button
                        ><span>
                            <!-- <el-button type="primary">打折</el-button> -->
                            <el-button type="primary" @click="submit()">出单</el-button></span
                        >
                    </div>
                </el-card>
            </div>
            <div
                class="p-2 md:w-3/4 w-full md:h-full h-auto float-left flex-wrap"
                v-loading="orderLoading"
            >
                <div class="w-full h-auto">
                    <el-scrollbar
                        ><div class="flex">
                            <el-button
                                size="large"
                                :type="buttonType == 'all' ? 'primary' : ''"
                                @click="clickSortButton('all')"
                                text
                                bg
                                >全部商品</el-button
                            >
                            <el-button
                                v-for="button in dishCate"
                                :key="button.name"
                                size="large"
                                :type="buttonType == button.name ? 'primary' : ''"
                                @click="clickSortButton(button.name)"
                                text
                                bg
                                >{{ button.name }}</el-button
                            >
                        </div></el-scrollbar
                    >
                    <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">
                    <!-- 菜单内容 -->
                    <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"
                        >
                            <a href="javascript:void(0);" @click="addGoods(item)"
                                ><el-card shadow="never" :body-style="{ padding: '0px' }">
                                    <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>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ElScrollbar } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import goodsItem from './goodsItem.vue'
import {
    dishAdd,
    dishCateAll,
    dishDec,
    dishDel,
    dishInc,
    dishListAll,
    toEmptyy,
    orderSubmit,
    deskOrderedDishListAll
} from '@/api/order'
import feedback from '@/utils/feedback'
// const route = useRoute()
const innerRef = ref<HTMLDivElement>()
const dishCate = ref<any[]>([])
const dishList = ref<any[]>([])
let dishListall: any[] = []
var 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 data = reactive<any>({
    deskName: '',
    deskCap: 0,
    currentNum: 0,
    selectGoods: [],
    oldGoods: [],
})
const orderData = reactive<any>({
    priceSum: 0,
    sumPriceSum: 0,
    numSum: 0,
    sumNumSum: 0,
    
})
const params = reactive({
    remark: '', //订单备注
    number: '' //订单id
})
const submit = () => {
    //出单
    if (data.selectGoods.length == 0) {
        feedback.alert('未点菜品！')
        return false;
    }
    feedback.loading('正在出单...')
    orderSubmit(params).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('出单成功')
        showOrderConsole.value = false;
        
    })
}
const open = (item: any, num?: number, orderNumber?: any) => {
    showOrderConsole.value = true
    data.deskName = item.name
    data.deskCap = item.num
    data.currentNum = item.userNum ? item.userNum : num
    params.number = item.ordersId ? item.ordersId : orderNumber
    //查询当前订单下的所有菜品
    deskOrderedDishListAll({ id: params.number }).then((res) => {
        data.selectGoods = res
        data.oldGoods = JSON.parse(JSON.stringify(res));//记录下进入时当前餐桌已有的食物
        if (res.length > 0) {
            params.remark = res[0].remark;
            let _list = res.filter((it: { status: number })=>it.status!=1);//找到没有出单的餐品来计算价格
            orderData.priceSum = _list.reduce((accumulator, currentValue) => accumulator + (currentValue.summary * currentValue.num), 0);
            orderData.numSum = _list.reduce((accumulator, currentValue) => accumulator + currentValue.num, 0);
            //所有餐品的总价以及总数量
            orderData.sumPriceSum = res.reduce((accumulator, currentValue) => accumulator + (currentValue.summary * currentValue.num), 0);
            orderData.sumNumSum = res.reduce((accumulator, currentValue) => accumulator + currentValue.num, 0);
        }else{
            orderData.priceSum = 0
            orderData.numSum = 0
            orderData.sumPriceSum = 0
            orderData.sumNumSum = 0
        }
    })
    dishList.value = dishListall;//显示所有菜品
}
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) {
        //清空未出单的餐品-保留出单餐品
        data.selectGoods = data.selectGoods.filter((good) => {
            return good.status == 1
        })
        orderData.sumPriceSum = data.selectGoods.reduce((accumulator, currentValue) => accumulator + (currentValue.summary * currentValue.num), 0);
        orderData.sumNumSum = data.selectGoods.reduce((accumulator, currentValue) => accumulator + currentValue.num, 0);
        // data.selectGoods.length = 0
        orderData.priceSum = 0
        orderData.numSum = 0
        // orderData.sumPriceSum = 0
        // orderData.sumNumSum = 0
        toEmptyy({ id: params.number })
    }
}
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 (let 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)
}
const addGoods = (item: any) => {
    console.warn("***addGoods-添加的菜品信息***",item)
    if(orderLoading.value){
        return false;
    }
    orderLoading.value = true
    //查找未出单的餐品列表
    const list = data.selectGoods.filter((element: any) => {return element.status != 1})
    var tempGoods: string | any[] = [];
    if(item.artId){//说明操作的是历史已经添加过的餐品
        tempGoods = [item];
    }else{
        //先从历史下单但是没有结单的餐品中找出要操作的餐品
        tempGoods = list.filter((element: any) => {
            return element.artId == item.id && element.artId
        })
        if(tempGoods.length==0){//历史没有，则从当次下单的餐品列表中找
            tempGoods = list.filter((element: any) => {
                return element.id == item.id && !element.artId
            })
        }
    }
    if (tempGoods.length == 0) {
        item.num = 1
        dishAdd({
            orderId: params.number,
            dishId: item.id
        }).then((res) => {
            //拿到orders_dish的id
            item.ordersDishId = res
            data.selectGoods.push(item)
            feedback.msgSuccess('成功添加商品' + item.title)
            addHandle(item)
        }).finally(()=>{
            orderLoading.value = false;
            nextTick(() => {
                scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
            })
        })
    } else {
        dishInc({ id: item.ordersDishId || tempGoods[0].id }).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)
    orderData.numSum++
    orderData.sumNumSum++
    orderData.priceSum += Number(item.summary)
    orderData.sumPriceSum += Number(item.summary)
}
const reduce = (item: any) => {
    if(orderLoading.value){
        return false;
    }
    orderLoading.value = true
    //查找未出单的餐品列表
    const list = data.selectGoods.filter((element: any) => {return element.status != 1})
    var tempGoods: string | any[] = [];
    if(item.artId){//说明操作的是历史已经添加过的餐品
        tempGoods = [item];
    }else{
        //先从历史下单但是没有结单的餐品中找出要操作的餐品
        tempGoods = list.filter((element: any) => {
            return element.artId == item.id && element.artId
        })
        if(tempGoods.length==0){//历史没有，则从当次下单的餐品列表中找
            tempGoods = list.filter((element: any) => {
                return element.id == item.id && !element.artId
            })
        }
    }
    const t = data.selectGoods.indexOf(tempGoods[0])
    const n = data.selectGoods[t].num
    if (n > 1) {
        dishDec({ id: item.ordersDishId || tempGoods[0].id}).then(() => {
            data.selectGoods[t].num--
            reduceHandle(item)
        }).finally(()=>{
            orderLoading.value = false;
        })
    } else {//餐品数量为0，要删减该餐品
        dishDel({ id: item.ordersDishId || tempGoods[0].id}).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
    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;
    }
}

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