using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.KpiRespository.Respose;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiKPI.Controllers
{

    public class ItemDisplayController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiItem _sigerKpiitem;
        private readonly ISigerKpiAuthority _kpiAuthority;
        private readonly ISigerKpiItemDisplaySetting _sigerKpiItemDisplaySetting;
        private readonly ISigerProjectSectionRepository _sigerProjectSection;
        private readonly ISigerProjectUserRepository _sigerProjectUser;
        private readonly ISigerKpiItemDisplayPosition _itemDisplayPosition;

        public ItemDisplayController(IUnitOfWork unitOfWork, ISigerKpiItem sigerKpi, ISigerKpiAuthority kpiAuthority, ISigerKpiItemDisplaySetting sigerKpiItemDisplay, ISigerProjectSectionRepository sigerProjectSection, ISigerProjectUserRepository sigerProjectUser, ISigerKpiItemDisplayPosition itemDisplayPosition)
        {
            _unitOfWork = unitOfWork;
            _sigerKpiitem = sigerKpi;
            _kpiAuthority = kpiAuthority;
            _sigerKpiItemDisplaySetting = sigerKpiItemDisplay;
            _sigerProjectSection = sigerProjectSection;
            _sigerProjectUser = sigerProjectUser;
            _itemDisplayPosition = itemDisplayPosition;
        }
        /// <summary>
        /// 获取指标展示位置
        /// </summary>
        /// <param name="section"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPosition(int section, int page = 1, int pageSize = 999999)
        {
            var permission = _kpiAuthority.VerifyPermission(UserId, section);
            var listResult = new List<ResponseItemDisplay>();
            var display = _itemDisplayPosition.GetList(f => f.projectId == ProjectId && f.Section == section && f.status == (int)RowState.Valid).ToList();
            if (!display.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var sections = _sigerProjectSection.GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid);
            foreach (var d in display)
            {
                var item = _sigerKpiitem.Get(f => f.id == d.Item);
                if (item == null)
                    continue;
                var diplaySection = sections.FirstOrDefault(f => f.id == d.Section);
                var itemSection = sections.FirstOrDefault(f => f.id == item.Section);
                listResult.Add(new ResponseItemDisplay
                {
                    Id = d.id,
                    ItemId = d.Item,
                    ItemDesc = item.Item,
                    Section = d.Section,
                    SectionDesc = diplaySection != null ? diplaySection.title : "",
                    ItemSection = item.Section,
                    ItemSectionDesc = itemSection != null ? itemSection.title : "",
                    Cycle = item.KpiCycle,
                    KpiCycleDesc = EnumHelper.GetEnumDesc(item.KpiCycle),
                    Color = d.Color,
                    Position = d.Position,
                    Permission = permission ? 1 : 0

                });
            }
            return new ObjectResult(listResult);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemsObj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]KpiItemsObj itemsObj)
        {
            var currUser = _sigerProjectUser.Get(f => f.mid == UserId);
            if (currUser == null)
                throw new BadRequestException(RequestEnum.UserIsEmpty);


            var permission = _kpiAuthority.VerifyPermission(UserId, itemsObj.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            var positionObj = _itemDisplayPosition.Get(f => f.projectId == ProjectId && f.Section == itemsObj.Section && f.Item == itemsObj.ItemId);
            if (positionObj != null)
                throw new BadRequestException(CommonEnum.RecordExits);

            _itemDisplayPosition.Insert(new SigerProjectKpiItemDisplayPosition
            {
                Position = itemsObj.Position,
                projectId = ProjectId,
                Item = itemsObj.ItemId,
                Section = itemsObj.Section,
                Color = itemsObj.BackColor,
                status = (int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 编辑/删除位置
        /// </summary>
        /// <param name="itemsObj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ModifyPosition([FromBody]KpiItemsObj itemsObj)
        {
            var permission = _kpiAuthority.VerifyPermission(UserId, itemsObj.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            var layout = _sigerKpiItemDisplaySetting.Get(f => f.projectId == ProjectId && f.id == itemsObj.Layout);
            if (layout == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var positionObj = _itemDisplayPosition.Get(f => f.id == itemsObj.Id);
            //positionObj.Section = currUser.sectionid;
            positionObj.Section = itemsObj.Section;
            positionObj.Position = itemsObj.Position;
            positionObj.Item = itemsObj.ItemId;
            positionObj.Color = itemsObj.BackColor;
            _itemDisplayPosition.Update(positionObj);

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Del(int id, int section)
        {
            var permission = _kpiAuthority.VerifyPermission(UserId, section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            var positionObj = _itemDisplayPosition.Get(f => f.id == id);
            if (positionObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            _itemDisplayPosition.Delete(id);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 下来列表
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetItemList(int section)
        {
            Expression<Func<siger_project_kpi_item, bool>> FunSection = f => true;

            if (section == 0)
            {
                var user = _sigerProjectUser.Get(f => f.mid == UserId);
                if (user != null)
                    section = user.sectionid;
            }
            var data = _sigerKpiitem.GetList(f => f.projectId == ProjectId && f.Section == section && f.status == (int)RowState.Valid);
            var reslut = new List<ResponseKeyValue>();
            var dataGrp = data.GroupBy(d => d.Item);
            foreach (var d in data)
            {
                var cycleDesc = EnumHelper.GetEnumDesc(d.KpiCycle);
                reslut.Add(new ResponseKeyValue
                {
                    Id = d.id,
                    Title = $"{d.Item} - {cycleDesc}"
                });
            }

            return new ObjectResult(reslut);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetItem(int section)
        {
            if (section == 0)
            {
                var user = _sigerProjectUser.Get(f => f.mid == UserId);
                if (user != null)
                    section = user.sectionid;
            }
            var data = _sigerKpiitem.GetList(f => f.projectId == ProjectId && f.Section == section && f.status == (int)RowState.Valid);
            var reslut = new List<ResponseKeyValue>();
            var dataGrp = data.GroupBy(d => d.Item);
            foreach (var g in dataGrp)
            {
                reslut.Add(new ResponseKeyValue
                {
                    Id = g.FirstOrDefault()?.id ?? 1,
                    Title = g.Key
                });
            }
            return new ObjectResult(reslut);
        }
    }
}
