<!-- 合并/转桌 -->
<template>
    <el-dialog title="转桌/并桌" width="700px" v-model="visible" @closed="onClose" top="3vh">
        <div class="scroll_y">
            <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
                <el-form-item label="当前台桌" v-if="goodsStore.tableInfo.id">
                    {{ goodsStore.tableInfo.name }}
                </el-form-item>
                <el-form-item label="转入台桌" prop="targetTableId">
                    <el-select v-model="form.targetTableId" style="width: 200px;" placeholder="请选择目标台桌">
                        <el-option :label="item.name" :value="item.id" v-for="item in tableList"
                            :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="转入类型" prop="cartIds">
                    <el-radio-group v-model="form.isFull" @change="tableChange">
                        <el-radio :value="false" border>转桌（可将部分商品转入）</el-radio>
                        <el-radio :value="true" border>并桌（并台会将全部购物车商品转入）</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="购物车商品" v-if="!form.isFull">
                    <el-table ref="cartTableRefs" :data="goodsStore.cartList" border stripe>
                        <el-table-column type="selection" align="center" width="50px"></el-table-column>
                        <el-table-column label="名称" prop="product_name"></el-table-column>
                        <el-table-column label="数量" prop="number"></el-table-column>
                        <el-table-column label="规格" prop="sku_name"></el-table-column>
                        <el-table-column label="价格" prop="lowPrice"></el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="已下单商品" v-if="!form.isFull && goodsStore.orderList.length">
                    <div v-for="item in goodsStore.orderList" style="width: 100%;">
                        <div>{{ `第${item.orderNum}次下单` }}</div>
                        <el-table ref="orderTableRefs" :data="item.goods" border stripe>
                            <el-table-column type="selection" align="center" width="50px"></el-table-column>
                            <el-table-column label="名称" prop="product_name"></el-table-column>
                            <el-table-column label="数量" prop="number"></el-table-column>
                            <el-table-column label="规格" prop="sku_name"></el-table-column>
                            <el-table-column label="价格" prop="lowPrice"></el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <div class="footer" style="display: flex;">
            <el-button style="width: 100%" @click="visible = false">
                取消
            </el-button>
            <el-button type="primary" style="width: 100%" :loading="loading" @click="confirmHandle">
                确认
            </el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { mergeOrder } from '@/api/order.js'
import { useGoods } from '@/store/goods.js'
import { shopTable } from "@/api/account.js";
import useStorage from '@/utils/useStorage.js'
import { useSocket } from '@/store/socket.js'

const emits = defineEmits(['success'])

const socket = useSocket()
const goodsStore = useGoods()
const visible = ref(false)
const cartTableRefs = ref(null)
const orderTableRefs = ref([])
const loading = ref(false)
const formRef = ref(null)
const resetForm = ref({})
const form = ref({
    targetTableId: '',
    isFull: false,
})

const rules = ref({
    targetTableId: [
        {
            required: true,
            message: ' ',
            trigger: 'change',
        }
    ],
    cartIds: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (!form.value.isFull) {
                    let arr = []
                    arr.push(...cartTableRefs.value.getSelectionRows())

                    goodsStore.orderList.map((item, index) => {
                        arr.push(...orderTableRefs.value[index].getSelectionRows())
                    })

                    if (!arr.length) {
                        callback(new Error('至少选择一个商品'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        }
    ]
})

// 切换道并桌时清除掉所有验证
function tableChange(e) {
    if (e) formRef.value.clearValidate('cartIds')
}

const tableList = ref([])
// 获取台桌列表
async function queryShopTableAjax() {
    try {
        const res = await shopTable({
            // status: 'using',
            // isBind: true
        })
        tableList.value = res.records
    } catch (error) {
        console.log(error)
    }
}

// 提交
function confirmHandle() {
    formRef.value.validate(async valid => {
        try {
            if (valid) {
                loading.value = true

                let targetTable = tableList.value.find(item => item.id == form.value.targetTableId)

                let sourceOrderId = goodsStore.orderListInfo.id
                let targetOrderId = targetTable.orderId
                let targetTableCode = targetTable.tableCode
                let detailIds = []

                if (form.value.isFull) {
                    goodsStore.orderList.map((item, index) => {
                        item.goods.map(val => {
                            detailIds.push(val.id)
                        })
                    })
                } else {
                    goodsStore.orderList.map((item, index) => {
                        detailIds.push(...orderTableRefs.value[index].getSelectionRows().map(item => item.id))
                    })
                }


                if (detailIds.length) {
                    await mergeOrder({
                        sourceOrderId: sourceOrderId, // 来源订单id
                        targetOrderId: targetOrderId, // 目标台桌订单id
                        targetTableCode: targetTableCode, // 目标台桌码
                        detailIds: detailIds // 转台详情
                    })
                    if (!goodsStore.cartList.length) {
                        useStorage.set('tableCode', targetTableCode)

                        goodsStore.successClearCart();
                        goodsStore.historyOrderAjax(targetTableCode);
                        socket.cartInit();
                    }
                }

                if (goodsStore.cartList.length) {
                    let table_code = goodsStore.cartList[0].table_code
                    let new_table_code = targetTable.tableCode
                    let cart_id = []

                    if (form.value.isFull) {
                        cart_id = goodsStore.cartList.map(item => item.id)
                    } else {
                        cart_id = cartTableRefs.value.getSelectionRows().map(item => item.id)
                    }

                    goodsStore.operateCart({
                        table_code: table_code,
                        new_table_code: new_table_code,
                        cart_id: cart_id
                    }, 'rottable')
                }
                visible.value = false
            }
        } catch (error) {
            console.log(error);
        }
        loading.value = false
    })
}

function onClose() {
    form.value = { ...resetForm.value }
    formRef.value.resetFields()
}

function show() {
    if (goodsStore.cartList.length || goodsStore.orderList.length) {
        visible.value = true
        queryShopTableAjax()
    }
}

defineExpose({
    show
})

onMounted(() => {
    resetForm.value = { ...form.value }
})
</script>

<style scoped lang="scss">
$btmH: 50px;

.scroll_y {
    height: 68vh;
    overflow-y: auto;
    padding-bottom: $btmH;
}

.footer {
    position: relative;

    &::before {
        content: "";
        height: $btmH;
        background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
        width: 100%;
        position: absolute;
        top: $btmH*-1;
        left: 0;
        z-index: 10;
    }
}
</style>