using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.EsopRepository.Entities;
using Siger.Middlelayer.EsopRepository.Repositories.Interface;
using Siger.Middlelayer.EsopRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;

namespace Siger.ApiEsop.Controllers
{
    public class EsopDocumentSetController : BaseController
    {

        private readonly IEsopDocumentSetRepository _documentSetRepository;
        private readonly IEsopDocumentCreateRepository _documentCreateRepository;
        private readonly ISigerProjectUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;

        public EsopDocumentSetController(IEsopDocumentSetRepository documentSetRepository, IEsopDocumentCreateRepository documentCreateRepository,
            ISigerProjectUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            _documentSetRepository = documentSetRepository;
            _documentCreateRepository = documentCreateRepository;
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
        }

        [HttpGet]
        public IActionResult GetDocumentSetPagedList(int page = 1, int pagesize = 10)
        {
            var data = _documentSetRepository.GetDocumentSetList(ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddDocumentSet([FromBody]RequestAddDocumentSet request)
        {
            var isExist = _documentSetRepository.IsExist(q => q.name == request.name && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            var entity = new siger_project_esop_document_set
            {
                project_id = ProjectId,
                create_time = DateTime.Now,
                creator_mid = UserId,
                name = request.name,
                need_train = request.need_train.ToInt(),
                process_id = request.process_id.ToInt(),
                sign_usergroup_id = request.sign_usergroup_id.ToInt(),
                usergroup_ids = request.usergroup_ids
            };
            _documentSetRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult UpdateDocumentSet([FromBody]RequestUpdateDocumentSet request)
        {
            var entity = _documentSetRepository.Get(request.id);
            if (entity == null || entity.status != (int) RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var isExist = _documentSetRepository.IsExist(q => q.name == request.name && q.project_id == ProjectId && q.status == (int) RowState.Valid
                                                              && q.id != request.id);
            if (isExist)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            entity.name = request.name;
            entity.need_train = request.need_train.ToInt();
            entity.process_id = request.process_id.ToInt();
            entity.sign_usergroup_id = request.sign_usergroup_id.ToInt();
            entity.usergroup_ids = request.usergroup_ids;
            _documentSetRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult DeleteDocumentSet(int id)
        {
            var entity = _documentSetRepository.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var document = _documentCreateRepository.Get(q => q.type_id == entity.id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (document != null)
            {
                throw new BadRequestException(RequestEnum.CannotDelete);
            }

            entity.status = (int) RowState.Invalid;
            _documentSetRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取有权限的文档类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllDocumentSets(int type = 0)
        {
            var projectUser = _userRepository.GetUserInfo(UserId);
            if (projectUser == null)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }

            var sets = _documentSetRepository.GetList(q => q.project_id == ProjectId && q.status == (int)RowState.Valid).OrderByDescending(m => m.create_time)
                .Select(m => new
                {
                    m.id,
                    m.name,
                    m.usergroup_ids
                }).ToList();

            var responses = new List<ResponseIdName>();

            foreach (var set in sets)
            {
                if (type == 0)
                {
                    if (string.IsNullOrWhiteSpace(set.usergroup_ids))
                    {
                        continue;
                    }

                    if (projectUser.usertype == (int)UserType.User)
                    {
                        var ids = set.usergroup_ids.Split(',');
                        if (ids.Contains(projectUser.usergroupid.ToStr()))
                        {
                            responses.Add(new ResponseIdName
                            {
                                id = set.id,
                                name = set.name
                            });
                        }
                    }
                    else //管理员有全部权限
                    {
                        responses.Add(new ResponseIdName
                        {
                            id = set.id,
                            name = set.name
                        });
                    }
                }
                else
                {
                    responses.Add(new ResponseIdName
                    {
                        id = set.id,
                        name = set.name
                    });
                }
            }

            return new ObjectResult(responses);
        }
    }
}