<template>
    <ele-page flex-table>
        <!-- Search Component -->
        <PageSearch
            @search="handleSearch"
            :myPendingCount="myPendingCount"
            orderType="recycle"
        />

        <!-- Common Table -->
        <common-table
            ref="tableRef"
            :pageConfig="pageConfig"
            :columns="columns"
        >
            <!-- Toolbar -->
            <template #toolbar>
                <div class="flex items-center space-x-2">
                    <el-button
                        type="primary"
                        @click="handleAdd"
                        v-permission="'workOrder:sell:add'"
                        :icon="Plus"
                        >新增工单</el-button
                    >
                    <el-button
                        type="success"
                        @click="handleBatchComplete"
                        v-permission="'workOrder:sell:complete'"
                        :icon="Check"
                        >批量完成</el-button
                    >
                </div>
            </template>

            <template #handleUsers="{ row }">
                <div v-if="row.handleUsers && row.handleUsers.length">
                    <span class="mr-1 text-gray-500"
                        >({{ getCompletedCount(row.handleUsers) }}/{{
                            row.handleUsers.length
                        }})</span
                    >
                    <span
                        v-for="(user, index) in row.handleUsers"
                        :key="user.id"
                    >
                        <span
                            :class="{
                                'text-green-600 font-medium': user.status === 2
                            }"
                            >{{ user.userName }}</span
                        >
                        <span
                            v-if="user.status === 2"
                            class="text-green-600 ml-0.5"
                            >✓</span
                        >
                        <span
                            v-if="index < row.handleUsers.length - 1"
                            class="text-gray-400"
                            >,
                        </span>
                    </span>
                </div>
                <div v-else class="text-gray-400">-</div>
            </template>

            <!-- Action Column -->
            <template #action="{ row }">
                <div class="flex justify-center space-x-2">
                    <!-- Logic: Creator -->
                    <template v-if="isCreator(row)">
                        <template v-if="[1, 2, 3].includes(row.status)">
                            <!-- Pending, Processing -->
                            <el-button
                                link
                                type="danger"
                                @click="handleVoid(row)"
                                >作废</el-button
                            >
                            <el-button
                                link
                                type="primary"
                                @click="handleEdit(row)"
                                >编辑</el-button
                            >
                            <el-button
                                link
                                type="success"
                                @click="handleComplete(row)"
                                >完成</el-button
                            >
                        </template>
                        <template v-else-if="[4, 5].includes(row.status)">
                            <!-- Completed, Void -->
                            <el-button
                                link
                                type="warning"
                                @click="handleReopen(row)"
                                >重开</el-button
                            >
                        </template>
                    </template>
                    <!-- Logic: Assignee -->
                    <template v-else-if="isAssignee(row)">
                        <template v-if="[1, 2, 3].includes(row.status)">
                            <el-button
                                link
                                type="success"
                                @click="handleComplete(row)"
                                >完成</el-button
                            >
                            <el-button
                                link
                                type="primary"
                                @click="handleEdit(row)"
                                >编辑</el-button
                            >
                        </template>
                    </template>
                </div>
            </template>
        </common-table>

        <!-- Edit Dialog -->
        <EditDialog ref="editDialogRef" @success="refreshPage" />
    </ele-page>
</template>

<script setup>
    import {
        ref,
        reactive,
        computed,
        onMounted,
        getCurrentInstance
    } from 'vue';
    import { ElMessage, ElMessageBox } from 'element-plus';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import PageSearch from '../sell/components/page-search.vue';
    import EditDialog from '@/views/workOrder/sell/components/edit-dialog.vue';
    import { useUserStore } from '@/store/modules/user';
    import { Plus, Check } from '@element-plus/icons-vue';
    const { proxy } = getCurrentInstance();

    const userStore = useUserStore();
    const currentUserId = computed(
        () => userStore.info?.userId || userStore.info?.id
    );

    const tableRef = ref(null);
    const editDialogRef = ref(null);
    const myPendingCount = ref(0); // Should be fetched separately if needed

    // Page Config for CommonTable
    const pageConfig = reactive({
        pageUrl: '/workorder/workorderinfo/pagelist',
        rowKey: 'id',
        fileName: '工单列表-回收',
        params: {
            type: 2
        }
    });

    // Column Definitions
    const columns = ref([
        { type: 'selection', width: 50, align: 'center' },
        { prop: 'id', label: '工单任务编号', width: 110, align: 'center' },
        { prop: 'orderId', label: '订单编号', minWidth: 100, align: 'center' },
        {
            prop: 'waybillCode',
            label: '运单号',
            minWidth: 140,
            align: 'center'
        },
        {
            prop: 'taskTypeName',
            label: '任务类型',
            width: 120,
            align: 'center'
        },
        { prop: 'statusName', label: '状态', width: 100, align: 'center' },
        {
            prop: 'handleUsers',
            label: '指派给',
            minWidth: 150,
            slot: 'handleUsers'
        },
        {
            prop: 'deatil',
            label: '任务详情',
            minWidth: 200,
            showOverflowTooltip: true
        },
        { prop: 'createTime', label: '创建时间', width: 160, align: 'center' },
        { prop: 'finishTime', label: '完成时间', width: 160, align: 'center' },
        {
            prop: 'createUserName',
            label: '创建人',
            width: 100,
            align: 'center'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 150,
            fixed: 'right',
            align: 'center',
            slot: 'action'
        }
    ]);

    // Helpers
    const getTaskTypeName = (type) => {
        const map = { 1: '仓库缺货', 2: '部分发货', 3: '书单不符' };
        return map[type] || '未知';
    };

    const getStatusName = (status) => {
        const map = { 1: '待处理', 2: '处理中', 3: '已完成', 4: '已作废' };
        return map[status] || '未知';
    };

    const getStatusType = (status) => {
        const map = { 1: 'primary', 2: 'warning', 3: 'success', 4: 'info' };
        return map[status] || 'info';
    };

    const getCompletedCount = (handleUsers) => {
        if (!handleUsers) return 0;
        return handleUsers.filter((u) => u.status === 2).length;
    };

    const isCreator = (row) => {
        if (!currentUserId.value) return false;
        return row.createUserId === currentUserId.value;
    };

    const isAssignee = (row) => {
        if (!currentUserId.value) return false;
        if (!row.handleUsers) return false;
        return row.handleUsers.some((u) => u.userId === currentUserId.value);
    };

    // Event Handlers
    const handleSearch = (params) => {
        tableRef.value?.reload(params);
    };

    const handleAdd = () => {
        editDialogRef.value?.handleOpen();
    };

    const handleBatchComplete = () => {
        const selectedRows = tableRef.value?.getSelections();

        tableRef.value?.operatBatch({
            method: 'post',
            url: '/workorder/workorderinfo/finish',
            title: `确认批量完成这 ${selectedRows.length} 个工单吗？`,
            data: { ids: selectedRows.map((row) => row.id) }
        });
    };

    const handleEdit = (row) => {
        editDialogRef.value?.handleOpen(row);
    };

    const refreshPage = () => {
        tableRef.value?.reload();
    };

    const handleVoid = (row) => {
        tableRef.value?.messageBoxConfirm({
            message: '确认作废该工单吗？',
            fetch: () =>
                proxy.$http.post('/workorder/workorderinfo/cancel', {
                    id: row.id
                })
        });
    };

    const handleComplete = (row) => {
        tableRef.value?.messageBoxConfirm({
            message: '确认完成该工单吗？',
            fetch: () =>
                proxy.$http.post('/workorder/workorderinfo/finish', {
                    ids: [row.id]
                })
        });
    };

    const handleReopen = (row) => {
        tableRef.value?.messageBoxConfirm({
            message: '确认重开该工单吗？',
            fetch: () =>
                proxy.$http.post('/workorder/workorderinfo/reopen', {
                    id: row.id
                })
        });
    };
</script>
