using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GxPress.Api.AdminControllers;
using GxPress.Auth;
using GxPress.Entity.WorkFlowDto;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.WorkFlow;
using GxPress.Repository.Interface.WorkProcess;
using GxPress.Request.App.Flow;
using GxPress.Result.App;
using GxPress.Result.App.Flow;
using GxPress.Service.Interface;
using GxPress.Service.Interface.Doc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace GxPress.Api.AppControllers
{
    /// <summary>
    /// 通讯录用户信息
    /// </summary>
    [Route("api/app/flow")]
    [ApiController]
    [Authorize]
    public partial class AppFlowController : ControllerBase
    {
        private readonly ILogger<AppVersionController> _logger;
        private readonly IWebHostEnvironment _environment;
        private readonly ILoginContext _loginContext;
        private readonly IFlowMessageRepository _flowMessageRepository;
        private readonly IFlowTodoRepository _flowTodoRepository;
        private readonly IProcessRepository _processRepository;
        private readonly IProcessService _processService;
        private readonly IFlowService _flowService;
        private readonly IUserRepository _userRepository;
        private readonly IFlowRepository _flowRepository;
        private readonly IDocService docService;

        public AppFlowController(
            ILogger<AppVersionController> logger,
            IWebHostEnvironment environment,
            ILoginContext loginContext,
            IFlowMessageRepository flowMessageRepository,
            IFlowTodoRepository flowTodoRepository,
            IProcessRepository processRepository,
            IProcessService processService,
            IFlowService flowService,
            IUserRepository userRepository,
            IFlowRepository flowRepository, IDocService docService
            )
        {
            _logger = logger;
            _environment = environment;
            _loginContext = loginContext;
            _flowMessageRepository = flowMessageRepository;
            _flowTodoRepository = flowTodoRepository;
            _processRepository = processRepository;
            _processService = processService;
            _flowService = flowService;
            _userRepository = userRepository;
            _flowRepository = flowRepository;
            this.docService = docService;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(int id)
        {
            await _flowService.DeleteAsync(id);
        }

        /// <summary>
        /// 添加工作项
        /// </summary>
        /// <param name="flow">工作项</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<FlowDto> Add([FromBody] FlowDto flow)
        {
            flow.State = FlowState.Checking;
            flow.UserId = _loginContext.AccountId;
            if (flow.Id > 0)
                await _flowService.DeleteAsync(flow.Id);
            flow.Id = await _flowService.AddAsync(flow);
            await _flowService.AddInboxAsyc(flow);
            return flow;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [AllowAnonymous]
        public async Task<FlowResult> Get(int id)
        {
            await _flowTodoRepository.UpdateCCIsDoneAsync(_loginContext.AccountId, id);
            return await _flowService.GetFlowResult(id, _loginContext.AccountId);
        }
        /// <summary>
        /// 获取详情 web专属
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("web/{id}")]
        [AllowAnonymous]
        public async Task<FlowResult> GetWeb(int id)
        {
            //await _flowTodoRepository.UpdateCCIsDoneAsync(_loginContext.AccountId, id);
            return await _flowService.GetFlowResult(id, 0);
        }
        /// <summary>
        /// 获取工作项列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ListResult> List([FromQuery] FlowListRequest request)
        {
            var userId = _loginContext.AccountId;

            if (request.Type == nameof(FlowListTypeConst.MyChecking))
            {
                return await _flowService.ListMyCheckingAsync(userId, request, nameof(FlowListTypeConst.MyChecking));
            }

            if (request.Type == nameof(FlowListTypeConst.MyChecked))
            {
                return await _flowService.ListMyCheckedAsync(userId, request, nameof(FlowListTypeConst.MyChecked));
            }

            if (request.Type == nameof(FlowListTypeConst.CcUnread))
            {
                return await _flowService.ListCcUnreadAsync(userId, request);
            }

            if (request.Type == nameof(FlowListTypeConst.CcAll))
            {
                return await _flowService.ListCcAllAsync(userId, request);
            }

            if (request.Type == nameof(FlowListTypeConst.SubmittedChecking))
            {
                return await _flowService.ListSubmittedCheckingAsync(userId, request);
            }

            if (request.Type == nameof(FlowListTypeConst.SubmittedChecked))
            {
                return await _flowService.ListSubmittedCheckedAsync(userId, request);
            }

            return new ListResult();
        }
        /// <summary>
        /// 获取工作项列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<ListResult> PostList(FlowListRequest request)
        {
            var userId = _loginContext.AccountId;

            if (request.Type == nameof(FlowListTypeConst.MyChecking))
            {
                return await _flowService.ListMyCheckingAsync(userId, request, nameof(FlowListTypeConst.MyChecking));
            }

            if (request.Type == nameof(FlowListTypeConst.MyChecked))
            {
                return await _flowService.ListMyCheckedAsync(userId, request, nameof(FlowListTypeConst.MyChecked));
            }

            if (request.Type == nameof(FlowListTypeConst.CcUnread))
            {
                return await _flowService.ListCcUnreadAsync(userId, request);
            }

            if (request.Type == nameof(FlowListTypeConst.CcAll))
            {
                return await _flowService.ListCcAllAsync(userId, request, nameof(FlowListTypeConst.CcAll));
            }

            if (request.Type == nameof(FlowListTypeConst.SubmittedChecking))
            {
                return await _flowService.ListSubmittedCheckingAsync(userId, request, nameof(FlowListTypeConst.SubmittedChecking));
            }

            if (request.Type == nameof(FlowListTypeConst.SubmittedChecked))
            {
                return await _flowService.ListSubmittedCheckedAsync(userId, request);
            }

            return new ListResult();
        }

        /// <summary>
        /// 待办事项
        /// </summary>
        /// <returns></returns>
        [HttpGet("todo")]
        [AllowAnonymous]
        public async Task<ListResult> TodoList([FromQuery] AdminFlowController.ListRequest request)
        {
            var userId = _loginContext.AccountId;
            var flowListRequest = new FlowListRequest();
            flowListRequest.Page = request.Page;
            flowListRequest.PerPage = request.PerPage;
            var result = await _flowService.ListMyCheckingAsync(userId, flowListRequest, nameof(FlowListTypeConst.MyChecking));
            return new ListResult
            {
                Count = result.Count,
                Items = result.Items
            };
            // var flowTodoList = await _flowService.GetTodoListAsync(userId, request.Page, request.PerPage, request.ProcessId);
            // var resultList = new List<FlowTodoResult>();
            // foreach (var flowTodo in flowTodoList)
            // {
            //     //新增
            //     if (flowTodo.IsDone)
            //         continue;
            //     var flow = await _flowService.GetAsync(flowTodo.FlowId);
            //     var user = await _userRepository.GetAsync(flow.UserId);
            //     if (user == null || flow == null) continue;

            //     var result = new FlowTodoResult
            //     {
            //         Id = flowTodo.Id,
            //         ProcessId = flowTodo.ProcessId,
            //         FlowId = flowTodo.FlowId,
            //         UserId = flowTodo.UserId,
            //         Type = flowTodo.Type,
            //         State = flow.State,
            //         IsDone = false,
            //         CreatedDate = flowTodo.CreatedDate
            //     };
            //     var (title, summaries) = await _flowService.GetFlowTitleAndSummaryAsync(user, flow.ProcessId, flow.Id);
            //     result.Title = title;
            //     result.AvatarUrl = _userRepository.GetAvatarUrl(user);
            //     result.Summaries = summaries;
            //     resultList.Add(result);
            // }

            // return new TodoListResult
            // {
            //     Count = await _flowService.GetTodoCountAsync(userId),
            //     Items = resultList
            // };

            //    //return resultList.ToList();
            //}
        }

        /// <summary>
        /// 获取数字
        /// </summary>
        /// <returns></returns>
        [HttpGet("count")]
        [AllowAnonymous]
        public async Task<GetCountResult> GetCount()
        {
            var userId = _loginContext.AccountId;
            var request = new FlowListRequest();

            var result = new GetCountResult
            {
                MyCheckingCount =
                   await _flowTodoRepository.GetCountAsync(userId, nameof(TodoTypeConst.ApproverCheck), false,
                    request),
                MyCheckedCount =
                    await _flowTodoRepository.GetCountAsync(userId, nameof(TodoTypeConst.ApproverCheck), true, request),
                SubmittedCheckingCount = await _flowRepository.GetCountByUserIdAsync(userId, true, request),
                //SubmittedCheckedCount= await _flowTodoRepository.GetUReadCountAsync(userId, "CarbonCopy",false,request),
                SubmittedCheckedCount = await _flowRepository.GetCountByUserIdAsync(userId, false, request),
                CcUnreadCount =
                    await _flowTodoRepository.GetReadCountAsync(userId, nameof(TodoTypeConst.CarbonCopy), request, false),
                CcAllCount = await _flowTodoRepository.GetReadCountAsync(userId, nameof(TodoTypeConst.CarbonCopy), request, true)
            };
            return result;
        }

        /// <summary>
        /// 获取筛选
        /// </summary>
        /// <returns></returns>
        [HttpGet("filter")]
        [AllowAnonymous]
        public async Task<List<Option>> Filter()
        {
            var processes = await _processRepository.GetListByDepartmentIdAsync(_loginContext.DepartmentId);
            var list = processes.Select(x => new Option
            {
                Label = x.Name,
                Value = x.Id
            }).ToList();
            list.Insert(0, new Option
            {
                Label = "全部",
                Value = 0
            });
            return list;
        }
    }
}