<template>
    <div class="container">
        <manageList :list-func="shopOrderApi.getOrderList" :custom-edit-handle="editHandle"
            :export-func="shopOrderApi.exportOrderList" edit-permiss="shop-order-setting" />

        <!-- 新增 / 编辑弹出框 -->
        <el-dialog title="管理订单" v-model="visible" style="width: 60%; min-width: 280px;">
            <el-row>
                <el-col :span="12">
                    <p class="line-height">
                        <span class="row-index">订单ID</span>
                        {{ orderDetail.id || "" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单状态</span>
                        <el-tag effect="plain" round>{{ orderDetail.orderStatus || "" }}</el-tag>
                        {{ orderDetail.orderStatusCode || "" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">下单用户ID</span>
                        {{ orderDetail.userId || "" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单价格</span>
                        {{ orderDetail.orderPrice ? ('￥' + orderDetail.orderPrice) : "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">下单时间</span>
                        {{ orderDetail.orderDate || "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单取消时间</span>
                        {{ orderDetail.cancelDate || "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单支付时间</span>
                        {{ orderDetail.payDate || "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单发货时间</span>
                        {{ orderDetail.shipDate || "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">订单送达时间</span>
                        {{ orderDetail.deliverDate || "-" }}
                    </p>
                    <p class="line-height">
                        <span class="row-index">运单号</span>
                        <template
                            v-if="orderDetail.orderStatusCode != 'Processing' && orderDetail.orderStatusCode != 'Shipped'">
                            {{ orderDetail.expressId || "-" }}
                        </template>
                        <el-input v-else v-model="shippingInfo.expressId" placeholder="Please input" />
                    </p>
                    <p class="line-height">
                        <span class="row-index">发货备注</span>
                        <template
                            v-if="orderDetail.orderStatusCode != 'Processing' && orderDetail.orderStatusCode != 'Shipped'">
                            {{ orderDetail.comment || "-" }}
                        </template>
                        <el-input v-else v-model="shippingInfo.comment" placeholder="Please input" />
                    </p>
                </el-col>
                <el-col :span="12">
                    <p style="margin-bottom: 20px;">该订单中包含如下商品</p>
                    <div style="max-height:50vh; overflow-y: scroll;">
                        <el-card class="box-card" v-for="i in orderItem" :key="i.goodId"
                            style="--el-card-padding: 10px; margin-bottom: 8px;">
                            <div style="display: grid; grid-template-columns: 50px 1fr 60px; gap: 15px;">
                                <img :src="i.good.picUrl" style="width: 60px; height: 60px;" />
                                <div style="place-self: center left;">
                                    <p>{{ i.good.goodsName }}</p>
                                    <p style="color: grey; font-size: 12px;">商品ID: {{ i.goodId }}</p>
                                </div>
                                <div style="place-self: center; font-size: 16px;">{{ i.goodCount }} {{ i.good.unit }}</div>
                            </div>
                        </el-card>
                    </div>
                </el-col>
            </el-row>
            <!-- 订单状态：PENDING("Pending", "等待确认"), -->
            <!-- 订单状态：PROCESSING("Processing", "已支付，等待发货中"), -->
            <!-- 订单状态：SHIPPED("Shipped", "已发货，等待确认收货"), -->
            <!-- 订单状态：DELIVERED("Delivered", "已送达"), -->
            <!-- 订单状态：CANCELLED("Cancelled", "已取消"); -->
            <!-- 该订单已被取消 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-if="orderDetail.orderStatusCode == 'Processing'" type="danger"
                        @click="withdrawOrder">取消发货并退款</el-button>
                    <el-button
                        v-if="orderDetail.orderStatusCode == 'Processing' || orderDetail.orderStatusCode == 'Shipped'"
                        type="primary" @click="saveEdit">保存发货信息</el-button>
                    <el-button @click="visible = false">关 闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import manageList from '../components/manage-list.vue';
import * as shopOrderApi from '../api/shop-order';
import { ref, reactive, onMounted, computed } from 'vue';
import { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Search, Plus, Filter, Download } from '@element-plus/icons-vue';

const visible: any = ref(false);

const orderDetail = ref({} as any);
const orderItem = ref([] as any);

const shippingInfo = ref({} as any); // 发货信息

let completeCallback: Function = () => { };

const editHandle = async function (tabIndex: number, row: any, refreshFunc: Function) {
    console.log("tabIndex", tabIndex)
    console.log("orderDetail", row)
    orderDetail.value = row // 订单详情

    shippingInfo.value.expressId = row.expressId
    shippingInfo.value.comment = row.comment

    completeCallback = refreshFunc
    visible.value = true

    shopOrderApi.getOrderDetail({
        orderId: row.id
    }).then(function (data) {
        let orderGoods = {}
        data.goods.forEach((good: any) => {
            orderGoods[good.id] = good
        });

        orderItem.value = data.orderItem.map((item: any) => {
            item.good = orderGoods[item.goodId]
            return item
        })

        console.log("orderItem", orderItem.value)
    })
}

const saveEdit = function () {
    // 保存发货信息
    ElMessageBox.confirm('确定要进行发货操作吗？发货后订单将不可撤销。（用户点击收货前仍可以修改发货信息）', '提示', { type: 'warning' })
        .then(async () => {
            shopOrderApi.deliverOrder({
                orderId: orderDetail.value.id,
                ...shippingInfo.value
            }).then(function (data) {
                if (data) { // 如果出错则已经出提示了
                    ElMessage.success({ message: data })
                    visible.value = false
                    completeCallback()
                }
            })
        })
        .catch(() => { });
}

const withdrawOrder = function () {
    // 取消订单
    ElMessageBox.confirm('确定要取消此订单吗？该操作不可撤销。', '提示', { type: 'warning' })
        .then(async () => {
            shopOrderApi.withdrawOrder({
                orderId: orderDetail.value.id,
                ...shippingInfo.value
            }).then(function (data) {
                if (data) { // 如果出错则已经出提示了
                    ElMessage.success({ message: data })
                    visible.value = false
                    completeCallback()
                }
            })
        })
        .catch(() => { });
}
</script>

<style>
.line-height {
    line-height: 2.7em;
}

.row-index {
    width: 110px;
    display: inline-block;
}
</style>
