using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Common;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.KpiRespository.Respose;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common.AppSettings;
using Siger.ApiCommon.Utilities;
using System.IO;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiKPI.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class ItemController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiItem _sigerKpitem;
        private readonly ISigerKpiAuthority _kpiAuthority;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="unitOfWork"></param>
        /// <param name="sigerKpi"></param>
        /// <param name="kpiAuthority"></param>
        public ItemController(IUnitOfWork unitOfWork, ISigerKpiItem sigerKpi, ISigerKpiAuthority kpiAuthority)
        {
            _sigerKpitem = sigerKpi;
            _kpiAuthority = kpiAuthority;
            _unitOfWork = unitOfWork;
        }
        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetItems(int section,string item,int page,int pageSize)
        {

            var items = _sigerKpitem.GetKPItemPagedList(section, item, ProjectId, page, pageSize);
            var result = items.Data;
            var permission = _kpiAuthority.VerifyPermission(UserId, section);
          


            foreach(var r in result)
            {
                r.Permission = permission ? 1 : 0;
                r.ConditionDesc = EnumHelper.GetEnumDesc((KpiCondition)r.Condition);
                r.KpiCycleDesc = EnumHelper.GetEnumDesc(r.KpiCycle);

            }
            return new PagedObjectResult(items.Data, items.Total, page, pageSize);

        }
        [HttpGet]
        public IActionResult GetItemTree(int section)
        {
            var result = new List<ResponseItemTree>();
            var data = _sigerKpitem.GetKpiItems(section, ProjectId);
            var departGrp = data.GroupBy(g => g.Section);
            foreach(var g in departGrp)
            {
                var node = new ResponseItemTree
                {
                    id = g.Key,
                    title = g.FirstOrDefault().Department,
                    expand=true,
                    children = new List<ResponseItemTree>()
                };
                var items = g.ToList();
                var namesItems = items.GroupBy(f => f.Item);
                foreach(var d in namesItems)
                {
                    node.children.Add(new ResponseItemTree {
                        id=g.Key,
                        title=d.Key,
                        expand=true,
                    });
                }
                result.Add(node);
            }
            return new ObjectResult(result);

        }
        /// <summary>
        /// 获取项目的 周期列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetCycle([FromBody]RequestCycleName req)
        {
            var items = _sigerKpitem.GetList(f => f.projectId == ProjectId && f.Section == req.section && f.Item == req.itemName && f.status==(int)RowState.Valid);
            if (!items.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var result = new List<ResponseCycleValue>();
            foreach(var i in items)
            {
                result.Add(new ResponseCycleValue
                {
                    Id = i.id,
                    Cycle=(int)i.KpiCycle,
                    Title = EnumHelper.GetEnumDesc(i.KpiCycle)
                });
            }
            return new ObjectResult(result);
        }
        private List<ResponseItemTree>FillItem(int parentId,List<siger_project_kpi_item> items )
        {
            var result = new List<ResponseItemTree>();
            var nodes = items.Where(f => f.ParentId == parentId).ToList();
            if (!nodes.Any())
                return null;

            foreach(var node in nodes)
            {
                var treeObj = new ResponseItemTree
                {
                    id = node.id,
                    title = node.Item,
                };
                result.Add(new ResponseItemTree
                {
                    id = node.id,
                    title = node.Item,
                    children = FillItem(node.id, items)
                });
            }

            return result;
        }
        /// <summary>
        /// 添加项目
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestKpiitem item)
        {
            var permission = _kpiAuthority.VerifyPermission(UserId, item.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            if (!item.Cycle.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);

            var cycleType = item.Cycle.Select(s => s.KpiCycle);
            if (_sigerKpitem.IsExist(f=>f.projectId==ProjectId && f.Section==item.Section && f.Item==item.Item && f.status==(int)RowState.Valid && cycleType.Contains(f.KpiCycle)))
                throw new BadRequestException(CommonEnum.RecordExits);

            foreach (var obj in item.Cycle)
            {

                _sigerKpitem.Insert(new siger_project_kpi_item
                {
                    Item = item.Item,
                    projectId = ProjectId,
                    Section = item.Section,
                    KpiCycle=obj.KpiCycle,
                    TargetVal =obj.TargetVal,
                    Unit = item.Unit,
                    ParentId = item.ParentId,
                    Condition = item.Condition,
                    Position = item.Position,
                    Color = item.BackColor,
                    Creater = UserId,
                    CreateTime = DateTime.Now.ToLocalTime(),
                    status = item.Enable
                });
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 获取部门下所有KPI 项目 位置
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetItemBySection(int section)
        {
            var result = new List<ResponseDepartItem>();
            var items = _sigerKpitem.GetList(f => f.projectId == ProjectId && f.Section == section && f.status==(int)RowState.Valid);
            if (items.Any())
            {
                foreach(var i in items)
                {
                    result.Add(new ResponseDepartItem {
                         Item=i.id,
                         ItemDesc=$"{i.Item}-"+EnumHelper.GetEnumDesc(i.KpiCycle),
                         Section=i.Section,
                         Unit=i.Unit,
                         TargetVal=i.TargetVal,
                         Condition=i.Condition,
                        // Condition=i.Condition==0?EnumHelper.GetEnumDesc(KpiCondition.Large) : EnumHelper.GetEnumDesc(KpiCondition.Less),
                         Position=i.Position,
                         Color=i.Color
                    });
                }
            }
            return new ObjectResult(result);
        }
        /// <summary>
        /// 编辑项目
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestModifyKpiitem item)
        {
            var permission= _kpiAuthority.VerifyPermission(UserId, item.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);
            
            var KpiObj = _sigerKpitem.Get(item.Id);
            if (KpiObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            if (KpiObj.KpiCycle!=item.KpiCycle)
                throw new BadRequestException(CommonEnum.RecordExits);
            //var boolexits = _sigerKpitem.IsExist(f => f.Item == item.Item && f.KpiCycle == item.KpiCycle && f.id != item.Id);
            //if (boolexits)
            //    throw new BadRequestException(CommonEnum.RecordExits);

            KpiObj.Item = item.Item;
            KpiObj.Section = item.Section;
            KpiObj.KpiCycle = item.KpiCycle;
            KpiObj.TargetVal = item.TargetVal;
            KpiObj.Unit = item.Unit;
            KpiObj.Condition = item.Condition;
            KpiObj.Position = item.Position;
            KpiObj.Color = item.BackColor;
            KpiObj.Creater = UserId;
            KpiObj.status = item.Enable;
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        ///  删除项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var KpiObj = _sigerKpitem.Get(id);
            if (KpiObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var permission = _kpiAuthority.VerifyPermission(UserId, KpiObj.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            _sigerKpitem.Delete(id);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportAll(int section, string item)
        {
            var items = _sigerKpitem.GetKPItemPagedList(section, item, ProjectId, 1, 999999);
            if (!items.Data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
          
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var dataList = new List<ImportKpiItem>();
            foreach (var obj in items.Data)
            {
                dataList.Add(new ImportKpiItem
                {
                     Department=obj.Department,
                     Item=obj.Item,
                     Cycle=(int)obj.KpiCycle,
                     TargetVal=obj.TargetVal,
                     Unit=obj.Unit,
                     Condition=obj.ConditionDesc,
                     Position=obj.Position,
                     Color=obj.Color,
                     Enable=obj.Enable,
                     Creater=obj.Creater
                });
            }
            if (dataList != null && dataList.Any())
            {
                EpPlusExcelHelper<ImportKpiItem> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportKpiItem>();
                    var temporaryFileName = $"KPI基本维护-{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportKpiitem failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            return new ObjectResult(CommonEnum.Fail);

        }

        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllItems()
        {
            var items = _sigerKpitem.GetKpiItemList(ProjectId).Select(q => new
            {
                id = q.Id,
                name = q.Department + "-" + q.Item + "-" + q.KpiCycle
            });

            return new ObjectResult(items);
        }
    }
}
