/**
 * 审批流程前端调用示例
 * @author simon lin
 * @date 2025-09-06
 */

// 审批流程API调用类
class ApprovalAPI {
    constructor() {
        this.baseURL = '/system/check';
    }

    /**
     * 1. 提交个人级别检查
     */
    async submitPersonalCheck(checkData) {
        const params = {
            id: checkData.id,
            description: checkData.description,
            checkType: checkData.checkType,
            location: checkData.location,
            targetUserIds: checkData.targetUserIds
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/personal`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("个人级别检查提交成功");
                return response.data;
            } else {
                $.modal.msgError(response.msg);
                return null;
            }
        } catch (error) {
            $.modal.msgError("提交失败：" + error.responseText);
            return null;
        }
    }

    /**
     * 2. 提交科级检查
     */
    async submitSectionCheck(checkData) {
        const params = {
            id: checkData.id,
            description: checkData.description,
            checkType: checkData.checkType,
            severity: checkData.severity,
            targetDeptId: checkData.targetDeptId
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/section`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("科级检查提交成功");
                return response.data;
            } else {
                $.modal.msgError(response.msg);
                return null;
            }
        } catch (error) {
            $.modal.msgError("提交失败：" + error.responseText);
            return null;
        }
    }

    /**
     * 3. 提交班组级检查
     */
    async submitGroupCheck(checkData) {
        const params = {
            id: checkData.id,
            description: checkData.description,
            checkType: checkData.checkType,
            severity: checkData.severity,
            targetDeptId: checkData.targetDeptId
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/group`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("班组级检查提交成功");
                return response.data;
            } else {
                $.modal.msgError(response.msg);
                return null;
            }
        } catch (error) {
            $.modal.msgError("提交失败：" + error.responseText);
            return null;
        }
    }

    /**
     * 4. 提交查获上报
     */
    async submitSeizureReport(reportData) {
        const params = {
            id: reportData.id,
            itemType: reportData.itemType,
            quantity: reportData.quantity,
            location: reportData.location,
            seizureTime: reportData.seizureTime,
            passengerInfo: reportData.passengerInfo
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/seizure/report`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("查获上报提交成功");
                return response.data;
            } else {
                $.modal.msgError(response.msg);
                return null;
            }
        } catch (error) {
            $.modal.msgError("提交失败：" + error.responseText);
            return null;
        }
    }

    /**
     * 5. 审批任务（同意）
     */
    async approveTask(taskId, approvalData) {
        const params = {
            comment: approvalData.comment,
            nodeType: approvalData.nodeType,
            targetGroupId: approvalData.targetGroupId,
            rectificationRequirement: approvalData.rectificationRequirement,
            rectificationDetail: approvalData.rectificationDetail,
            rectificationTime: approvalData.rectificationTime,
            rectificationResult: approvalData.rectificationResult
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/approval/approve/${taskId}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("审批成功");
                return true;
            } else {
                $.modal.msgError(response.msg);
                return false;
            }
        } catch (error) {
            $.modal.msgError("审批失败：" + error.responseText);
            return false;
        }
    }

    /**
     * 6. 驳回任务
     */
    async rejectTask(taskId, rejectReason) {
        const params = {
            rejectReason: rejectReason
        };

        try {
            const response = await $.ajax({
                url: `${this.baseURL}/approval/reject/${taskId}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(params)
            });

            if (response.code === 200) {
                $.modal.msgSuccess("驳回成功");
                return true;
            } else {
                $.modal.msgError(response.msg);
                return false;
            }
        } catch (error) {
            $.modal.msgError("驳回失败：" + error.responseText);
            return false;
        }
    }

    /**
     * 7. 获取待办任务列表
     */
    async getPendingTasks() {
        try {
            const response = await $.get(`${this.baseURL}/approval/tasks/pending`);
            return response;
        } catch (error) {
            console.error("获取待办任务失败", error);
            return { code: 500, rows: [] };
        }
    }

    /**
     * 8. 获取已办任务列表
     */
    async getCompletedTasks() {
        try {
            const response = await $.get(`${this.baseURL}/approval/tasks/completed`);
            return response;
        } catch (error) {
            console.error("获取已办任务失败", error);
            return { code: 500, rows: [] };
        }
    }

    /**
     * 9. 获取我发起的审批实例
     */
    async getSubmittedInstances(status = null) {
        const url = status ? 
            `${this.baseURL}/approval/instances/submitted?status=${status}` : 
            `${this.baseURL}/approval/instances/submitted`;

        try {
            const response = await $.get(url);
            return response;
        } catch (error) {
            console.error("获取提交实例失败", error);
            return { code: 500, rows: [] };
        }
    }

    /**
     * 10. 取消审批流程
     */
    async cancelProcess(instanceId, comment) {
        try {
            const response = await $.ajax({
                url: `${this.baseURL}/approval/cancel/${instanceId}?comment=${encodeURIComponent(comment)}`,
                type: 'PUT'
            });

            if (response.code === 200) {
                $.modal.msgSuccess("取消成功");
                return true;
            } else {
                $.modal.msgError(response.msg);
                return false;
            }
        } catch (error) {
            $.modal.msgError("取消失败：" + error.responseText);
            return false;
        }
    }

    /**
     * 11. 获取待办任务数量
     */
    async getPendingTasksCount() {
        try {
            const response = await $.get(`${this.baseURL}/approval/tasks/pending/count`);
            return response.code === 200 ? response.data : 0;
        } catch (error) {
            console.error("获取待办数量失败", error);
            return 0;
        }
    }
}

// 审批流程页面管理类
class ApprovalPageManager {
    constructor() {
        this.api = new ApprovalAPI();
    }

    /**
     * 初始化待办任务页面
     */
    async initPendingTasksPage() {
        const response = await this.api.getPendingTasks();
        if (response.code === 200) {
            this.renderTaskList(response.rows, 'pending');
        }
    }

    /**
     * 初始化已办任务页面
     */
    async initCompletedTasksPage() {
        const response = await this.api.getCompletedTasks();
        if (response.code === 200) {
            this.renderTaskList(response.rows, 'completed');
        }
    }

    /**
     * 渲染任务列表
     */
    renderTaskList(tasks, type) {
        const tbody = $(`#${type}TasksTable tbody`);
        tbody.empty();

        tasks.forEach(task => {
            const row = this.createTaskRow(task, type);
            tbody.append(row);
        });
    }

    /**
     * 创建任务行
     */
    createTaskRow(task, type) {
        const actions = type === 'pending' ? 
            `<button class="btn btn-success btn-sm" onclick="approvalManager.showApprovalModal(${task.id})">审批</button>
             <button class="btn btn-danger btn-sm" onclick="approvalManager.showRejectModal(${task.id})">驳回</button>` :
            `<span class="badge ${task.status === 'APPROVED' ? 'badge-success' : 'badge-danger'}">${task.status}</span>`;

        return `
            <tr>
                <td>${task.taskNo}</td>
                <td>${task.taskName}</td>
                <td>${task.instance?.title || ''}</td>
                <td>${task.assigneeName}</td>
                <td>${task.assignTime}</td>
                <td>${actions}</td>
            </tr>
        `;
    }

    /**
     * 显示审批模态框
     */
    showApprovalModal(taskId) {
        $('#approvalTaskId').val(taskId);
        $('#approvalModal').modal('show');
    }

    /**
     * 显示驳回模态框
     */
    showRejectModal(taskId) {
        $('#rejectTaskId').val(taskId);
        $('#rejectModal').modal('show');
    }

    /**
     * 处理审批
     */
    async handleApproval() {
        const taskId = $('#approvalTaskId').val();
        const comment = $('#approvalComment').val();
        const nodeType = $('#approvalNodeType').val();
        
        const approvalData = {
            comment: comment,
            nodeType: nodeType
        };

        // 根据节点类型添加额外数据
        if (nodeType === 'SECTION_LEADER') {
            approvalData.targetGroupId = $('#targetGroupId').val();
            approvalData.rectificationRequirement = $('#rectificationRequirement').val();
        } else if (nodeType === 'GROUP_LEADER_RECTIFY') {
            approvalData.rectificationDetail = $('#rectificationDetail').val();
            approvalData.rectificationTime = $('#rectificationTime').val();
            approvalData.rectificationResult = $('#rectificationResult').val();
        }

        const success = await this.api.approveTask(taskId, approvalData);
        if (success) {
            $('#approvalModal').modal('hide');
            this.initPendingTasksPage(); // 刷新列表
        }
    }

    /**
     * 处理驳回
     */
    async handleReject() {
        const taskId = $('#rejectTaskId').val();
        const rejectReason = $('#rejectReason').val();

        const success = await this.api.rejectTask(taskId, rejectReason);
        if (success) {
            $('#rejectModal').modal('hide');
            this.initPendingTasksPage(); // 刷新列表
        }
    }

    /**
     * 更新待办数量徽章
     */
    async updatePendingBadge() {
        const count = await this.api.getPendingTasksCount();
        $('.pending-count-badge').text(count);
    }
}

// 全局实例
const approvalManager = new ApprovalPageManager();

// 页面加载完成后初始化
$(document).ready(function() {
    // 定时更新待办数量
    approvalManager.updatePendingBadge();
    setInterval(() => {
        approvalManager.updatePendingBadge();
    }, 30000); // 30秒更新一次
});

// 使用示例
/*
// 1. 提交个人级别检查
const personalCheckData = {
    id: 1,
    description: '发现个人违规行为',
    checkType: 'PERSONAL_VIOLATION',
    location: 'A区域安检口',
    targetUserIds: [10, 11, 12]
};
approvalManager.api.submitPersonalCheck(personalCheckData);

// 2. 提交科级检查
const sectionCheckData = {
    id: 2,
    description: '发现科级管理问题',
    checkType: 'MANAGEMENT_ISSUE',
    severity: 'HIGH',
    targetDeptId: 100
};
approvalManager.api.submitSectionCheck(sectionCheckData);

// 3. 提交查获上报
const seizureData = {
    id: 3,
    itemType: '危险品',
    quantity: 1,
    location: 'B区域',
    seizureTime: new Date(),
    passengerInfo: '张三，身份证：123456'
};
approvalManager.api.submitSeizureReport(seizureData);

// 4. 审批任务
const approvalData = {
    comment: '同意处理',
    nodeType: 'SECTION_LEADER',
    targetGroupId: 200,
    rectificationRequirement: '请在3天内完成整改'
};
approvalManager.api.approveTask(1, approvalData);

// 5. 驳回任务
approvalManager.api.rejectTask(1, '信息不完整，请补充详细情况');
*/