using Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App.Request;
using OpenAuth.App;
using OpenAuth.Repository.Domain;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
using Microsoft.AspNetCore.Authorization;
using OpenAuth.App.BaseApp.WFTask;
using Infrastructure.Extensions;
using SqlSugar;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// 流程实例任务
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WFTaskController : ControllerBase
    {
        WFTaskApp taskApp;
        WFProcessApp processApp;
        WFSchemeInfoApp schemeInfoApp;
        IAuth auth;

        public WFTaskController(WFTaskApp taskApp, WFProcessApp processApp, WFSchemeInfoApp schemeInfoApp, IAuth auth)
        {
            this.taskApp = taskApp;
            this.processApp = processApp;
            this.schemeInfoApp = schemeInfoApp;
            this.auth = auth;
        }

        #region 查询

        #region 实例
        /// <summary>
        /// 实例
        /// workflow/process/task/{id}
        /// </summary>
        /// <param name="id">任务id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<WFTaskDto>> Get(string id)
        {
            var res = new WFTaskDto();
            res.Task = taskApp.GetEntity(id);
            res.Process = await processApp.GetEntity(res.Task.ProcessId);
            res.Scheme = await schemeInfoApp.GetSchemeEntity(res.Process.SchemeId);
            res.Logs = await taskApp.GetLogList(res.Task.ProcessId);
            res.Tasks = await taskApp.GetUnFinishTaskList(res.Task.ProcessId);
            return new Response<WFTaskDto>
            {
                Result = res,
                Message = "success"
            };
        }

        /// <summary>
        /// 适配 BPMN
        /// </summary>
        /// <param name="id">wfTask id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<BPMNWFTaskDto>> GetBPMN(string id)
        {
            var res = new BPMNWFTaskDto();
            res.Task =  taskApp.GetEntity(id);
            res.FlowViewer = new FlowUnit();
            var process = await processApp.GetEntity(res.Task.ProcessId);
            res.Process = process;
            var scheme = await schemeInfoApp.GetSchemeEntity(res.Process.SchemeId);
            res.Scheme = scheme;
            res.FlowContent = scheme.FlowContent;

            res.Logs = await taskApp.GetLogList(res.Task.ProcessId);

            var unfinishTasks = await taskApp.GetUnFinishTaskList(res.Task.ProcessId);
            res.Tasks = unfinishTasks;
            res.FlowViewer.UnfinishedTaskSet = unfinishTasks.Select(a => a.UnitId).ToList();


            List<string> unfids = new List<string>();
            if (unfinishTasks.Count() > 0)
            {
                unfids = unfinishTasks.Select(r => r.Id).ToList();
            }
            var finishTasks = await taskApp.GetFinishTaskList(res.Task.ProcessId, unfids);
            res.FlowViewer.FinishedTaskSet = finishTasks.Select(a => a.UnitId).ToList();

            return new Response<BPMNWFTaskDto>
            {
                Result = res,
                Message = "success"
            };
        }
        #endregion

        #region 任务 byToken
        /// <summary>
        /// 任务 byToken
        /// workflow/process/task/token/{token}
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<WFTaskDto>> GetTaskByToken(string token)
        {
            var res = new WFTaskDto();
            res.Task = await taskApp.GetEntityByToken(token, auth.GetUserId());
            if (res.Task == null)
            {
                throw new Exception("当前任务已经结束！");
            }
            res.Process = await processApp.GetEntity(res.Task.ProcessId);
            res.Scheme = await schemeInfoApp.GetSchemeEntity(res.Process.SchemeId);
            res.Logs = await taskApp.GetLogList(res.Task.ProcessId);
            res.Tasks = await taskApp.GetUnFinishTaskList(res.Task.ProcessId);
            return new Response<WFTaskDto>
            {
                Result = res,
                Message = "success"
            };
        }
        #endregion

        #region 我的待办分页
        /// <summary>
        /// 我的待办分页
        /// workflow/process/uncompleted/mypage
        /// </summary>
        /// <param name="PageReq">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<WFTask>>>> LoadMyUncompletedPage([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams, string category)
        {
            var pageInfo = await taskApp.GetMyUncompletedPageList(pageReq, searchParams,category);
            return new Response<PageInfo<List<WFTask>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        /// <summary>
        /// 我的待办分页
        /// workflow/process/uncompleted/mypage
        /// </summary>
        /// <param name="PageReq">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<WFTask>>>> LoadMyUncompletedPage1([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams, string category)
        {
            var pageInfo = await taskApp.GetMyUncompletedPageList1(pageReq, searchParams,category);
            return new Response<PageInfo<List<WFTask>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        #endregion

        #region 我的已办分页
        /// <summary>
        /// 我的已办分页
        /// workflow/process/completed/mypage
        /// </summary>
        /// <param name="PageReq">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<WFTask>>>> LoadMyCompletedPage([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams, string category)
        {
            var pageInfo = await taskApp.GetMyCompletedPageList(pageReq, searchParams, category);

            return new Response<PageInfo<List<WFTask>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        #endregion

        #region 我的传阅分页
        /// <summary>
        /// 获取我的传阅任务
        /// workflow/process/read/mypage
        /// </summary>
        /// <param name="pageReq">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<WFTask>>>> LoadMyReadPage([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams,string category)
        {
            var pageInfo = await taskApp.GetMyReadPageList(pageReq, searchParams, category);

            return new Response<PageInfo<List<WFTask>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }

        #endregion

        #region 我的委托分页
        /// <summary>
        /// 我的委托分页
        /// workflow/process/delegate/mypage
        /// </summary>
        /// <param name="paginationInputDto">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<WFTask>>>> LoadMyDelegatePage([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams, string category)
        {
            var pageInfo = await taskApp.GetMyDelegatePageList(pageReq, searchParams, category);

            return new Response<PageInfo<List<WFTask>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        #endregion

        #region 我的可撤回案件
        /// <summary>
        /// 获取我的可撤回案件
        /// </summary>
        /// <param name="pageReq"></param>
        /// <param name="searchParams"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        [HttpGet]
        public Response<PageInfo<List<dynamic>>> GetRetractPageList([FromQuery] PageReq pageReq, [FromQuery] WFProcessSearchDto searchParams, string category)
        {
            var pageInfo = taskApp.GetRetractPageList(pageReq, searchParams, category);

            return new Response<PageInfo<List<dynamic>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        #endregion
        #endregion


        #region 根据案件id，查询当前应该执行的任务
        /// <summary>
        /// 根据案件id，查询当前应该执行的任务
        /// </summary>
        /// <param name="caseid">案件id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<dynamic>> GetTaskByCaseId(string caseid)
        {
            Response<dynamic> response = new Response<dynamic>();
            try
            {
                response.Result = await taskApp.GetTaskByCaseId(caseid);
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return response;
        }
        #endregion

        #region
        /// <summary>
        /// 修改地类类型（仅限农用地到建设用地，待接收状态）
        /// </summary>
        /// <param name="caseno">案件编号</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateCaseinfoTypeKC(string caseno)
        {
            var result = new Response<bool>();
            try
            {
                result = await taskApp.UpdateCaseinfoTypeKC(caseno);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取任务列表(地类类型修改专用）
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<WFTask>>> GetTaskList(string processId)
        {
            var result = await taskApp.GetTaskList(processId);

            return new Response<List<WFTask>>
            {
                Result = result,
                Message = "success"
            };
        }

        /// <summary>
        /// 获取任务日志列表(地类类型修改专用）
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<WFTaskLog>>> GetTaskLogList(string processId)
        {
            var result = await taskApp.GetTaskLogList(processId);

            return new Response<List<WFTaskLog>>
            {
                Result = result,
                Message = "success"
            };
        }

        /// <summary>
        /// 删除任务（地类类型修改专用）
        /// </summary>
        /// <param name="ids">任务ids</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteTaskByIds(string ids)
        {
            var result = new Response<bool>();
            try
            {
                result = await taskApp.DeleteTaskByIds(ids);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 删除任务日志（地类类型修改专用）
        /// </summary>
        /// <param name="ids">任务ids</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteTaskLogByIds(string ids)
        {
            var result = new Response<bool>();
            try
            {
                result = await taskApp.DeleteTaskLogByIds(ids);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 更新任务（地类修改专用）
        /// </summary>
        /// <param name="wfTaskEntity">任务</param>
        [HttpPost]
        public async Task<Response<bool>> UpdateTask(WFTask wfTaskEntity)
        {
            var result = new Response<bool>();
            try
            {
                result = await taskApp.UpdateTask(wfTaskEntity);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 更新任务日志（地类修改专用）
        /// </summary>
        /// <param name="wfTasklogEntity">任务日志</param>
        [HttpPost]
        public async Task<Response<bool>> UpdateTaskLog(WFTaskLog wfTasklogEntity)
        {
            var result = new Response<bool>();
            try
            {
                result = await taskApp.UpdateTaskLog(wfTasklogEntity);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion
    }
}
