<template>
    <div class="app-container">
        <div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
            <el-form
                :model="queryParams"
                ref="queryRef"
                :inline="true"
                v-show="showSearch"
                label-width="68px"
            >
                <el-form-item label="订单编号" prop="orderNo">
                    <el-input
                        v-model="queryParams.orderNo"
                        placeholder="请输入订单编号"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="用户ID" prop="userId">
                    <el-input
                        v-model="queryParams.userId"
                        placeholder="请输入用户ID"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                    <el-input
                        v-model="queryParams.userName"
                        placeholder="请输入用户姓名"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="用户手机" prop="userPhone">
                    <el-input
                        v-model="queryParams.userPhone"
                        placeholder="请输入用户手机号"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="订单总额" prop="totalAmount">
                    <el-input
                        v-model="queryParams.totalAmount"
                        placeholder="请输入订单总额"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="发货状态" prop="orderStatus">
                    <el-select
                        v-model="queryParams.orderStatus"
                        placeholder="选择发货状态"
                        style="width: 100%"
                    >
                        <el-option label="待发货" :value="5" />
                        <el-option label="已发货" :value="6" />
                        <el-option label="待收货" :value="7" />
                        <el-option label="已收货" :value="8" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品ID" prop="productId">
                    <el-input
                        v-model="queryParams.productId"
                        placeholder="请输入商品ID"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="SKU ID" prop="skuId">
                    <el-input
                        v-model="queryParams.skuId"
                        placeholder="请输入SKU ID"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="购买数量" prop="quantity">
                    <el-input
                        v-model="queryParams.quantity"
                        placeholder="请输入购买数量"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="单价" prop="unitPrice">
                    <el-input
                        v-model="queryParams.unitPrice"
                        placeholder="请输入单价"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="拼单ID" prop="groupId">
                    <el-input
                        v-model="queryParams.groupId"
                        placeholder="请输入拼单ID"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="佣金金额" prop="commissionAmount">
                    <el-input
                        v-model="queryParams.commissionAmount"
                        placeholder="请输入佣金金额"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="支付时间" prop="payTime">
                    <el-date-picker
                        clearable
                        v-model="queryParams.payTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择支付时间"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="取消时间" prop="cancelTime">
                    <el-date-picker
                        clearable
                        v-model="queryParams.cancelTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择取消时间"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="完成时间" prop="finishTime">
                    <el-date-picker
                        clearable
                        v-model="queryParams.finishTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择完成时间"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
            <el-row :gutter="10" class="mb8">
                <!-- <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['service:order:add']"
                    >
                        新增
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['service:order:edit']"
                    >
                        修改
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['service:order:remove']"
                    >
                        删除
                    </el-button>
                </el-col> -->
                <el-col :span="1.5">
                    <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['service:order:export']"
                    >
                        导出
                    </el-button>
                </el-col>
                <right-toolbar
                    v-model:showSearch="showSearch"
                    @queryTable="getList"
                ></right-toolbar>
            </el-row>
        </div>

        <div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
            <el-table
                v-loading="loading"
                :data="orderList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="订单ID" align="center" prop="id" />
                <el-table-column label="订单编号" align="center" prop="orderNo" />
                <el-table-column label="用户ID" align="center" prop="userId" />
                <!-- <el-table-column label="用户姓名" align="center" prop="userName" /> -->
                <!-- <el-table-column label="用户手机号" align="center" prop="userPhone" /> -->
                <el-table-column label="订单类型" align="center" prop="orderType">
                    <template #default="scope">
                        <el-tag v-if="scope.row.orderType === 1">普通订单</el-tag>
                        <el-tag v-else>拼单订单</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="订单状态" align="center" prop="orderStatus">
                    <template #default="scope">
                        <el-tag>{{ getOrderStatusText(scope.row.orderStatus) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="支付状态" align="center" prop="payStatus">
                    <template #default="scope">
                        <el-tag v-if="scope.row.payStatus === 0">未支付</el-tag>
                        <el-tag v-else-if="scope.row.payStatus === 1">已支付</el-tag>
                        <el-tag v-else>已退款</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="订单总额" align="center" prop="totalAmount" />
                <el-table-column label="支付金额" align="center" prop="payAmount" />
                <el-table-column label="商品ID" align="center" prop="productId" />
                <el-table-column label="SKU ID" align="center" prop="skuId" />
                <el-table-column label="购买数量" align="center" prop="quantity" />
                <el-table-column label="单价" align="center" prop="unitPrice" />
                <el-table-column label="拼单ID" align="center" prop="groupId" />
                <el-table-column label="是否是发起人" align="center" prop="isInitiator">
                    <template #default="scope">
                        <el-tag v-if="scope.row.isInitiator === 0">否</el-tag>
                        <el-tag v-else>是</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="佣金金额" align="center" prop="commissionAmount" />
                <el-table-column label="佣金状态" align="center" prop="commissionStatus">
                    <template #default="scope">
                        <el-tag v-if="scope.row.commissionStatus === 0">未发放</el-tag>
                        <el-tag v-else>已发放</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="支付时间" align="center" prop="payTime" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="取消时间" align="center" prop="cancelTime" width="180">
                    <template #default="scope">
                        <span>
                            {{ parseTime(scope.row.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
                    <template #default="scope">
                        <span>
                            {{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                    fixed="right"
                    width="100"
                >
                    <template #default="scope">
                        <el-button
                            link
                            type="primary"
                            icon="Edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['service:order:edit']"
                        >
                            详情
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            icon="Edit"
                            v-if="scope.row.orderStatus > 4"
                            @click="handleDelivery(scope.row)"
                            v-hasPermi="['service:order:edit']"
                        >
                            发货状态
                        </el-button>
                        <!-- <el-button
                            link
                            type="primary"
                            icon="Delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['service:order:remove']"
                        >
                            删除
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
            />
        </div>

        <!-- 添加或修改订单列表对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form
                ref="orderRef"
                :model="form"
                :rules="rules"
                label-width="80px"
                label-position="top"
            >
                <el-form-item label="订单编号" prop="orderNo">
                    <el-input v-model="form.orderNo" disbaled placeholder="请输入订单编号" />
                </el-form-item>
                <el-form-item label="用户ID" prop="userId">
                    <el-input v-model="form.userId" disbaled placeholder="请输入用户ID" />
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户姓名" />
                </el-form-item>
                <el-form-item label="用户手机号" prop="userPhone">
                    <el-input v-model="form.userPhone" placeholder="请输入用户手机号" />
                </el-form-item>
                <el-form-item label="订单总额" prop="totalAmount">
                    <el-input v-model="form.totalAmount" placeholder="请输入订单总额" />
                </el-form-item>
                <el-form-item label="支付金额" prop="payAmount">
                    <el-input v-model="form.payAmount" placeholder="请输入支付金额" />
                </el-form-item>
                <el-form-item label="发货状态" prop="orderStatus">
                    <el-select v-model="form.orderStatus" placeholder="Select" style="width: 100%">
                        <el-option label="待发货" :value="5" />
                        <el-option label="已发货" :value="6" />
                        <el-option label="待收货" :value="7" />
                        <el-option label="已收货" :value="8" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/service/order';

const { proxy } = getCurrentInstance();
const router = useRouter();

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        userId: null,
        userName: null,
        userPhone: null,
        orderType: null,
        orderStatus: null,
        payStatus: null,
        totalAmount: null,
        payAmount: null,
        productId: null,
        skuId: null,
        quantity: null,
        unitPrice: null,
        groupId: null,
        isInitiator: null,
        commissionAmount: null,
        commissionStatus: null,
        payTime: null,
        cancelTime: null,
        finishTime: null,
    },
    rules: {
        orderNo: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
        userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
        orderType: [
            {
                required: true,
                message: '订单类型(1:普通订单,2:拼单订单)不能为空',
                trigger: 'change',
            },
        ],
        orderStatus: [
            {
                required: true,
                message: '订单状态(0:待支付,1:已支付,2:已取消,3:已完成)不能为空',
                trigger: 'change',
            },
        ],
        totalAmount: [{ required: true, message: '订单总额不能为空', trigger: 'blur' }],
        payAmount: [{ required: true, message: '支付金额不能为空', trigger: 'blur' }],
        productId: [{ required: true, message: '商品ID不能为空', trigger: 'blur' }],
        skuId: [{ required: true, message: 'SKU ID不能为空', trigger: 'blur' }],
        unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
    },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单列表列表 */
function getList() {
    loading.value = true;
    listOrder(queryParams.value).then(response => {
        orderList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        orderNo: null,
        userId: null,
        userName: null,
        userPhone: null,
        orderType: null,
        orderStatus: null,
        payStatus: null,
        totalAmount: null,
        payAmount: null,
        productId: null,
        skuId: null,
        quantity: null,
        unitPrice: null,
        groupId: null,
        isInitiator: null,
        commissionAmount: null,
        commissionStatus: null,
        payTime: null,
        cancelTime: null,
        finishTime: null,
        remark: null,
        createTime: null,
        updateTime: null,
    };
    proxy.resetForm('orderRef');
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = '添加订单列表';
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    // getOrder(_id).then(response => {
    //     form.value = response.data;
    //     open.value = true;
    //     title.value = '修改订单列表';
    // });
    router.push({
        path: 'orderDetail',
        name: 'OrderDetail',
        query: {
            orderId: _id,
        },
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['orderRef'].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateOrder(form.value).then(response => {
                    proxy.$modal.msgSuccess('修改成功');
                    open.value = false;
                    getList();
                });
            } else {
                addOrder(form.value).then(response => {
                    proxy.$modal.msgSuccess('新增成功');
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

// 点击发货
function handleDelivery(row) {
    reset();
    const _id = row.id || ids.value;
    getOrder(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = '修改订单列表';
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
        .confirm('是否确认删除订单列表编号为"' + _ids + '"的数据项？')
        .then(function () {
            return delOrder(_ids);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'service/order/export',
        {
            ...queryParams.value,
        },
        `order_${new Date().getTime()}.xlsx`
    );
}

// 获取订单状态文本
const getOrderStatusText = status => {
    const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        3: '已完成',
        4: '等待拼团',
        5: '待发货',
        6: '已发货',
        7: '待收货',
        8: '已收货',
        9: '已退款',
    };
    return statusMap[status] || '未知';
};

getList();
</script>
