using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Datory;
using GxPress.Entity.WorkFlow;
using GxPress.EnumConst;
using GxPress.Request.Notice;
using GxPress.Result;
using Newtonsoft.Json;

namespace GxPress.Service.Implement
{
    public partial class FlowService
    {
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="todoId"></param>
        /// <param name="isChecked"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task CheckAsync(int todoId, bool isChecked, string message)
        {
            var todo = await _flowTodoRepository.GetAsync(todoId);
            todo.IsChecked = isChecked;
            todo.Message = message;
            todo.IsDone = true;
            //是否当前操作
            todo.IsOperate = false;
            todo.DoneType = 0;
            var updated = await _flowTodoRepository.UpdateAsync(todo);
            var flow = await GetAsync(todo.FlowId);
            await _flowMessageRepository.InsertAsync(new FlowMessage
            {
                ProcessId = flow.ProcessId,
                FlowId = flow.Id,
                UserId = todo.UserId,
                Type = nameof(TodoTypeConst.ApproverCheck),
                Message = message
            });

            //var nodes = await GetNodesAsync(flow, await _processService.GetNodesAsync(flow.ProcessId, 0));
            // var isCheck = false;
            if (isChecked)
            {
                //修改状态
                if (todo.IsCaseOr && todo.ParentId > 0)
                {
                    var flowDtos = await _flowTodoRepository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.ParentId), todo.ParentId).Where(nameof(Entity.WorkFlow.FlowTodo.IsCaseOr), true));
                    foreach (var item in flowDtos)
                    {
                        item.IsOperate = false;
                        item.IsDone = true;
                        item.IsChecked = true;
                        await _flowTodoRepository.UpdateAsync(item);
                    }
                }
                // //修改状态
                // // await _flowRepository.UpdateStateAsync(flow.Id, nameof(FlowState.Checked));
                // //是否审核通过
                var checkedCount = await _flowTodoRepository.CountAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), flow.Id).Where(nameof(Entity.WorkFlow.FlowTodo.IsDone), true).Where(nameof(Entity.WorkFlow.FlowTodo.Type), nameof(TodoTypeConst.ApproverCheck)).Where(nameof(Entity.WorkFlow.FlowTodo.IsChecked), true));
                var allCount = await _flowTodoRepository.CountAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), flow.Id).Where(nameof(Entity.WorkFlow.FlowTodo.Type), nameof(TodoTypeConst.ApproverCheck)));
                //判断是否最后一个通过
                if (checkedCount == allCount)
                    await _flowRepository.UpdateStateAsync(flow.Id, nameof(FlowState.Checked));
                else
                {
                    //修改可操作人
                    var flowTodo = await _flowTodoRepository.GetAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.IsChecked), false).Where(nameof(Entity.WorkFlow.FlowTodo.IsDone), false).Where(nameof(Entity.WorkFlow.FlowTodo.Type), nameof(TodoTypeConst.ApproverCheck)).Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), todo.FlowId).OrderBy(nameof(Entity.WorkFlow.FlowTodo.Sort)));
                    if (flowTodo.IsCaseOr && flowTodo.ParentId > 0)
                    {
                        var flowDtos = await _flowTodoRepository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.ParentId), flowTodo.ParentId).Where(nameof(Entity.WorkFlow.FlowTodo.IsCaseOr), true).Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), flowTodo.FlowId));
                        foreach (var item in flowDtos)
                        {
                            item.IsOperate = true;
                            await _flowTodoRepository.UpdateAsync(item);
                        }
                    }
                    else
                    {
                        flowTodo.IsOperate = true;
                        await _flowTodoRepository.UpdateAsync(flowTodo);
                    }
                }
                // ProcessNodeDto nextApproverNode = null;
                // foreach (var processNodeDto in nodes)
                // {
                //     if (processNodeDto.Id == flow.ProcessNodeId)
                //     {
                //         // 当前节点如果是会签需要判断是否为当前节点的最后一个审核人
                //         if (processNodeDto.Type == nameof(ProcessNodeTypeConst.Approver) &&
                //             processNodeDto.ApprovalType == nameof(ApprovalTypeConst.And) &&
                //             processNodeDto.ApproverChecks != null)
                //         {
                //             var checkedUserIdList = await _flowTodoRepository.GetAllCheckedUserIdListAsync(flow.Id);
                //             var allUserIdList = await GetUserIdListAsync(processNodeDto.ApproverChecks);
                //             if (checkedUserIdList.Count() != allUserIdList.Count)
                //             {
                //                 return;
                //             }
                //         }
                //     }
                //     //判断是否进入下一阶段
                //     if (isCheck && processNodeDto.Id > flow.ProcessNodeId && processNodeDto.Type == nameof(ProcessNodeTypeConst.Approver))
                //     {
                //         nextApproverNode = processNodeDto;
                //         //设置节点
                //         await _flowRepository.UpdateProcessNodeIdAsync(flow.Id, processNodeDto.Id);
                //         break;
                //     }
                // }

                // if (nextApproverNode == null)
                // {
                //     if (isCheck)
                //     {
                //         //修改状态
                //         await _flowRepository.UpdateStateAsync(flow.Id, nameof(FlowState.Checked));
                //     }
                //     //await _flowTodoRepository.DeleteCheckingByFlowIdAsync(flow.Id);

                //     //await NodeExecuteAsync(flow, nodes.Last());
                // }
                // else
                // {
                //     //修改状态
                //     await _flowRepository.UpdateStateAsync(flow.Id, nameof(FlowState.Checking));
                //     await NodeExecuteAsync(flow, nextApproverNode);
                // }
            }
            else
            {
                //删除多余的审核人
                // await _flowTodoRepository.DeleteCheckingByFlowIdAsync(flow.Id);
                //修改工作流程状态
                await _flowRepository.UpdateStateAsync(flow.Id, nameof(FlowState.Denied));
                //await NodeExecuteAsync(flow, nodes.Last());
            }
        }

        public async Task<bool> RemindAsync(int flowId, int userId)
        {
            var flow = await GetFlowResult(flowId);
            var flowDto = await _flowRepository.GetAsync(flowId);
            var todo = await _flowTodoRepository.GetAsync(Q.Where(nameof(FlowTodo.FlowId), flowId).Where(nameof(FlowTodo.IsOperate), true));
            if (todo == null)
                return false;
            if (todo.IsRemind)
                return true;
            var user = await _userRepository.GetAsync(todo.UserId);
            //发送通知
            var request = new NoticeInRequest();
            request.Title = "工作流催办";
            request.UserId = flowDto.UserId;
            request.AddresseeUserMiddles = new List<Request.UserMiddle.UserMiddleInRequest>();
            request.AddresseeUserMiddles.Add(new Request.UserMiddle.UserMiddleInRequest { MiddleType = 10, SourceType = 0, SourceId = todo.UserId, SourceName = user.Name });
            request.NoticeType = NoticeTypeConst.Send;
            //构建数据
            var resultJson = new List<ContentJsonData>();
            // var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(result.Content);
            // foreach (var item in contentJsonData)
            //     item.File = StringUtils.AddDomain(item.File);
            // result.Data = contentJsonData;
            //文字
            var resultJsonText = new ContentJsonData();
            resultJsonText.Title = "催办工作流程";
            resultJsonText.Type = 1;
            resultJson.Add(resultJsonText);
            //审批
            var resultJsonFlow = new ContentJsonData();
            resultJsonFlow.Type = 14;
            resultJsonFlow.Id = flowId;
            resultJsonFlow.Title = flow.Name;
            resultJson.Add(resultJsonFlow);
            request.Content = JsonConvert.SerializeObject(resultJson);
            var boolValue = await _noticeService.InsertAsync(request);
            todo.IsRemind = true;
            await _flowTodoRepository.UpdateAsync(todo);
            return false;
        }

        public async Task TransferCheckAsync(int todoId, List<int> transferUserIds, string message, List<int> fileIds)
        {
            var todo = await _flowTodoRepository.GetAsync(todoId);
            // await _flowTodoRepository.DeleteAsync(todo.Id);
            var flow = await GetAsync(todo.FlowId);
            await _flowMessageRepository.InsertAsync(new FlowMessage
            {
                ProcessId = flow.ProcessId,
                FlowId = flow.Id,
                UserId = todo.UserId,
                Type = nameof(TodoTypeConst.ApproverCheck),
                Message = message,
                FileIds = fileIds
            });
            //判断是否存在专审 存在就提示
            var flowTodo = await _flowTodoRepository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), todo.FlowId).Where(nameof(Entity.WorkFlow.FlowTodo.Type), nameof(TodoTypeConst.ApproverCheck)));
            if (flowTodo.Select(n => n.UserId).Any(n => transferUserIds.Contains(n)))
            {
                throw new Exception("转审人或者审核人已存在！");
            }
            if (transferUserIds.Count > 0)
            {
                //获取其他审核人
                var flowTodos = await _flowTodoRepository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowTodo.FlowId), todo.FlowId).Where(nameof(Entity.WorkFlow.FlowTodo.Sort), ">", todo.Sort));
                foreach (var item in flowTodos)
                {
                    item.Sort = item.Sort + transferUserIds.Count;
                    await _flowTodoRepository.UpdateSortAsync(item);
                }
            }
            var sort = 1;
            foreach (var transferUserId in transferUserIds)
            {
                var flowTo = new Entity.WorkFlow.FlowTodo();
                flowTo.UserId = transferUserId;
                flowTo.IsChecked = false;
                flowTo.IsDone = false;
                flowTo.IsRead = false;
                flowTo.FlowId = flow.Id;
                flowTo.ProcessId = flow.ProcessId;
                flowTo.Type = nameof(TodoTypeConst.ApproverCheck);
                flowTo.IsOperate = sort == 1 ? true : false;
                flowTo.Sort = todo.Sort + sort;
                await _flowTodoRepository.InsertAsync(flowTo);
                sort++;
            }
            //修改当前用户状态
            todo.Message = message;
            todo.IsDone = true;
            todo.FileIds = fileIds;
            todo.IsChecked = true;
            todo.IsOperate = false;
            //已转审
            todo.IsReferral = true;
            await _flowTodoRepository.UpdateAsync(todo);
        }
    }
}