<template>
    <ele-page flex-table>
        <!-- 搜索表单 -->
        <order-search @search="reload" />
        <ele-card :body-style="{ paddingTop: '8px' }" flex-table>
            <!-- 表格 -->
            <ele-pro-table ref="tableRef" row-key="orderId" :columns="propColumns.length > 0 ? propColumns : columns"
                :datasource="datasource" :show-overflow-tooltip="true" v-model:selections="selections"
                highlight-current-row :export-config="{ fileName: pageConfig.fileName }"
                :cache-key="pageConfig.cacheKey">
                <template #toolbar>
                    <slot name="toolbar"></slot>
                </template>

                <template #status="{ row }">
                    <el-tag type="danger" v-if="row.cancelStatus == 1">已取消</el-tag>
                    <dict-data v-else code="order_status" type="tag" :model-value="row.status" />
                    <div v-if="row.status == 4 && row.auditRejectReason">
                        原因：
                        <el-text type="info">{{ row.auditRejectReason }}</el-text>
                    </div>
                    <div class v-if="row.cancelReason && row.cancelStatus == 1">
                        取消原因：
                        <el-text type="info">{{ row.cancelReason }}</el-text>
                    </div>
                </template>
                <template #orderNumber="{ row }">
                    <order-number :row="row" />
                </template>
                <template #customer="{ row }">
                    <order-customer :row="row" />
                </template>
                <template #amount="{ row }">
                    <order-amount :row="row" />
                </template>
                <template #time="{ row }">
                    <order-time :row="row" />
                </template>
                <template #remarks="{ row }">
                    <el-popover trigger="hover" width="240px" @show="handleShowPopover(row)" @hide="showOrderId = ''">
                        <template #reference>
                            <el-icon style="cursor: pointer" :size="24" :color="row.remarkLabel || '#777777'"
                                @click="handleRemarks(row)">
                                <Flag />
                            </el-icon>
                        </template>
                        <orderTimeline title="备注历史记录" ref="remarkPopoverRef" />
                    </el-popover>
                </template>

                <template #action="{ row }">
                    <div class="flex justify-center flex-wrap">
                        <el-button type="success" link v-permission="usePermission('detail')"
                            @click="toOrderDetail(row)">
                            [订单详情]
                        </el-button>
                        <el-button type="warning" link v-permission="usePermission('log')" @click="openOrderLog(row)">
                            [订单日志]
                        </el-button>
                        <el-button type="danger" link v-if="row.status == 2" v-permission="usePermission('audit')"
                            @click="handleFirstCheck(row)">
                            [初步审核]
                        </el-button>
                        <!-- 3 已初审-带上门取件 5已揽件-待签收 6已签收-待确认到货 -->
                        <el-button type="danger" link v-if="['3', '5', '6'].includes(row.status)"
                            v-permission="usePermission('cancel')" @click="handleCancelOrder(row)">
                            [取消订单]
                        </el-button>
                        <!-- 3 已初审-带上门取件 5已揽件-待签收 6已签收-待确认到货 8待回收审核 9审核未提交 10待付款 -->
                        <el-button type="primary" link v-if="['3', '5', '6', '8', '9', '10'].includes(row.status)"
                            v-permission="usePermission('fallback')" @click="fallbackOrder(row)">
                            [回退状态]
                        </el-button>
                        <el-button type="success" link v-if="row.status == 3"
                            v-permission="usePermission('materialPickup')" @click="materialPickup(row)">
                            [物流揽件]
                        </el-button>
                        <el-button type="success" link v-if="row.status == 5" v-permission="usePermission('receive')"
                            @click="handleLogisticsSigning(row)">
                            [物流签收]
                        </el-button>
                        <el-button type="success" link v-if="row.status == 5 || row.status == 7"
                            v-permission="usePermission('signDelivery')" @click="handleSignDelivery(row)">
                            [快递签收]
                        </el-button>
                        <el-button type="success" link v-if="row.status == 6"
                            v-permission="usePermission('confirmReceipt')" @click="handleConfirmReceipt(row)">
                            [确认收货]
                        </el-button>
                        <el-button type="success" link v-if="['8', '9'].includes(row.status)"
                            v-permission="usePermission('arrivalAudit')" @click="toOrderDetail(row)">
                            [到货审核]
                        </el-button>
                        <el-button type="danger" link v-if="['8', '9', '10', '11'].includes(row.status)"
                            v-permission="usePermission('auditScreenshot')" @click="handleAuditScreenshot(row)">
                            [审核截图]
                        </el-button>
                        <el-button type="danger" link v-if="row.status == 10" v-permission="usePermission('payment')"
                            @click="handleBatchPayment(row)">
                            [支付书款]
                        </el-button>
                        <el-button type="danger" link v-if="row.status == 11"
                            v-permission="usePermission('afterSalesPayment')" @click="handleAfterSalesPayment(row)">
                            [售后补款]
                        </el-button>
                        <el-button type="warning" link v-permission="usePermission('userTag')"
                            @click="openEditUserTag(row)">
                            [用户标签]
                        </el-button>
                        <el-button type="success" link v-if="row.status == 2"
                            v-permission="usePermission('modifyAddress')" @click="handleModifyAddress(row)">
                            [修改地址]
                        </el-button>

                        <!-- v-if="['8', '9', '10', '11'].includes(row.status)" -->
                        <el-button type="success" link v-if="row.status > 2" v-permission="usePermission('sendSMS')"
                            @click="handleSendSMS(row)">
                            [推送短信]
                        </el-button>
                        <el-button type="info" link v-if="['8', '9', '10'].includes(row.status)"
                            v-permission="usePermission('smsLog')" @click="handleSmsLog(row)">
                            [短信记录]
                        </el-button>
                        <el-button color="#7728f5" link plain v-if="row.status == 11"
                            v-permission="usePermission('applyForOrderClaim')" @click="handleApplyForOrderClaim(row)">
                            [申请订单理赔]
                        </el-button>
                        <el-button color="#7728f5" link plain v-if="row.cancelStatus == 1"
                            v-permission="usePermission('applyForOrderRestore')"
                            @click="handleApplyForOrderRestore(row)">
                            [申请恢复订单]
                        </el-button>

                        <el-button link plain type="danger" v-if="
                            row.status == 11 &&
                            (row.refundStatus == 1 || row.refundStatus == 5)
                        " v-permission="usePermission('returnBad')" @click="handleReturnBad(row)">
                            [退回不良]
                        </el-button>

                        <template v-if="row.interceptStatus == 0">
                            <el-button type="danger" link v-if="['5', '6'].includes(row.status)"
                                v-permission="usePermission('interception')" @click="applyForInterception(row)">
                                [申请拦截退回]
                            </el-button>
                        </template>
                        <template v-else>
                            <el-button type="info" link v-if="['5', '6'].includes(row.status)"
                                v-permission="usePermission('cancelInterception')" @click="cancelInterception(row)">
                                [取消拦截退回]
                            </el-button>
                        </template>
                    </div>
                </template>
            </ele-pro-table>
        </ele-card>

        <slot></slot>
        <!-- 备注 -->
        <orderRemarks ref="remarksRef" @refresh="reload()" />
        <!-- 初审 -->
        <firstCheckModal ref="firstCheckRef" @success="reload()" />
        <!-- 修改地址 -->
        <modifyAddress ref="modifyAddressRef" @success="reload()" />
        <!-- 订单日志 -->
        <orderLog ref="orderLogRef" />
        <!-- 用户标签 -->
        <userBindTag ref="userTagRef" @success="reload()" />
        <!-- 订单详情 -->
        <orderDetail ref="orderDetailRef" @refresh="reload()" />
        <!-- 审核截图 -->
        <auditScreenshot ref="auditScreenshotRef" />
        <!-- 申请订单理赔 -->
        <applyForOrderClaim ref="applyForOrderClaimRef" />
        <!-- 售后补款 -->
        <afterSalesPayment ref="afterSalesPaymentRef" />
        <!-- 推送短信 -->
        <sendSMS ref="sendSMSRef" />
        <!-- 短信记录 -->
        <orderSmsLog ref="orderSmsLogRef" />
        <!-- 申请恢复订单 -->
        <applyOrderRestore ref="applyOrderRestoreRef" @success="reload()" />
    </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick } from "vue";
import { ElMessageBox } from "element-plus/es";
import { EleMessage } from "ele-admin-plus/es";
import { DownloadOutlined } from "@/components/icons";
import { Flag, ChatDotSquare } from "@element-plus/icons-vue";
import OrderSearch from "../components/order-search.vue";
import OrderNumber from "@/views/recycleOrder/components/order-number.vue";
import OrderCustomer from "@/views/recycleOrder/components/order-customer.vue";
import OrderAmount from "@/views/recycleOrder/components/order-amount.vue";
import OrderTime from "@/views/recycleOrder/components/order-time.vue";
import { useDictData } from "@/utils/use-dict-data";
import { download, toFormData, checkDownloadRes } from "@/utils/common";
import orderRemarks from "@/views/recycleOrder/components/order-remarks.vue";
import orderTimeline from "@/views/recycleOrder/components/order-timeline.vue";
import firstCheckModal from "@/views/recycleOrder/components/first-check-modal.vue";
import modifyAddress from "@/views/recycleOrder/components/modify-address.vue";
import applyForOrderClaim from "@/views/recycleOrder/components/applyfor-order-claim.vue";
import afterSalesPayment from "@/views/recycleOrder/components/after-sales-payment.vue";
//订单日志
import orderLog from "@/views/recycleOrder/components/order-log.vue";
//用户标签
import userBindTag from "@/views/recycleOrder/components/user-bind-tag.vue";
//订单详情
import orderDetail from "@/views/recycleOrder/components/order-detail.vue";
//审核截图
import auditScreenshot from "@/views/recycleOrder/components/audit-screenshot.vue";
//推送短信
import sendSMS from "@/views/recycleOrder/components/send-SMS.vue";
//短信记录
import orderSmsLog from "@/views/recycleOrder/components/order-sms-log.vue";
//申请恢复订单
import applyOrderRestore from "@/views/recycleOrder/components/apply-order-restore.vue";

let props = defineProps({
    pageConfig: {
        type: Object,
        default: () => ({
            cacheKey: "recycleOrderTable",
            pageUrl: "/order/orderInfo/pageList",
            fileName: "回收订单查询",
            exportUrl: "/order/orderInfo/export",
            where: {},
        }),
    },
    exportUrl: { type: String, default: "/system/post/export" },
    permissionKey: { type: String, default: "search" },
    propColumns: { type: Array, default: () => [] },
});
const usePermission = computed(() => (opts) => {
    return `recycleOrder:${props.permissionKey}:${opts}`;
});

let { proxy } = getCurrentInstance();
/** 字典数据 */
const [statusDicts] = useDictData(["order_status"]);

/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
    {
        type: "selection",
        columnKey: "selection",
        width: 50,
        align: "center",
        fixed: "left",
    },
    {
        label: "单号",
        prop: "orderNumber",
        slot: "orderNumber",
        minWidth: 230,
    },
    { label: "客户", prop: "customer", slot: "customer", minWidth: 360 },
    { label: "金额", prop: "amount", slot: "amount", minWidth: 160 },
    {
        label: "状态",
        prop: "status",
        slot: "status",
        width: "166",
    },
    { label: "时间", prop: "time", slot: "time", minWidth: 210 },
    { label: "备注", prop: "remarks", slot: "remarks" },
    {
        columnKey: "action",
        label: "操作",
        width: 182,
        align: "center",
        slot: "action",
        hideInPrint: true,
        hideInExport: true,
        fixed: "right",
    },
]);

/** 表格选中数据 */
const selections = ref([]);

/** 当前编辑数据 */
const current = ref(null);

/** 是否显示编辑弹窗 */
const showEdit = ref(false);

async function queryPage(params) {
    if (!props.pageConfig.pageUrl) return EleMessage.error("未配置页面请求URL");
    const res = await proxy.$http.get(props.pageConfig.pageUrl, { params });
    if (res.data.code === 200) {
        return res.data;
    }
    return Promise.reject(new Error(res.data.msg));
}

/** 表格数据源 */
const datasource = ({ pages, where, orders }) => {
    let initParams = props.pageConfig?.where || {};
    return queryPage({
        ...where,
        ...orders,
        ...pages,
        ...initParams,
    });
};

/** 搜索 */
const reload = (where = {}) => {
    let data = where && where.search ? { page: 1, where } : { where };
    delete data.where?.search;
    delete data.where?.isReset;

    tableRef.value?.reload?.(data);
};

/** 批量操作 */
const operatBatch = ({ row, url, title }) => {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
        EleMessage.error("请至少选择一条数据");
        return;
    }
    title = title || "是否确认当前操作？";
    ElMessageBox.confirm(title, "提示", {
        type: "warning",
        draggable: true,
    })
        .then(() => {
            const loading = EleMessage.loading({
                message: "请求中..",
                plain: true,
            });

            proxy.$http
                .delete(url)
                .then(() => {
                    loading.close();
                    EleMessage.success("操作成功");
                    reload();
                })
                .catch((e) => {
                    loading.close();
                    EleMessage.error(e.message);
                });
        })
        .catch(() => { });
};

/// 导出数据
async function exportPage(params, name) {
    if (!props.pageConfig.exportUrl) return EleMessage.error("未配置导出的URL！");
    const res = await proxy.$http({
        url: props.pageConfig.exportUrl,
        method: "POST",
        data: toFormData(params),
        responseType: "blob",
    });
    await checkDownloadRes(res);
    download(
        res.data,
        name ? `${name}_${Date.now()}.xlsx` : `post_${Date.now()}.xlsx`
    );
}

//导出数据 进导出记录
function exportRecord(params, name) {
    if (!props.pageConfig.exportUrl) return EleMessage.error("未配置导出的URL！");
    return proxy.$http({
        url: props.pageConfig.exportUrl,
        method: "POST",
        data: params,
    }); // 导出记录
}

/** 导出数据 */
const exportData = (name) => {
    const loading = EleMessage.loading({
        message: "请求中..",
        plain: true,
    });
    tableRef.value?.fetch?.(({ where, orders }) => {
        exportRecord({ ...where, ...orders }, name)
            .then((res) => {
                if (res.data.code === 200) {
                    EleMessage.success("操作成功,请前往导出记录下载");
                }
                loading.close();
            })
            .catch((e) => {
                loading.close();
                EleMessage.error(e.message);
            });
    });
};

//修改备注
const remarksRef = ref(null);
function handleRemarks(row) {
    remarksRef.value?.handleOpen(row);
}

//备注弹窗显示
const showOrderId = ref();
const remarkPopoverRef = ref(null);
function handleShowPopover(row) {
    nextTick(() => {
        remarkPopoverRef.value?.getRemarks(row.orderId);
    });

    if (showOrderId.value !== row.orderId) {
        showOrderId.value = row.orderId;
    }
}

//弹窗确认操作
function messageBoxConfirm({ message, fetch, toast = false }) {
    ElMessageBox.confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "关闭",
        type: "warning",
    }).then(() => {
        fetch().then((res) => {
            if (res.data.code === 200) {
                EleMessage.success(toast ? res.data.data : "操作成功");
                reload();
            } else {
                EleMessage.error(res.data.msg);
            }
        });
    });
}

//取消订单
function handleCancelOrder(row) {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
        EleMessage.error("请至少选择一条数据");
        return;
    }
    messageBoxConfirm({
        message: "是否确认取消订单？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/adminCancel", {
                orderIds: rows.map((item) => item.orderId),
            }),
    });
}
//申请拦截退出
function applyForInterception(row) {
    messageBoxConfirm({
        message: "确认拦截?",
        fetch: () => proxy.$http.post(`/order/orderInfo/intercept/${row.orderId}`),
    });
}
//取消拦截退出
function cancelInterception(row) {
    messageBoxConfirm({
        message: "确认取消拦截?",
        fetch: () =>
            proxy.$http.post(`/order/orderInfo/interceptBack/${row.orderId}`),
    });
}
//退回不良
function handleReturnBad(row) {
    messageBoxConfirm({
        message: "确认退回不良？",
        toast: true,
        fetch: () =>
            proxy.$http.post(`/order/orderInfo/refund/adminSubmit`, {
                orderId: row.orderId,
            }),
    });
}

//物流签收
function handleLogisticsSigning(row) {
    messageBoxConfirm({
        message: "确认签收？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/adminSigned", {
                orderIds: [row.orderId],
            }),
    });
}
//快递签收
function handleSignDelivery(row) {
    messageBoxConfirm({
        message: "确认快递签收？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/adminDeliverySigned", {
                orderId: row.orderId,
            }),
    });
}
//物流揽件
function materialPickup(row) {
    messageBoxConfirm({
        message: "确认物流揽件？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/adminPickup", {
                orderIds: [row.orderId],
            }),
    });
}
//申请订单理赔
const applyForOrderClaimRef = ref(null);
function handleApplyForOrderClaim(row) {
    applyForOrderClaimRef.value?.handleOpen(row);
}
//售后补款
const afterSalesPaymentRef = ref(null);
function handleAfterSalesPayment(row) {
    afterSalesPaymentRef.value?.handleOpen(row);
}
//推送短信
const sendSMSRef = ref(null);
function handleSendSMS(row) {
    sendSMSRef.value?.handleOpen(row);
}
//短信记录
const orderSmsLogRef = ref(null);
function handleSmsLog(row) {
    orderSmsLogRef.value?.handleOpen(row);
}

//确认收货
function handleConfirmReceipt(row) {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
        EleMessage.error("请至少选择一条数据");
        return;
    }
    messageBoxConfirm({
        message: "确认收货？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/adminConfirm", {
                orderIds: rows.map((item) => item.orderId),
            }),
    });
}

//订单详情
const orderDetailRef = ref(null);
function toOrderDetail(row) {
    orderDetailRef.value?.handleOpen(row);
}
//初审
const firstCheckRef = ref(null);
function handleFirstCheck(row) {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
        EleMessage.error("请至少选择一条数据");
        return;
    }
    let orderIds = rows.map((item) => item.orderId).join(",");
    firstCheckRef.value?.handleOpen(orderIds);
}
//修改地址
const modifyAddressRef = ref(null);
function handleModifyAddress(row) {
    modifyAddressRef.value?.handleOpen(row);
}
//订单日志
const orderLogRef = ref(null);
function openOrderLog(row) {
    orderLogRef.value?.handleOpen(row.orderId);
}
//用户标签
const userTagRef = ref(null);
function openEditUserTag(row) {
    userTagRef.value?.handleOpen(row);
}

function handleBatchPayment(row) {
    const rows = row == null ? selections.value : [row];
    console.log(row, rows, "xxxx");
    if (!rows.length) {
        EleMessage.error("请至少选择一条数据");
        return;
    }
    messageBoxConfirm({
        message: "确认支付书款？",
        fetch: () =>
            proxy.$http.post("/order/orderInfo/payout", {
                orderIds: rows.map((item) => item.orderId),
            }),
    });
}

//回退状态
function fallbackOrder(row) {
    messageBoxConfirm({
        message: "确认回退？",
        fetch: () => proxy.$http.post(`/order/orderInfo/statusBack/${row.orderId}`),
    });
}
//审核截图
const auditScreenshotRef = ref(null);
function handleAuditScreenshot(row) {
    auditScreenshotRef.value?.handleOpen(row);
}

//申请恢复订单
const applyOrderRestoreRef = ref(null);
function handleApplyForOrderRestore(row) {
    applyOrderRestoreRef.value?.handleOpen(row);
}

defineExpose({
    selections,
    reload,
    exportData,
    operatBatch,
    handleFirstCheck,
    handleConfirmReceipt,
    handleCancelOrder,
    handleBatchPayment,
});
</script>
