using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Siger.ApiKPI.Controllers
{
    public class AuthorityController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectUserGroupRepository _sigerProjectUserGroup;
        private readonly ISigerKpiAuthority _kpiAuthority;

        public AuthorityController(IUnitOfWork unitOfWork,ISigerProjectUserGroupRepository sigerProjectUserGroup, ISigerKpiAuthority kpiAuthority)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectUserGroup = sigerProjectUserGroup;
            _kpiAuthority = kpiAuthority;
        }
        /// <summary>
        /// 获取items
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Items(int usergroup)
        {
           var data= _kpiAuthority.GetList(f => f.projectId == ProjectId && f.usergroup == usergroup);

            return new ObjectResult(data);
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="kpiAuthority"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestKpiAuthority kpiAuthority)
        {
            var groupObj = _sigerProjectUserGroup.Get(kpiAuthority.usergroup);
            if (groupObj==null)
                throw new BadRequestException(RequestEnum.UserGroupNotFound);

            var items = _kpiAuthority.GetList(f => f.projectId == ProjectId && f.usergroup == groupObj.id).ToList();
            foreach(var item in items)
            {
                _kpiAuthority.Delete(item.id);
            }

            foreach(var it in kpiAuthority.section)
            {
                _kpiAuthority.Insert(new Middlelayer.KpiRespository.Entities.siger_project_kpi_authority
                {
                     authorization=it,
                     mid=UserId,
                     operate=DateTime.Now,
                     projectId=ProjectId,
                     usergroup=kpiAuthority.usergroup,
                     status=(int)RowState.Valid
                });
            }
            
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
    }
}
