<!-- 确认订单页面 -->

<template>
    <div class="confirm-order-page">
        <div class="order-container">
            <!-- 订单步骤 -->
            <div class="order-steps">
                <el-steps :active="1" finish-status="success">
                    <el-step title="确认订单" />
                    <el-step title="支付订单" />
                    <el-step title="完成" />
                </el-steps>
            </div>

            <!-- 订单内容 -->
            <div class="order-content">
                <!-- 商品信息 -->
                <div class="order-section">
                    <div class="section-header">
                        <h3>商品信息</h3>
                    </div>
                    <div class="section-body">
                        <el-table :data="g_templateCaseList" style="width: 100%">
                            <el-table-column label="商品" min-width="400">
                                <template #default="{ row }">
                                    <div class="item-info">
                                        <el-image
                                            :src="(row.imgUrl?.indexOf('http') == 0 ? '' : 'https://') + row.imgUrl"
                                            style="width: 80px; height: 80px" fit="cover" />
                                        <div class="item-detail">
                                            <div class="item-name">{{ row.name }}</div>
                                            <div class="item-title">{{ row.title }}</div>
                                            <div class="item-intro">{{ row.introduction }}</div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="单价" min-width="120">
                                <template #default="{ row }">
                                    ¥{{ row.price.toFixed(2) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="120">
                                <template #default="{ row }">
                                    {{ row.quantity || 1 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="小计" min-width="120">
                                <template #default="{ row }">
                                    ¥{{ ((row.price || 0) * (row.quantity || 1)).toFixed(2) }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

                <!-- 订单信息 -->
                <div class="order-section">
                    <div class="section-header">
                        <h3>订单信息</h3>
                    </div>
                    <div class="section-body">
                        <el-form :model="orderForm" label-width="100px">
                            <el-form-item label="备注">
                                <el-input v-model="orderForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                            </el-form-item>
                        </el-form>
                    </div>
                </div>

                <!-- 订单金额 -->
                <div class="order-section">
                    <div class="section-header">
                        <h3>订单金额</h3>
                    </div>
                    <div class="section-body">
                        <div class="price-summary">
                            <div class="price-item">
                                <span>商品总价：</span>
                                <span>¥{{ computeTotalAmount(g_templateCaseList).toFixed(2) }}</span>
                            </div>
                            <div class="price-item">
                                <span>优惠金额：</span>
                                <span>-¥0.00</span>
                            </div>
                            <div class="price-item total">
                                <span>实付金额：</span>
                                <span>¥{{ computeTotalAmount(g_templateCaseList).toFixed(2) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
                <el-button @click="goBack">返回修改</el-button>
                <el-button type="primary" @click="confirmOrderClick" :loading="submitting">
                    提交订单
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
/************************************************
 *                   引入文件                   *
 ************************************************/
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/index'
import { generateOrder } from '@/http/api/pages/Order/index'
import { getTemplatesDetail } from '@/http/api/pages/Template/index'

/************************************************
 * 全局变量
 *
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/
const g_route = useRoute();
const g_router = useRouter();
const g_userStore = useUserStore();
const g_templateCaseList = ref([]);

const orderForm = ref({
    invoiceType: '1',
    remark: ''
});

const submitting = ref(false);

/************************************************
 * 生命周期函数
 ************************************************/
onMounted(() => {
    const templateId = g_route.query.templateId;
    const cartItems = g_route.query.items;

    if (templateId) {
        // 直接购买场景
        getTemplateCase(templateId);
    } else if (cartItems) {
        // 购物车结算场景
        try {
            g_templateCaseList.value = JSON.parse(cartItems);
        } catch (error) {
            ElMessage.error('订单数据解析错误');
            g_router.push('/cart');
        }
    } else {
        ElMessage.error('订单数据错误');
        g_router.push('/');
    }
})

/************************************************
 * 获取数据
 *
 * 格式: get_ + 事件名     例如: get_AppDataList
 ************************************************/
const getTemplateCase = async (templateId) => {
    var response = await getTemplatesDetail(templateId);
    g_templateCaseList.value = [response.data];
}

const computeTotalAmount = function (templateCaseList = []) {
    return templateCaseList.reduce((result, item) => {
        return result + Number(item.price || 0) * (item.quantity || 1);
    }, 0);
}

const formatDate = function (date, format = 'YYYY-MM-DD HH:mm:ss') {
    const pad = (num) => num.toString().padStart(2, '0');
    return format
        .replace(/YYYY/g, date.getFullYear())
        .replace(/MM/g, pad(date.getMonth() + 1))
        .replace(/DD/g, pad(date.getDate()))
        .replace(/HH/g, pad(date.getHours()))
        .replace(/mm/g, pad(date.getMinutes()))
        .replace(/ss/g, pad(date.getSeconds()));
}

const getOrderCreatePayload = function (templateCaseList = []) {
    return {
        orders: {
            userId: g_userStore.userInfo.user.id,
            orderDate: formatDate(new Date(), "YYYY-MM-DD"),
            totalAmount: computeTotalAmount(templateCaseList),
            orderStatus: null,
            refundStatus: null,
            refundDate: null,
        },
        detailList: templateCaseList.reduce((result, item) => {
            result.push({
                templateId: item.id,
                quantity: item.quantity || 1,
                price: item.price,
                createTime: formatDate(new Date()),
                status: 1,
            });
            return result;
        }, [])
    }
}

/************************************************
* 事件处理
*
* 格式: act_ + 事件名     例如: getAppDataList
************************************************/
const confirmOrderClick = function () {
    if (!g_userStore.isUserLogin()) {
        ElMessage.warning('请先登录');
        g_router.push('/login');
        return;
    }

    var createPayload = getOrderCreatePayload(g_templateCaseList.value);
    console.log(createPayload)
    createOrderAction(createPayload);
}

const createOrderAction = async (payload) => {
    const loading = ElLoading.service({ fullscreen: true, text: "订单正在生成中..." });
    try {
        var response = await generateOrder(payload);
        loading.close();
        if (response.code == 200) {
            // 跳转到订单支付页面
            g_router.push({
                path: '/PayOrder',
                query: {
                    orderId: String(response.data.id)
                }
            });
        } else {
            ElMessageBox.alert(`订单生成失败！请稍候再试！`, '');
        }
    } catch (error) {
        loading.close();
        ElMessageBox.alert(`订单生成失败！请稍候再试！`, '');
    }
}

const goBack = () => {
    g_router.back();
};

</script>

<style scoped>
.confirm-order-page {
    min-height: calc(100vh - 60px);
    background-color: #f5f7fa;
    padding: 20px;
}

.order-container {
    max-width: 1200px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.order-steps {
    margin-bottom: 30px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
}

.order-section {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
}

.section-header {
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

.section-header h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
}

.section-body {
    padding: 20px;
}

.item-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.item-detail {
    flex: 1;
}

.item-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 5px;
}

.item-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
}

.item-intro {
    font-size: 12px;
    color: #909399;
    line-height: 1.5;
}

.price-summary {
    text-align: right;
    padding: 0 20px;
}

.price-item {
    margin-bottom: 10px;
    font-size: 14px;
    color: #606266;
}

.price-item.total {
    font-size: 18px;
    font-weight: bold;
    color: #f56c6c;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px dashed #dcdfe6;
}

.order-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
    .order-container {
        padding: 15px;
    }

    .section-body {
        padding: 15px;
    }

    .item-info {
        flex-direction: column;
        align-items: flex-start;
    }

    .item-detail {
        width: 100%;
    }
}
</style>