using Microsoft.AspNetCore.Mvc;
using OpenAuth.App.Interface;
using OpenAuth.App.workflow;

namespace OpenAuth.WebApi.Controllers.ServerController;

// todo 关于针对流程及个人的处理状态处置
/// <summary>
/// 工作流核心API接口（流程发起/处理 + 拟办/待办/已办/未办结/已完成/全部事项查询）
/// </summary>
[ApiController]
[Route("api/[controller]/[action]")]
public class WorkflowController : ControllerBase
{
    private readonly WorkflowEngineApp _workflowEngineApp;
    private readonly IAuth _auth;

    // 构造函数注入依赖
    public WorkflowController(WorkflowEngineApp workflowEngineApp, IAuth auth)
    {
        _workflowEngineApp = workflowEngineApp;
        _auth = auth;
    }

    #region 一、流程操作接口

    /// <summary>
    /// 发起流程（区县提交） 拟办需要重新提交
    /// </summary>
    /// <param name="requestDto">发起流程请求参数</param>
    /// <returns>流程实例ID</returns>
    [HttpPost]
    public ActionResult<ApiResponseDto<long>> InitiateFlow([FromBody] InitiateFlowRequestDto requestDto)
    {
        try
        {
            requestDto.FlowCode = "IllegalConstructionFlow";
            // 获取当前登录用户（实际项目中从Token/IAuth中解析）
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<long>.Fail("未登录或登录过期"));

            var instanceId = _workflowEngineApp.InitiateFlow(
                currentUser.Id,
                currentUser.Name,
                requestDto);

            return Ok(ApiResponseDto<long>.Success(instanceId, "流程发起成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<long>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 处理工作项（执法监督科转发/审核科会签/汇总处理 todo 驳回）
    /// </summary>
    /// <param name="requestDto">处理工作项请求参数</param>
    /// <returns>处理结果</returns>
    [HttpPost]
    public ActionResult<ApiResponseDto<bool>> HandleWorkitem([FromBody] HandleWorkitemRequestDto requestDto)
    {
        try
        {
            // 获取当前登录用户（实际项目中从Token/IAuth中解析）
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<bool>.Fail("未登录或登录过期"));

            var result = _workflowEngineApp.HandleWorkitem(
                currentUser.Id,
                currentUser.Name,
                requestDto);

            return Ok(ApiResponseDto<bool>.Success(result, "工作项处理成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<bool>.Fail(ex.Message));
        }
    }

    #endregion

    #region 二、完整查询接口（拟办/待办/已办/未办结/已完成/全部事项）

    /// <summary>
    /// 保存拟办（逻辑待完善）
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public ActionResult<ApiResponseDto<bool>> SaveDraft([FromBody] InitiateFlowRequestDto requestDto)
    {
        // 先保存到表单中，发起流程时，根据业务编号确定存不存，如果已经存在，则修改状态为已提交
        try
        {
            // 获取当前登录用户（实际项目中从Token/IAuth中解析）
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<bool>.Fail("未登录或登录过期"));
            var result = _workflowEngineApp.SaveDraft(requestDto);
            return Ok(ApiResponseDto<bool>.Success());
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<bool>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的拟办（未完成）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页拟办结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyDraft(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));
            var result = _workflowEngineApp.QueryMyDraft(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "拟办查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的待办（已分配/待处理事项）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页待办结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyToDo(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));

            var result = _workflowEngineApp.QueryMyToDo(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "待办查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的已办（已处理完成事项）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页已办结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyDone(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));

            var result = _workflowEngineApp.QueryMyDone(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "已办查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的未办结（参与过/流程未完成事项）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页未办结结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyUnfinished(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));

            var result = _workflowEngineApp.QueryMyUnfinished(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "未办结查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的已完成（参与过/流程已归档事项）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页已完成结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyCompleted(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));

            var result = _workflowEngineApp.QueryMyCompleted(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "已完成查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 查询我的全部事项（拟办+待办+已办+未办结+已完成）
    /// </summary>
    /// <param name="pageQueryDto">分页查询参数</param>
    /// <returns>分页全部事项结果</returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>> QueryMyAllItems(
        [FromQuery] PageQueryRequestDto pageQueryDto)
    {
        try
        {
            var currentUser = _auth.GetCurrentUser().User;
            if (currentUser == null)
                return BadRequest(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail("未登录或登录过期"));
            var result = _workflowEngineApp.QueryMyAllItems(currentUser.Id, pageQueryDto);

            return Ok(ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Success(result, "全部事项查询成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResponseDto<PageQueryResultDto<FlowQuerySingleResultDto>>.Fail(ex.Message));
        }
    }

    #endregion

    /// <summary>
    ///  详情
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ActionResult<ApiResponseDto<dynamic>> Detail(string businessNo)
    {
        var detail = _workflowEngineApp.Detail(businessNo);
        return Ok(ApiResponseDto<dynamic>.Success(detail));
    }
}