<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="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 }">
                    <dict-data
                        code="order_status"
                        type="tag"
                        :model-value="row.status"
                    />
                </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 #sender="{ row }">
                    <div class="common-text">
                        <el-text>推送人：</el-text>
                        <el-text>{{
                            row.exceptOrderCheckInfo?.createName
                        }}</el-text>
                    </div>
                    <div class="common-text">
                        <el-text>推送时间：</el-text>
                        <el-text>{{
                            row.exceptOrderCheckInfo?.createTime || '-'
                        }}</el-text>
                    </div>
                </template>
                <template #dealer="{ row }">
                    <div class="common-text">
                        <el-text>员工姓名：</el-text>
                        <el-text>{{
                            row.exceptOrderCheckInfo?.checkName || '-'
                        }}</el-text>
                    </div>
                    <div class="common-text">
                        <el-text>处理时间：</el-text>
                        <el-text>{{
                            row.exceptOrderCheckInfo?.checkTime || '-'
                        }}</el-text>
                    </div>
                </template>
                <template #checkStatus="{ row }">
                    <dict-data
                        code="abnormal_check_status"
                        type="tag"
                        :model-value="row.exceptOrderCheckInfo?.checkStatus"
                    />
                </template>
                <template #remarks="{ row }">
                    <el-popover
                        trigger="hover"
                        width="240px"
                        @show="handleShowPopover(row)"
                        @hide="showOrderId = ''"
                    >
                        <template #reference>
                            <el-button
                                :icon="Flag"
                                link
                                style="font-size: 20px"
                                @click="handleRemarks(row)"
                            />
                        </template>
                        <orderTimeline
                            :orderId="showOrderId"
                            title="备注历史记录"
                        />
                    </el-popover>
                </template>

                <template #action="{ row }">
                    <slot name="action" :row="row"></slot>
                </template>
            </ele-pro-table>
        </ele-card>

        <slot></slot>
        <orderRemarks ref="remarksRef" />
    </ele-page>
</template>

<script setup>
    import { ref, getCurrentInstance, computed } from 'vue';
    import { ElMessageBox } from 'element-plus/es';
    import { EleMessage } from 'ele-admin-plus/es';
    import { Flag, ChatDotSquare } from '@element-plus/icons-vue';
    import OrderSearch from './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';

    let props = defineProps({
        pageConfig: {
            type: Object,
            default: () => ({
                cacheKey: 'abnormalSignTable',
                fileName: '异常订单查询'
            })
        },
        pageUrl: {
            type: String,
            default: '/order/orderInfo/exceptionOrderList'
        },
        exportUrl: {
            type: String,
            default: '/order/orderInfo/exceptionOrderExport'
        }
    });
    let { proxy } = getCurrentInstance();
    /** 字典数据 */
    const [statusDicts] = useDictData(['sys_normal_disable']);

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

    /** 表格列配置 */
    const baseColumns = [
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '单号',
            prop: 'orderNumber',
            slot: 'orderNumber',
            minWidth: 240
        },
        { label: '客户', prop: 'customer', slot: 'customer', minWidth: 360 },
        { label: '信息', prop: 'amount', slot: 'amount', minWidth: 160 },
        {
            label: '状态',
            prop: 'status',
            slot: 'status',
            minWidth: 140,
            formatter: (row) =>
                statusDicts.value.find((d) => d.dictValue == row.status)
                    ?.dictLabel
        },
        { label: '时间', prop: 'time', slot: 'time', minWidth: 220 },
        { label: '推送人', prop: 'createName', slot: 'sender', minWidth: 170 },
        { label: '处理备注', prop: 'remarks', slot: 'remarks' },
        {
            columnKey: 'action',
            label: '操作',
            width: 180,
            align: 'center',
            slot: 'action',
            fixed: 'right'
        }
    ];

    const historyColumns = [
        { label: '员工姓名', prop: 'checkName', slot: 'dealer', minWidth: 170 },
        {
            label: '处理结果',
            prop: 'checkStatus',
            slot: 'checkStatus',
            minWidth: 120
        }
    ];

    const columns = computed(() => {
        // Insert history columns before the action column if not in pending status
        if (props.pageConfig.pageUrl.includes('exceptionHistoryList')) {
            return [
                ...baseColumns.slice(0, -2),
                ...historyColumns,
                ...baseColumns.slice(-2)
            ];
        }
        return baseColumns;
    });

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

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

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

    //备注弹窗显示
    const showOrderId = ref();
    function handleShowPopover(row) {
        showOrderId.value = row.orderId;
    }

    async function queryPage(params) {
        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 }) => {
        return queryPage({ ...where, ...orders, ...pages });
    };

    /** 搜索 */
    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) {
        const res = await proxy.$http({
            url: props.exportUrl,
            method: 'POST',
            data: toFormData(params),
            responseType: 'blob'
        });
        await checkDownloadRes(res);
        download(
            res.data,
            name ? `${name}_${Date.now()}.xlsx` : `post_${Date.now()}.xlsx`
        );
    }

    /** 导出数据 */
    const exportData = (name) => {
        const loading = EleMessage.loading({
            message: '请求中..',
            plain: true
        });
        tableRef.value?.fetch?.(({ where, orders }) => {
            exportPage({ ...where, ...orders }, name)
                .then(() => {
                    loading.close();
                })
                .catch((e) => {
                    loading.close();
                    EleMessage.error(e.message);
                });
        });
    };

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

    defineExpose({ reload, exportData, operatBatch });
</script>
