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.Helpers;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;
using Siger.Middlelayer.Repository.Response;

namespace Siger.ApiConfig.Controller
{
    public class ProjectSectionController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectSectionRepository _projectSectionRepository;
        private readonly ISigerProjectUserGroupRepository _sigerProjectUserGroup;
        private readonly ISigerUserRoleRepository _sigerUserRoleRepository;
        private readonly ISigerProjectUserRepository _sigerProjectUser;

        public ProjectSectionController(IUnitOfWork unitOfWork, ISigerProjectSectionRepository projectSectionRepository, ISigerProjectUserGroupRepository sigerProjectUserGroup,
            ISigerUserRoleRepository sigerUserRoleRepository,ISigerProjectUserRepository sigerProjectUser)
        {
            _unitOfWork = unitOfWork;
            _sigerUserRoleRepository = sigerUserRoleRepository;
            _sigerProjectUser = sigerProjectUser;
            _projectSectionRepository = projectSectionRepository;
            _sigerProjectUserGroup = sigerProjectUserGroup;
        }

        [HttpGet]
        public IActionResult GetSections()
        {
            var reponse = new List<ResponseIdTitle>();

            var list = _projectSectionRepository.GetList(q => q.status == (int) RowState.Valid && q.projectid == ProjectId).ToList();

            foreach (var sigerProjectSection in list)
            {
                reponse.Add(Mapper<siger_project_section, ResponseIdTitle>.Map(sigerProjectSection));
            }
            return new ObjectResult(reponse);
        }

        [HttpGet]
        public IActionResult SelectSectionItem(int id, int page = 1, int pagesize = PageSize)
        {
            var response =  new List<ResponseGetSections>();

            var list = _projectSectionRepository.GetList(q => q.status == (int) RowState.Valid && q.id == id).ToList();

            foreach (var sigerProjectSection in list)
            {
                var section = Mapper<siger_project_section, ResponseGetSections>.Map(sigerProjectSection);
                section.create_time = UnixTimeHelper.ConvertStringDateTime(sigerProjectSection.create_time.ToString())
                    .ToString(ParameterConstant.DateTimeFormat);
                response.Add(section);
            }
            return new PagedObjectResult(response, list.Count, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddSection([FromBody] RequestAddSection request)
        {
            var isExist = _projectSectionRepository.IsExist(q => q.title == request.title && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(RequestEnum.SectionHasExist);
            }

            var name  = request.title + "_" + ProjectId;
            var roleId = _sigerUserRoleRepository.AddUserRole(name, 2);

            var section = new siger_project_section();
            section.type = request.type;
            section.description = request.description;
            section.title = request.title;
            section.projectid = ProjectId;
            section.create_mid = UserId;
            section.role_id = roleId;
            section.create_time = UnixTimeHelper.GetNow();
            _projectSectionRepository.Insert(section);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult UpdateSection([FromBody] RequestUpdateSection request)
        {
            var section = _projectSectionRepository.Get(request.id);
            if (section == null || section.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.SectionNotFound);
            }
            var isExist = _projectSectionRepository.IsExist(q => q.title == request.title && q.projectid == ProjectId 
                                                                                          && q.id != section.id && q.status == (int)RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(RequestEnum.SectionHasExist);
            }
            section.type = request.type;
            section.description = request.description;
            section.title = request.title;
            section.create_mid = UserId;
            
            _projectSectionRepository.Update(section);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteSection(int id)
        {
            var section = _projectSectionRepository.Get(q => q.id == id && q.create_mid == UserId);
            if (section == null)
            {
                throw new BadRequestException(RequestEnum.SectionNotFound);
            }
            var usergroup = _sigerProjectUserGroup.GetList(q => q.sectionid==section.id && q.status == (int)RowState.Valid);
            if (usergroup.Any())
            {
                throw new BadRequestException(RequestEnum.IsUsedNotDelete);
            }
            section.status = (int) RowState.Invalid;
            _projectSectionRepository.Update(section);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpGet]
        public IActionResult GetCurrentDepart()
        {
            var user = _sigerProjectUser.Get(f => f.projectid == ProjectId && f.mid == UserId);
            if (user==null)
                throw new BadRequestException(RequestEnum.SectionIDNotNull);
            var deprt = _projectSectionRepository.Get(f => f.projectid == ProjectId && f.id == user.sectionid);
            return new ObjectResult(deprt);
        }
    }
}