package com.sundot.airport.web.controller.approval;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.system.domain.approval.ApprovalInstance;
import com.sundot.airport.system.domain.approval.ApprovalTask;
import com.sundot.airport.system.service.approval.IApprovalEngineService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.common.core.page.TableDataInfo;

/**
 * 审批流程Controller
 *
 * @author simon lin
 * @date 2025-09-06
 */
@RestController
@RequestMapping("/system/approval")
public class ApprovalController extends BaseController {
    @Autowired
    private IApprovalEngineService approvalEngineService;

    /**
     * 启动审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "启动审批流程", businessType = BusinessType.INSERT)
    @PostMapping("/start")
    public AjaxResult startProcess(@RequestBody Map<String, Object> params) {
        String workflowCode = (String) params.get("workflowCode");
        String businessType = (String) params.get("businessType");
        Long businessId = Long.valueOf(params.get("businessId").toString());
        String title = (String) params.get("title");
        Long submitterId = SecurityUtils.getUserId();
        String submitterName = SecurityUtils.getUsername();
        Map<String, Object> formData = (Map<String, Object>) params.get("formData");
        Map<String, Object> businessData = (Map<String, Object>) params.get("businessData");

        ApprovalInstance instance = approvalEngineService.startProcess(
                workflowCode, businessType, businessId, title,
                submitterId, submitterName, formData, businessData);

        return AjaxResult.success("流程启动成功", instance);
    }

    /**
     * 启动个人级别审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "启动个人级别审批流程", businessType = BusinessType.INSERT)
    @PostMapping("/start/personal")
    public AjaxResult startPersonalLevelProcess(@RequestBody Map<String, Object> params) {
        String businessType = (String) params.get("businessType");
        Long businessId = Long.valueOf(params.get("businessId").toString());
        String title = (String) params.get("title");
        Long submitterId = SecurityUtils.getUserId();
        String submitterName = SecurityUtils.getUsername();

        // 新的个人级别检查流程参数
        Long sectionLeaderId = null;
        Object sectionLeaderIdObj = params.get("sectionLeaderId");
        if (sectionLeaderIdObj != null) {
            if (sectionLeaderIdObj instanceof Number) {
                sectionLeaderId = ((Number) sectionLeaderIdObj).longValue();
            } else if (sectionLeaderIdObj instanceof String) {
                sectionLeaderId = Long.parseLong((String) sectionLeaderIdObj);
            }
        }

        if (sectionLeaderId == null) {
            return AjaxResult.error("sectionLeaderId参数不能为空");
        }

        Map<String, Object> formData = (Map<String, Object>) params.get("formData");
        Map<String, Object> businessData = (Map<String, Object>) params.get("businessData");

        ApprovalInstance instance = approvalEngineService.startPersonalLevelProcess(
                businessType, businessId, title, submitterId, submitterName,
                sectionLeaderId, formData, businessData);

        return AjaxResult.success("个人级别流程启动成功", instance);
    }

    /**
     * 启动科级审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "启动科级审批流程", businessType = BusinessType.INSERT)
    @PostMapping("/start/section")
    public AjaxResult startSectionLevelProcess(@RequestBody Map<String, Object> params) {
        String businessType = (String) params.get("businessType");
        Long businessId = Long.valueOf(params.get("businessId").toString());
        String title = (String) params.get("title");
        Long submitterId = SecurityUtils.getUserId();
        String submitterName = SecurityUtils.getUsername();

        // 新的科级审批流程参数
        Long sectionLeaderId = null;
        Object sectionLeaderIdObj = params.get("sectionLeaderId");
        if (sectionLeaderIdObj != null) {
            if (sectionLeaderIdObj instanceof Number) {
                sectionLeaderId = ((Number) sectionLeaderIdObj).longValue();
            } else if (sectionLeaderIdObj instanceof String) {
                sectionLeaderId = Long.parseLong((String) sectionLeaderIdObj);
            }
        }

        if (sectionLeaderId == null) {
            return AjaxResult.error("sectionLeaderId参数不能为空");
        }

        Map<String, Object> formData = (Map<String, Object>) params.get("formData");
        Map<String, Object> businessData = (Map<String, Object>) params.get("businessData");

        ApprovalInstance instance = approvalEngineService.startSectionLevelProcess(
                businessType, businessId, title, submitterId, submitterName, sectionLeaderId, formData, businessData);

        return AjaxResult.success("科级审批流程启动成功", instance);
    }

    /**
     * 启动班组级审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "启动班组级审批流程", businessType = BusinessType.INSERT)
    @PostMapping("/start/group")
    public AjaxResult startGroupLevelProcess(@RequestBody Map<String, Object> params) {
        String businessType = (String) params.get("businessType");
        Long businessId = Long.valueOf(params.get("businessId").toString());
        String title = (String) params.get("title");
        Long submitterId = SecurityUtils.getUserId();
        String submitterName = SecurityUtils.getUsername();
        Map<String, Object> formData = (Map<String, Object>) params.get("formData");
        Map<String, Object> businessData = (Map<String, Object>) params.get("businessData");

        ApprovalInstance instance = approvalEngineService.startGroupLevelProcess(
                businessType, businessId, title, submitterId, submitterName, formData, businessData);

        return AjaxResult.success("班组级审批流程启动成功", instance);
    }

    /**
     * 启动查获上报审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "启动查获上报审批流程", businessType = BusinessType.INSERT)
    @PostMapping("/start/seizure")
    public AjaxResult startSeizureReportProcess(@RequestBody Map<String, Object> params) {
        String businessType = (String) params.get("businessType");
        Long businessId = Long.valueOf(params.get("businessId").toString());
        String title = (String) params.get("title");
        Long submitterId = SecurityUtils.getUserId();
        String submitterName = SecurityUtils.getUsername();
        String submitterRole = (String) params.get("submitterRole");
        Map<String, Object> formData = (Map<String, Object>) params.get("formData");
        Map<String, Object> businessData = (Map<String, Object>) params.get("businessData");

        ApprovalInstance instance = approvalEngineService.startSeizureReportProcess(
                businessType, businessId, title, submitterId, submitterName,
                submitterRole, formData, businessData);

        return AjaxResult.success("查获上报审批流程启动成功", instance);
    }

    /**
     * 审批任务（同意）
     */
    @PreAuthorize("@ss.hasPermi('system:approval:approve')")
    @Log(title = "审批任务", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/{taskId}")
    public AjaxResult approveTask(@PathVariable("taskId") Long taskId, @RequestBody Map<String, Object> params) {
        Long operatorId = SecurityUtils.getUserId();
        String operatorName = SecurityUtils.getUsername();
        String comment = (String) params.get("comment");
        Map<String, Object> formData = (Map<String, Object>) params.get("formData");

        boolean result = approvalEngineService.approveTask(taskId, operatorId, operatorName, comment, formData);
        return result ? AjaxResult.success("审批成功") : AjaxResult.error("审批失败");
    }

    /**
     * 驳回任务
     */
    @PreAuthorize("@ss.hasPermi('system:approval:reject')")
    @Log(title = "驳回任务", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/{taskId}")
    public AjaxResult rejectTask(@PathVariable("taskId") Long taskId, @RequestBody Map<String, Object> params) {
        Long operatorId = SecurityUtils.getUserId();
        String operatorName = SecurityUtils.getUsername();
        String comment = (String) params.get("comment");

        boolean result = approvalEngineService.rejectTask(taskId, operatorId, operatorName, comment);
        return result ? AjaxResult.success("驳回成功") : AjaxResult.error("驳回失败");
    }

    /**
     * 取消审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:cancel')")
    @Log(title = "取消审批流程", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{instanceId}")
    public AjaxResult cancelProcess(@PathVariable("instanceId") Long instanceId, @RequestBody Map<String, Object> params) {
        Long operatorId = SecurityUtils.getUserId();
        String operatorName = SecurityUtils.getUsername();
        String comment = (String) params.get("comment");

        boolean result = approvalEngineService.cancelProcess(instanceId, operatorId, operatorName, comment);
        return result ? AjaxResult.success("取消成功") : AjaxResult.error("取消失败");
    }

    /**
     * 获取用户待办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/tasks/pending")
    public TableDataInfo getPendingTasks() {
        Long userId = SecurityUtils.getUserId();
        List<ApprovalTask> list = approvalEngineService.getUserPendingTasks(userId);
        return getDataTable(list);
    }

    /**
     * 获取用户已办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/tasks/completed")
    public TableDataInfo getCompletedTasks() {
        Long userId = SecurityUtils.getUserId();
        List<ApprovalTask> list = approvalEngineService.getUserCompletedTasks(userId);
        return getDataTable(list);
    }

    /**
     * 获取用户发起的审批实例列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/instances/submitted")
    public TableDataInfo getSubmittedInstances(String status) {
        Long userId = SecurityUtils.getUserId();
        List<ApprovalInstance> list = approvalEngineService.getUserSubmittedInstances(userId, status);
        return getDataTable(list);
    }

    /**
     * 根据业务类型和级别获取流程代码
     */
    @GetMapping("/workflow/code")
    public AjaxResult getWorkflowCode(String businessType, String level, String submitterRole) {
        String workflowCode = approvalEngineService.getWorkflowCodeByBusinessAndLevel(businessType, level, submitterRole);
        return AjaxResult.success(workflowCode);
    }

    /**
     * 统计用户待办任务数量
     */
    @GetMapping("/tasks/pending/count")
    public AjaxResult getPendingTasksCount() {
        Long userId = SecurityUtils.getUserId();
        List<ApprovalTask> tasks = approvalEngineService.getUserPendingTasks(userId);
        return AjaxResult.success(tasks.size());
    }

    /**
     * 批量审批任务（同意）
     *
     * @param ids 任务ID列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:approve')")
    @Log(title = "审批任务", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/list")
    public AjaxResult approveTaskList(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("ID列表不能为空");
        }
        boolean result = approvalEngineService.approveTaskList(ids);
        return result ? AjaxResult.success("审批成功") : AjaxResult.error("审批失败");
    }

    /**
     * 批量驳回任务
     *
     * @param ids 任务ID列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:reject')")
    @Log(title = "驳回任务", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/list")
    public AjaxResult rejectTaskList(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("ID列表不能为空");
        }
        boolean result = approvalEngineService.rejectTaskList(ids);
        return result ? AjaxResult.success("驳回成功") : AjaxResult.error("驳回失败");
    }
}