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

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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.core.page.TableDataInfo;
import com.sundot.airport.common.enums.BusinessType;
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 com.sundot.airport.system.service.approval.IApprovalUserService;
import com.sundot.airport.system.service.approval.ICheckApprovalService;
import com.sundot.airport.web.controller.approval.dto.*;
import com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO;

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

    @Autowired
    private IApprovalUserService approvalUserService;

    @Autowired
    private ICheckApprovalService checkApprovalService;

    /**
     * 1. 启动个人级别审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "个人级别安检检查", businessType = BusinessType.INSERT)
    @PostMapping("/personal")
    public AjaxResult submitPersonalCheck(@RequestBody Map<String, Object> requestData) {
        // 获取备注参数
        String remark = (String) requestData.get("remark");

        try {
            ApprovalInstance instance = checkApprovalService.submitPersonalCheck(
                    requestData,
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername(),
                    remark
            );
            return AjaxResult.success("个人级别检查流程启动成功", instance);
        } catch (Exception e) {
            logger.error("启动个人级别检查流程失败", e);
            return AjaxResult.error("启动流程失败：" + e.getMessage());
        }
    }

    /**
     * 2. 启动科级审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "科级安检检查", businessType = BusinessType.INSERT)
    @PostMapping("/section")
    public AjaxResult submitSectionCheck(@RequestBody Map<String, Object> requestData) {
        // 获取备注参数
        String remark = (String) requestData.get("remark");

        try {
            ApprovalInstance instance = checkApprovalService.submitSectionCheck(
                    requestData,
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername(),
                    remark
            );
            return AjaxResult.success("科级检查流程启动成功", instance);
        } catch (Exception e) {
            logger.error("启动科级检查流程失败", e);
            return AjaxResult.error("启动流程失败：" + e.getMessage());
        }
    }

    /**
     * 3. 启动班组级审批流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "班组级安检检查", businessType = BusinessType.INSERT)
    @PostMapping("/group")
    public AjaxResult submitGroupCheck(@RequestBody Map<String, Object> requestData) {
        // 获取备注参数
        String remark = (String) requestData.get("remark");

        try {
            ApprovalInstance instance = checkApprovalService.submitGroupCheck(
                    requestData,
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername(),
                    remark
            );
            return AjaxResult.success("班组级检查流程启动成功", instance);
        } catch (Exception e) {
            logger.error("启动班组级检查流程失败", e);
            return AjaxResult.error("启动流程失败：" + e.getMessage());
        }
    }

    /**
     * 4. 启动查获上报流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:start')")
    @Log(title = "查获上报", businessType = BusinessType.INSERT)
    @PostMapping("/seizure")
    public AjaxResult submitSeizureReport(@RequestBody Map<String, Object> requestData) {
        // 获取备注参数
        String remark = (String) requestData.get("remark");

        try {
            ApprovalInstance instance = checkApprovalService.submitSeizureReport(
                    requestData,
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername(),
                    remark
            );
            return AjaxResult.success("查获上报流程启动成功", instance);
        } catch (Exception e) {
            logger.error("启动查获上报流程失败", e);
            return AjaxResult.error("启动流程失败：" + e.getMessage());
        }
    }

    /**
     * 5. 审批任务（同意）
     */
    @PreAuthorize("@ss.hasPermi('system:approval:approve')")
    @Log(title = "审批任务", businessType = BusinessType.UPDATE)
    @PutMapping("/approval/approve/{taskId}")
    public AjaxResult approveTask(@PathVariable Long taskId, @Valid @RequestBody ApprovalDTO approvalData) {
        try {
            ApprovalTask task = checkApprovalService.approveTask(
                    taskId,
                    approvalData.getComment(),
                    approvalData.getFormData(),
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername()
            );
            return AjaxResult.success("任务审批成功", task);
        } catch (Exception e) {
            logger.error("审批任务失败", e);
            return AjaxResult.error("审批失败：" + e.getMessage());
        }
    }

    /**
     * 6. 审批任务（驳回）
     */
    @PreAuthorize("@ss.hasPermi('system:approval:reject')")
    @Log(title = "驳回任务", businessType = BusinessType.UPDATE)
    @PutMapping("/approval/reject/{taskId}")
    public AjaxResult rejectTask(@PathVariable Long taskId, @Valid @RequestBody RejectDTO rejectData) {
        try {
            ApprovalTask task = checkApprovalService.rejectTask(
                    taskId,
                    rejectData.getRejectReason(),
                    SecurityUtils.getUserId(),
                    SecurityUtils.getUsername()
            );
            return AjaxResult.success("任务驳回成功", task);
        } catch (Exception e) {
            logger.error("驳回任务失败", e);
            return AjaxResult.error("驳回失败：" + e.getMessage());
        }
    }

    /**
     * 7. 获取待办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/tasks/pending")
    public TableDataInfo getPendingTasks() {
        try {
            List<ApprovalTask> list = checkApprovalService.getPendingTasks(SecurityUtils.getUserId());
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取待办任务列表失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 8. 获取已办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/tasks/completed")
    public TableDataInfo getCompletedTasks() {
        try {
            List<ApprovalTask> list = checkApprovalService.getCompletedTasks(SecurityUtils.getUserId());
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取已办任务列表失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 9. 获取我发起的审批实例
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/instances/submitted")
    public TableDataInfo getSubmittedInstances(@RequestParam(required = false) String status) {
        try {
            List<ApprovalInstance> list = checkApprovalService.getSubmittedInstances(SecurityUtils.getUserId(), status);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取提交实例列表失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 10. 取消流程
     */
    @PreAuthorize("@ss.hasPermi('system:approval:cancel')")
    @Log(title = "取消审批流程", businessType = BusinessType.UPDATE)
    @PutMapping("/approval/cancel/{instanceId}")
    public AjaxResult cancelProcess(@PathVariable Long instanceId, @RequestParam String comment) {
        try {
            boolean success = approvalEngineService.cancelProcess(instanceId, SecurityUtils.getUserId(), SecurityUtils.getUsername(), comment);
            if (!success) {
                return AjaxResult.error("取消失败");
            }
            ApprovalInstance instance = null; // 返回空对象或查询实例
            return AjaxResult.success("流程取消成功", instance);
        } catch (Exception e) {
            logger.error("取消流程失败", e);
            return AjaxResult.error("取消失败：" + e.getMessage());
        }
    }

    /**
     * 11. 根据业务类型获取工作流代码
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/workflow-code")
    public AjaxResult getWorkflowCode(@RequestParam String businessType,
                                      @RequestParam(required = false) String submitterRole) {
        try {
            // 暂时返回空值，需要实现该方法
            String workflowCode = null;
            return AjaxResult.success("获取工作流代码成功", workflowCode);
        } catch (Exception e) {
            logger.error("获取工作流代码失败", e);
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 12. 获取待办任务数量
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/tasks/pending/count")
    public AjaxResult getPendingTasksCount() {
        try {
            Long count = checkApprovalService.getPendingTaskCount(SecurityUtils.getUserId());
            return AjaxResult.success("获取待办任务数量成功", count);
        } catch (Exception e) {
            logger.error("获取待办任务数量失败", e);
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 13. 获取当前用户的抄送列表详情
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/cc/details")
    public TableDataInfo getCcDetails() {
        try {
            startPage();
            List<ApprovalCcDetailDTO> list = checkApprovalService.getCcDetailsByUserId(SecurityUtils.getUserId());
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取抄送详情列表失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 14. 根据实例ID获取审批历史
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/history/instance/{instanceId}")
    public TableDataInfo getApprovalHistoryByInstanceId(@PathVariable Long instanceId) {
        try {
            List<com.sundot.airport.system.domain.approval.ApprovalHistory> list =
                    checkApprovalService.getApprovalHistoryByInstanceId(instanceId);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("根据实例ID获取审批历史失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 15. 根据任务ID获取审批历史
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/history/task/{taskId}")
    public TableDataInfo getApprovalHistoryByTaskId(@PathVariable Long taskId) {
        try {
            List<com.sundot.airport.system.domain.approval.ApprovalHistory> list =
                    checkApprovalService.getApprovalHistoryByTaskId(taskId);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("根据任务ID获取审批历史失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 16. 获取用户的审批历史记录
     */
    @PreAuthorize("@ss.hasPermi('system:approval:query')")
    @GetMapping("/approval/history/user")
    public TableDataInfo getUserApprovalHistory(@RequestParam(required = false) String action) {
        try {
            List<com.sundot.airport.system.domain.approval.ApprovalHistory> list =
                    checkApprovalService.getUserApprovalHistory(SecurityUtils.getUserId(), action);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取用户审批历史失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 17. 批量更新抄送消息已读状态
     */
    @PreAuthorize("@ss.hasPermi('system:approval:update')")
    @Log(title = "批量更新抄送已读状态", businessType = BusinessType.UPDATE)
    @PutMapping("/approval/cc/batch-read")
    public AjaxResult batchUpdateCcReadStatus(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return AjaxResult.error("ID列表不能为空");
            }
            int rows = checkApprovalService.batchUpdateCcReadStatus(ids);
            return AjaxResult.success("批量更新成功", rows);
        } catch (Exception e) {
            logger.error("批量更新抄送已读状态失败", e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }
}