<template>
    <ele-page flex-table>
        <!-- 搜索表单 -->
        <return-search @search="reload" />
        <ele-card :body-style="{ paddingTop: '8px' }" flex-table>
            <!-- 表格 -->
            <ele-pro-table
                ref="tableRef"
                row-key="postId"
                :columns="columns"
                :datasource="datasource"
                :show-overflow-tooltip="true"
                v-model:selections="selections"
                highlight-current-row
                :export-config="{ fileName: '需退回订单' }"
                cache-key="needReturnedTable"
            >
                <template #toolbar>
                    <!-- 0-创建(待付款) 1-已付款 2-已推送 3-已发货 4-已签收 5-已完成 6-已取消 7-超时取消 -->
                    <el-radio-group
                        v-model="status"
                        @change="handleStatusChange"
                    >
                        <el-radio-button label="全部" value="0" />
                        <el-radio-button label="待发货" value="1" />
                        <el-radio-button label="已发货" value="2" />
                        <el-radio-button label="已完成" value="3" />
                        <el-radio-button label="已取消" value="4" />
                    </el-radio-group>
                </template>

                <template #status="{ row }">
                    <dict-data
                        code="refund_status"
                        type="text"
                        :model-value="row.status"
                    />
                </template>
                <template #isPush="{ row }">
                    <el-tag type="success" v-if="row.checkStatus == 1"
                        >已推送</el-tag
                    >
                    <el-tag type="danger" v-else>未推送</el-tag>
                </template>
                <template #isFirstOrder="{ row }">
                    <dict-data
                        code="is_first_order"
                        type="tag"
                        :model-value="row.firstOrder"
                    />
                </template>
                <template #orderNumber="{ row }">
                    <order-number :row="row" isReturn />
                </template>
                <template #customer="{ row }">
                    <refund-customer :row="row" :isScrect="false" />
                </template>
                <template #amount="{ row }">
                    <div class="common-text flex flex-col">
                        <el-text>余额</el-text>
                        <el-text
                            >邮费：¥ {{ row.expressMoney || '0' }}
                        </el-text>
                    </div>
                </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
                            :orderId="showOrderId"
                            title="备注历史记录"
                            ref="remarkPopoverRef"
                        />
                    </el-popover>
                </template>

                <template #action="{ row }">
                    <div class="flex flex-wrap flex-col">
                        <el-button
                            type="success"
                            link
                            v-permission="'recycleOrder:needReturned:detail'"
                            @click="toOrderDetail(row)"
                        >
                            [订单详情]
                        </el-button>
                        <el-button
                            color="#7728f5"
                            v-if="row.status !== '3'"
                            link
                            plain
                            v-permission="
                                'recycleOrder:needReturned:manualDelivery'
                            "
                            @click="handleManualDelivery(row)"
                        >
                            [手工发货]
                        </el-button>
                        <el-button
                            type="primary"
                            link
                            v-if="row.status * 1 < 3"
                            v-permission="
                                'recycleOrder:needReturned:modifyAddress'
                            "
                            @click="handleModifyAddr(row)"
                        >
                            [修改地址]
                        </el-button>

                        <el-button
                            type="danger"
                            link
                            v-if="row.status < 3"
                            v-permission="'recycleOrder:needReturned:cancel'"
                            @click="cancelOrder(row)"
                        >
                            [取消订单]
                        </el-button>
                        <el-button
                            type="danger"
                            link
                            v-if="row.status == '6'"
                            v-permission="
                                'recycleOrder:needReturned:cancelRecover'
                            "
                            @click="cancelRecover(row)"
                        >
                            [恢复订单]
                        </el-button>
                        <el-button
                            type="warning"
                            link
                            v-permission="'recycleOrder:needReturned:log'"
                            @click="openOrderLog(row)"
                        >
                            [订单日志]
                        </el-button>
                    </div>
                </template>
            </ele-pro-table>
        </ele-card>

        <slot></slot>
        <orderRemarks ref="remarksRef" isRefund @refresh="reload()" />
        <orderLog ref="logRef" type="refund" />
        <manualDelivery ref="deliveryRef" @success="reload()" />
        <orderRefundDetail ref="orderDetailRef" />
        <modifyRefundAddress ref="modifyAddressRef" @success="reload()" />
    </ele-page>
</template>

<script setup>
    import { ref, getCurrentInstance, nextTick } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import { ElMessageBox } from 'element-plus/es';
    import { Flag } from '@element-plus/icons-vue';
    import returnSearch from './return-search.vue';
    import OrderNumber from '@/views/recycleOrder/components/order-number.vue';
    import RefundCustomer from '@/views/recycleOrder/components/refund-customer.vue';
    import { useDictData } from '@/utils/use-dict-data';
    import orderRemarks from '@/views/recycleOrder/components/order-remarks.vue';
    import orderTimeline from '@/views/recycleOrder/components/order-timeline.vue';
    import orderLog from '@/views/recycleOrder/components/order-log.vue';
    import manualDelivery from '@/views/recycleOrder/components/manual-delivery.vue';
    import modifyRefundAddress from '@/views/recycleOrder/components/modify-refund-address.vue';

    //订单详情
    import orderRefundDetail from '@/views/recycleOrder/needReturned/order-refund-detail.vue';
    const status = ref('0');

    let props = defineProps({
        pageConfig: {
            type: Object,
            default: () => ({
                cacheKey: 'recycleOrderTable',
                fileName: '需退回订单'
            })
        },
        pageUrl: { type: String, default: '/order/orderInfo/refund/pageList' }
    });
    let { proxy } = getCurrentInstance();
    /** 字典数据 */
    const [statusDicts] = useDictData(['sys_normal_disable']);

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

    function handleStatusChange(val) {
        status.value = val;
        reload();
    }

    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '单号',
            prop: 'refundOrderId',
            slot: 'orderNumber',
            minWidth: 180
        },
        { label: '客户', prop: 'userNick', slot: 'customer', minWidth: 380 },
        { label: '金额', prop: 'balanceMoney', slot: 'amount', minWidth: 100 },
        { label: '是否推送', prop: 'plat', slot: 'isPush' },
        {
            label: '订单状态',
            prop: 'status',
            slot: 'status',
            formatter: (row) =>
                statusDicts.value.find((d) => d.dictValue == row.status)
                    ?.dictLabel
        },
        {
            label: '入库状态',
            prop: 'stockStatus',
            formatter: (row) =>
                row.stockStatus == 1
                    ? '已入库'
                    : row.stockStatus == 0
                      ? '未入库'
                      : '-'
        },
        { label: '是否首单', prop: 'firstOrder', slot: 'isFirstOrder' },
        { label: '创建时间', prop: 'createTime', width: 120 },
        { label: '备注', prop: 'remarkLabel', slot: 'remarks' },
        {
            columnKey: 'action',
            label: '操作',
            width: 120,
            align: 'center',
            slot: 'action',
            hideInPrint: true,
            hideInExport: true
        }
    ]);

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

    async function queryPage(params) {
        const res = await proxy.$http.get(props.pageUrl, { params });
        if (res.data.code === 200) {
            return res.data;
        }
        return Promise.reject(new Error(res.data.msg));
    }

    /** 表格数据源 */
    const datasource = ({ pages, where, orders }) => {
        return queryPage({
            ...where,
            ...orders,
            ...pages,
            tabStatus: status.value
        });
    };

    /** 搜索 */
    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 orderDetailRef = ref(null);
    function toOrderDetail(row) {
        orderDetailRef.value?.handleOpen(row);
    }

    //修改地址
    const modifyAddressRef = ref(null);
    function handleModifyAddr(row) {
        modifyAddressRef.value?.handleOpen(row);
    }

    //弹窗确认
    function messageBoxConfirm({ message, url, row }) {
        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '关闭',
            type: 'warning'
        }).then(() => {
            proxy.$http
                .post(url, { orderIds: [row.refundOrderId] })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success('操作成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg || '操作失败');
                    }
                });
        });
    }

    //取消订单
    function cancelOrder(row) {
        messageBoxConfirm({
            message: '确认取消?',
            url: '/order/orderInfo/refund/cancel',
            row
        });
    }
    //恢复订单
    function cancelRecover(row) {
        messageBoxConfirm({
            message: '确认恢复?',
            url: '/order/orderInfo/refund/cancelRecover',
            row
        });
    }
    //人工发货
    const deliveryRef = ref(null);
    function handleManualDelivery(row) {
        deliveryRef.value?.handleOpen(row);
    }
    //订单日志
    const logRef = ref(null);
    const openOrderLog = (row) => {
        logRef.value?.handleOpen(row.refundOrderId);
    };

    //修改备注
    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.refundOrderId, true);
        });

        if (showOrderId.value !== row.refundOrderId) {
            showOrderId.value = row.refundOrderId;
        }
    }
</script>
