<template>
    <div class="app-container">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input v-model="listQuery.nickname" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入用户昵称" />
            <el-input v-model="listQuery.consignee" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入收货人名称" />
            <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入订单编号" />
            <el-date-picker v-model="listQuery.timeArray" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :shortcuts="pickerOptions.shortcuts" @change="dataChange" />
            <el-select v-model="listQuery.orderStatusArray" multiple style="width: 200px" class="filter-item"
                placeholder="请选择订单状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
            </el-select>
            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">查找</el-button>
            <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="download"
                @click="handleDownload">导出</el-button>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

            <el-table-column type="expand">
                <template #default="props">
                    <div v-for="item in props.row.goodsVoList" :key="item.id" class="order-goods">
                        <div class="picture">
                            <img :src="item.picUrl" width="40">
                        </div>
                        <div class="name">
                            商品名称：{{ item.goodsName }}
                        </div>
                        <div class="spec">
                            规格：{{ item.specifications.join('-') }}
                        </div>
                        <div class="price">
                            单价：{{ item.price }} 元
                        </div>
                        <div class="num">
                            数量：{{ item.number }} 件
                        </div>
                        <div class="price">
                            小计：{{ item.price * item.number }} 元
                        </div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column align="center" min-width="120" label="订单编号" prop="orderSn" />

            <el-table-column align="center" label="用户头像" width="80">
                <template #default="scope">
                    <el-avatar :src="scope.row.avatar" />
                </template>
            </el-table-column>

            <el-table-column align="center" label="下单用户" prop="userName" />

            <el-table-column align="center" label="下单时间" prop="addTime" min-width="100">
                <template #default="scope">
                    {{ scope.row.addTime ? moment(scope.row.addTime).format("YYYY-MM-DD") : '' }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="订单状态" prop="orderStatus">
                <template #default="scope">
                    <el-tag>{{ statusMap[scope.row.orderStatus] }}</el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" label="订单金额" prop="orderPrice">
                <template #default="scope">
                    {{ scope.row.orderPrice }} 元
                </template>
            </el-table-column>

            <el-table-column align="center" label="实付金额" prop="actualPrice">
                <template #default="scope">
                    {{ scope.row.actualPrice }} 元
                </template>
            </el-table-column>

            <el-table-column align="center" label="支付时间" prop="payTime" />

            <el-table-column align="center" label="收货人" prop="consignee">
                <template #default="scope">
                    <span style="color:red; font-weight:bold;">{{ scope.row.consignee }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="收货电话" prop="mobile" min-width="100" />

            <el-table-column align="center" label="物流单号" prop="shipSn" />

            <el-table-column align="center" label="物流渠道" prop="shipChannel" />

            <el-table-column align="center" label="操作" width="100" class-name="oper">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    <!-- <el-button type="warning" size="small" @click="handlePay(scope.row)">收款</el-button>
                    <el-button type="primary" size="small" @click="handleShip(scope.row)">发货</el-button>
                    <el-button type="danger" size="small" @click="handleRefund(scope.row)">退款</el-button> -->
                </template>
            </el-table-column>
        </el-table>



        <!-- 订单详情对话框 -->
        <el-dialog v-model="orderDialogVisible" title="订单详情" width="60%">
            <section ref="print">
                <el-form :model="orderDetail" label-position="left">
                    <el-form-item label="订单编号">
                        <span>{{ orderDetail.order?.orderSn }}</span>
                    </el-form-item>
                    <el-form-item label="订单状态">
                        <el-tag>{{ orderDetail.order?.orderStatus }}</el-tag>
                    </el-form-item>
                    <el-form-item label="订单用户">
                        <span>{{ orderDetail.user?.nickname }}</span>
                    </el-form-item>
                    <el-form-item label="用户留言">
                        <span>{{ orderDetail.order?.message }}</span>
                    </el-form-item>
                    <el-form-item label="收货信息">
                        <span>（收货人）{{ orderDetail.order?.consignee }}</span>
                        <span>（手机号）{{ orderDetail.order?.mobile }}</span>
                        <span>（地址）{{ orderDetail.order?.address }}</span>
                    </el-form-item>
                    <el-form-item label="商品信息">
                        <el-table :data="orderDetail?.orderGoods" border fit highlight-current-row>
                            <el-table-column align="center" label="商品名称" prop="goodsName" />
                            <el-table-column align="center" label="商品编号" prop="goodsSn" />
                            <el-table-column align="center" label="货品规格" prop="specifications" />
                            <el-table-column align="center" label="货品价格" prop="price" />
                            <el-table-column align="center" label="货品数量" prop="number" />
                            <el-table-column align="center" label="货品图片" prop="picUrl">
                                <template #default="scope">
                                    <img :src="scope.row.picUrl" width="40">
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    <el-form-item label="费用信息">
                        <span>
                            (实际费用){{ orderDetail.order?.actualPrice }}元 =
                            (商品总价){{ orderDetail.order?.goodsPrice }}元 +
                            (快递费用){{ orderDetail.order?.freightPrice }}元 -
                            (优惠减免){{ orderDetail.order?.couponPrice }}元 -
                            (积分减免){{ orderDetail.order?.integralPrice }}元
                        </span>
                    </el-form-item>
                    <el-form-item label="支付信息">
                        <span>（支付渠道）微信支付</span>
                        <span>（支付时间）{{ orderDetail.order?.payTime }}</span>
                    </el-form-item>
                    <el-form-item label="快递信息">
                        <span>（快递公司）{{ orderDetail.order?.shipChannel }}</span>
                        <span>（快递单号）{{ orderDetail.order?.shipSn }}</span>
                        <span>（发货时间）{{ orderDetail.order?.shipTime }}</span>
                    </el-form-item>
                    <el-form-item label="退款信息">
                        <span>（退款金额）{{ orderDetail.order?.refundAmount }}元</span>
                        <span>（退款类型）{{ orderDetail.order?.refundType }}</span>
                        <span>（退款备注）{{ orderDetail.order?.refundContent }}</span>
                        <span>（退款时间）{{ orderDetail.order?.refundTime }}</span>
                    </el-form-item>
                    <el-form-item label="收货信息">
                        <span>（确认收货时间）{{ orderDetail.order?.confirmTime }}</span>
                    </el-form-item>
                </el-form>
            </section>
            <template #footer class="dialog-footer">
                <el-button @click="orderDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="printOrder">打 印</el-button>
            </template>
        </el-dialog>

        <!-- 收款对话框 -->
        <el-dialog v-model="payDialogVisible" title="订单收款" width="40%" center>
            <el-form ref="payFormRef" :model="payForm" status-icon label-position="left" label-width="100px">
                <div style="margin-bottom: 10px;">
                    确认当前订单（订单编号 {{ payForm.orderSn }} ) 已经完成线下收款 ？
                </div>
                <el-form-item label="订单金额" prop="oldMoney">
                    <el-input-number v-model="payForm.oldMoney" disabled />
                </el-form-item>
                <el-form-item label="付款金额" prop="newMoney">
                    <el-input-number v-model="payForm.newMoney" :controls="false" />
                </el-form-item>
            </el-form>
            <el-table :data="payForm.goodsList">
                <el-table-column property="goodsName" label="商品" />
                <el-table-column label="规格">
                    <template #default="scope">
                        {{ scope.row.specifications.join('-') }}
                    </template>
                </el-table-column>
                <el-table-column property="onumber" width="100" label="下单数量" />
                <!-- <el-table-column label="实际数量" width="100">
          <template #default="scope">
            <el-input-number v-model="scope.row.number" :min="0" :controls="false" />
          </template>
        </el-table-column> -->
            </el-table>
            <template #footer class="dialog-footer">
                <el-button @click="payDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmPay">确定</el-button>
            </template>
        </el-dialog>

        <!-- 发货对话框 -->
        <el-dialog v-model="shipDialogVisible" title="发货">
            <el-form ref="shipFormRef" :model="shipForm" status-icon label-position="left" label-width="100px"
                style="width: 400px; margin-left:50px;">
                <el-form-item label="快递公司" prop="shipChannel">
                    <el-select v-model="shipForm.shipChannel" placeholder="请选择">
                        <el-option v-for="item in channels" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="快递编号" prop="shipSn">
                    <el-input v-model="shipForm.shipSn" />
                </el-form-item>
            </el-form>
            <template #footer class="dialog-footer">
                <el-button @click="shipDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmShip">确定</el-button>
            </template>
        </el-dialog>

        <!-- 退款对话框 -->
        <el-dialog v-model="refundDialogVisible" title="退款">
            <el-form ref="refundFormRef" :model="refundForm" status-icon label-position="left" label-width="100px"
                style="width: 400px; margin-left:50px;">
                <el-form-item label="退款金额" prop="refundMoney">
                    <el-input v-model="refundForm.refundMoney" :disabled="true" />
                </el-form-item>
            </el-form>
            <template #footer class="dialog-footer">
                <el-button @click="refundDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRefund">确定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, computed, nextTick } from 'vue'
import moment from 'moment'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { detailOrder, listOrder, listChannel, refundOrder, payOrder, deleteOrder, shipOrder } from '@/services/api/market/order'

let statusMap = {
    101: '未付款',
    102: '用户取消',
    103: '系统取消',
    201: '已付款',
    202: '申请退款',
    203: '已退款',
    301: '已发货',
    401: '用户收货',
    402: '系统收货'
} as any

let orderStatusFilter = computed((status: any) => {
    console.log(status);

    return statusMap[status]
})

let shipFormRef = ref()
let refundFormRef = ref()
let list = ref([] as any)
let total = ref(0)
let listLoading = ref(true)
let listQuery = reactive({
    page: 1,
    limit: 20,
    nickname: undefined,
    consignee: undefined,
    orderSn: undefined,
    timeArray: [],
    orderStatusArray: [],
    sort: 'add_time',
    order: 'desc'
} as any)
let pickerOptions = ref({
    shortcuts: [{
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        }
    }, {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        }
    }, {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        }
    }]
})
let orderDialogVisible = ref(false)
let orderDetail = ref({
    // order: {},
    // user: {},
    // orderGoods: []
} as any)
let shipForm = reactive({
    orderId: undefined,
    shipChannel: undefined,
    shipSn: undefined
})
let shipDialogVisible = ref(false)
let payForm = ref({
    orderId: undefined,
    orderSn: '',
    oldMoney: 0,
    newMoney: 0,
    goodsList: []
})
let payDialogVisible = ref(false)
let refundForm = reactive({
    orderId: undefined,
    refundMoney: undefined
})
let refundDialogVisible = ref(false)
let downloadLoading = ref(false)
let channels = ref([] as any)

let getList = () => {
    listLoading.value = true
    if (listQuery.timeArray && listQuery.timeArray.length === 2) {
        listQuery.start = listQuery.timeArray[0]
        listQuery.end = listQuery.timeArray[1]
    } else {
        listQuery.start = null
        listQuery.end = null
    }
    if (listQuery.orderId) {
        detailOrder(listQuery.orderId).then((res: any) => {
            console.log(res);

            list.value = []
            if (res.data.order) {
                list.value.push(res.data.order)
                total.value = 1
                listLoading.value = false
            }
        }).catch(() => {
            list.value = []
            total.value = 0
            listLoading.value = false
        })
    } else {
        listOrder(listQuery).then((res: any) => {
            console.log(res);

            list.value = res.data.list
            total.value = res.data.total
            listLoading.value = false
        }).catch(() => {
            list.value = []
            total.value = 0
            listLoading.value = false
        })
    }
}
getList()

let getChannel = () => {
    listChannel().then((res: any) => {
        channels.value = res.data
    })
}
getChannel()

let dataChange = (datatime: any) => {
    console.log(datatime);

}

let handleFilter = () => {
    listQuery.page = 1
    getList()
}

let handleDetail = (row: any) => {
    detailOrder(row.id).then((res: any) => {
        orderDetail.value = res.data
        console.log(orderDetail.value.order);
    })
    orderDialogVisible.value = true
}
let handlePay = (row: any) => {
    console.log(row);
    payForm.value.orderId = row.id
    payForm.value.orderSn = row.orderSn
    payForm.value.oldMoney = row.actualPrice
    payForm.value.newMoney = row.actualPrice
    payForm.value.goodsList = row.goodsVoList
    payForm.value.goodsList.forEach((element: any) => {
        element.onumber = element.number
    })
    console.log(payForm, 'pay');

    payDialogVisible.value = true
}
let confirmPay = () => {
    if (payForm.value.oldMoney !== payForm.value.newMoney) {
        const diff = payForm.value.newMoney - payForm.value.oldMoney
        ElMessageBox.confirm('差额 ' + diff + '元， 是否确认提交')
            .then(_ => {
                confirmPay2()
            })
            .catch(_ => { })
    } else {
        confirmPay2()
    }
}
let confirmPay2 = () => {
    payOrder(payForm).then((res: any) => {
        ElNotification({
            type: 'success',
            title: '成功',
            message: '订单收款操作成功'
        })
        getList()
    }).catch((res: any) => {
        ElNotification({
            type: 'error',
            title: '失败',
            message: res.data.errmsg
        })
    }).finally(() => {
        payDialogVisible.value = false
    })
}
let handleShip = (row: any) => {
    shipForm.orderId = row.id
    shipForm.shipChannel = row.shipChannel
    shipForm.shipSn = row.shipSn

    shipDialogVisible.value = true
    nextTick(() => {
        shipFormRef.value?.clearValidate()
    })
}
let confirmShip = () => {
    shipFormRef.value?.validate((valid: any) => {
        if (valid) {
            shipOrder(shipForm).then((res: any) => {
                shipDialogVisible.value = false
                ElNotification({
                    type: 'success',
                    title: '成功',
                    message: '确认发货成功'
                })
                getList()
            }).catch((res: any) => {
                ElNotification({
                    type: 'error',
                    title: '失败',
                    message: res.data.errmsg
                })
            })
        }
    })
}
let handleDelete = (row: any) => {
    deleteOrder({ orderId: row.id }).then((res: any) => {
        ElNotification({
            type: 'success',
            title: '成功',
            message: '订单删除成功'
        })
        getList()
    }).catch((res: any) => {
        ElNotification({
            type: 'error',
            title: '失败',
            message: res.data.errmsg
        })
    })
}
let handleRefund = (row: any) => {
    refundForm.orderId = row.id
    refundForm.refundMoney = row.actualPrice

    refundDialogVisible.value = true
    nextTick(() => {
        refundFormRef.value?.clearValidate()
    })
}
let confirmRefund = () => {
    refundFormRef.value?.validate((valid: any) => {
        if (valid) {
            refundOrder(refundForm).then((res: any) => {
                refundDialogVisible.value = false
                ElNotification({
                    type: 'success',
                    title: '成功',
                    message: '确认退款成功'
                })
                getList()
            }).catch((res: any) => {
                ElNotification({
                    type: 'error',
                    title: '失败',
                    message: res.data.errmsg
                })
            })
        }
    })
}
let handleDownload = () => {
    //   downloadLoading.value = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '收货地址']
    //     const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'address']
    //     excel.export_json_to_excel2(tHeader, list, filterVal, '订单信息')
    //     downloadLoading.value = false
    //   })
}
let printOrder = () => {
    // $print($refs.print)
    orderDialogVisible.value = false
}
</script>
 
<style lang = "scss" scoped>
.el-table--medium th,
.el-table--medium td {
    padding: 3px 0;
}

.el-input-number--medium {
    width: 100%;
}

.oper .el-button--small {
    padding: 7px 4px;
    width: 40px;
    font-size: 10px;
    margin-left: 3px;
}

::v-deep .el-table__expanded-cell {
    padding: 6px 80px;
}

.order-goods {
    display: flex;
    justify-content: space-around;
    justify-items: center;
    align-items: center;
    padding: 6px 0;
}

.name {
    width: 400px;
}

.spec {
    width: 180px;
}

.price {
    width: 120px;
}

.num {
    width: 120px;
}
</style>