using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Respose;
using Siger.ApiCommon.Filters;
namespace Siger.ApiKPI.Controllers
{
    /// <summary>
    /// KPI 推送维护
    /// </summary>
    public class PushSettingController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiPushSetting _sigerKpiPushSetting;
        private readonly ISigerPlanReportLevel _sigerPlanReportLevel;
        private readonly ISigerPlanReport _sigerPlanReport;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="unitOfWork"></param>
        /// <param name="sigerKpiPushSetting"></param>
        /// <param name="sigerReportLevel"></param>
        /// <param name="sigerPlanReport"></param>
        public PushSettingController(IUnitOfWork unitOfWork, ISigerKpiPushSetting sigerKpiPushSetting, ISigerPlanReportLevel sigerReportLevel, ISigerPlanReport sigerPlanReport)
        {
            _unitOfWork = unitOfWork;
            _sigerKpiPushSetting = sigerKpiPushSetting;
            _sigerPlanReportLevel = sigerReportLevel;
            _sigerPlanReport = sigerPlanReport;
        }
        /// <summary>
        ///  推送设置列表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSettingList(int section,int item, int page, int pageSize)
        {
            var data = _sigerKpiPushSetting.GetKPIPushSettingList(section, item, ProjectId, page, pageSize);
            var result = data.Data.ToList();
            foreach (var d in result)
            {
                //usgroup
                //var planRptlist = _sigerPlanReportLevel.GetList(f => f.project_id == ProjectId && f.process_code == d.ProcessCode && f.status==(int)RowState.Valid);
                var planRptlist = _sigerPlanReportLevel.GetUserGroupsBySettingCode(ProjectId, d.ProcessCode);
                var planReport = _sigerPlanReport.GetList(f => f.projectId == ProjectId && f.process_code == d.ProcessCode);

                var _lv1_grpId = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.First).Select(s => s.Id).ToList();
                var _lv1_grpName = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.First).Select(s => s.Name).ToList();
                var _lv1_t1 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.First && f.type == (int)KpiPushSettingType.Exception);
                var _lv1_t2 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.First && f.type == (int)KpiPushSettingType.Processing);
                var _lv1_t3 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.First && f.type == (int)KpiPushSettingType.Done);

                d.Level1 = new ReponsePushErroTypeLevel
                {
                    Type1 = new ReponsePushErroType
                    {
                        Min = _lv1_t1 != null ? _lv1_t1.space_time : 0,
                        Type = KpiPushSettingType.Exception,
                    },
                    Type2 = new ReponsePushErroType
                    {
                        Min = _lv1_t2 != null ? _lv1_t2.space_time : 0,
                        Type = KpiPushSettingType.Processing,
                    },
                    Type3 = new ReponsePushErroType
                    {
                        Min = _lv1_t3 != null ? _lv1_t3.space_time : 0,
                        Type = KpiPushSettingType.Done,
                    },
                    Sections = new ReponseUserGroup
                    {
                        usergroup = _lv1_grpId,
                        groupname = _lv1_grpName
                    }
                };

                var _lv2_grpId = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Second).Select(s => s.Id).ToList();
                var _lv2_grpName = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Second).Select(s => s.Name).ToList();
                var _lv2_t1 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Second && f.type == (int)KpiPushSettingType.Exception);
                var _lv2_t2 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Second && f.type == (int)KpiPushSettingType.Processing);
                var _lv2_t3 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Second && f.type == (int)KpiPushSettingType.Done);

                d.Level2 = new ReponsePushErroTypeLevel
                {
                    Type1 = new ReponsePushErroType
                    {
                        Min = _lv2_t1 != null ? _lv2_t1.space_time : 0,
                        Type = KpiPushSettingType.Exception,
                    },
                    Type2 = new ReponsePushErroType
                    {
                        Min = _lv2_t2 != null ? _lv2_t2.space_time : 0,
                        Type = KpiPushSettingType.Processing,
                    },
                    Type3 = new ReponsePushErroType
                    {
                        Min = _lv2_t3 != null ? _lv2_t3.space_time : 0,
                        Type = KpiPushSettingType.Done,
                    },
                    Sections = new ReponseUserGroup
                    {
                        usergroup = _lv2_grpId,
                        groupname = _lv2_grpName
                    }
                };

                var _lv3_grpId = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Three).Select(s => s.Id).ToList();
                var _lv3_grpName = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Three).Select(s => s.Name).ToList();
                var _lv3_t1 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Three && f.type == (int)KpiPushSettingType.Exception);
                var _lv3_t2 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Three && f.type == (int)KpiPushSettingType.Processing);
                var _lv3_t3 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Three && f.type == (int)KpiPushSettingType.Done);

                d.Level3 = new ReponsePushErroTypeLevel
                {
                    Type1 = new ReponsePushErroType
                    {
                        Min = _lv3_t1 != null ? _lv3_t1.space_time : 0,
                        Type = KpiPushSettingType.Exception,
                    },
                    Type2 = new ReponsePushErroType
                    {
                        Min = _lv3_t2 != null ? _lv3_t2.space_time : 0,
                        Type = KpiPushSettingType.Processing,
                    },
                    Type3 = new ReponsePushErroType
                    {
                        Min = _lv3_t3 != null ? _lv3_t3.space_time : 0,
                        Type = KpiPushSettingType.Done,
                    },
                    Sections = new ReponseUserGroup
                    {
                        usergroup = _lv3_grpId,
                        groupname = _lv3_grpName
                    }
                };

                var _lv4_grpId = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Four).Select(s => s.Id).ToList();
                var _lv4_grpName = planRptlist.Where(f => f.Level == (int)KpiPushSettingLevel.Four).Select(s => s.Name).ToList();
                var _lv4_t1 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Four && f.type == (int)KpiPushSettingType.Exception);
                var _lv4_t2 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Four && f.type == (int)KpiPushSettingType.Processing);
                var _lv4_t3 = planReport.FirstOrDefault(f => f.start_level == (int)KpiPushSettingLevel.Four && f.type == (int)KpiPushSettingType.Done);

                d.Level4 = new ReponsePushErroTypeLevel
                {
                    Type1 = new ReponsePushErroType
                    {
                        Min = _lv4_t1 != null ? _lv4_t1.space_time : 0,
                        Type = KpiPushSettingType.Exception,
                    },
                    Type2 = new ReponsePushErroType
                    {
                        Min = _lv4_t2 != null ? _lv4_t2.space_time : 0,
                        Type = KpiPushSettingType.Processing,
                    },
                    Type3 = new ReponsePushErroType
                    {
                        Min = _lv4_t3 != null ? _lv4_t3.space_time : 0,
                        Type = KpiPushSettingType.Done,
                    },
                    Sections = new ReponseUserGroup
                    {
                        usergroup = _lv4_grpId,
                        groupname = _lv4_grpName
                    }
                };

                //d.FlowDetails= _sigerKpiPushSetting.GetSectionDesc(levels,ProjectId);
            }
            return new PagedObjectResult(result, data.Total, page, pageSize);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="pushSetting"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestPushSetting pushSetting)
        {
            var Pid = ProjectId;
            if (_sigerKpiPushSetting.IsExist(f => f.projectId == Pid && f.section_id == pushSetting.Depart && f.kpi_item == pushSetting.KpiItem))
                throw new BadRequestException(CommonEnum.RecordExits);

            return InserPlanLevel(pushSetting);

        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="pushSetting"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestPushSetting pushSetting)
        {
            var obj = _sigerKpiPushSetting.Get(f => f.id == pushSetting.Id);
            if (obj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            //先删
            var plan = _sigerPlanReport.GetList(f => f.projectId == ProjectId && f.process_code == obj.process_code);
            foreach(var p in plan)
            {
                _sigerPlanReport.Delete(p);
            }
            var planlevel=_sigerPlanReportLevel.GetList(f => f.project_id == ProjectId && f.process_code == obj.process_code);
            foreach(var pl in planlevel)
            {
                _sigerPlanReportLevel.Delete(pl);
            }
            _sigerKpiPushSetting.Delete(obj);
            //后插
            return InserPlanLevel(pushSetting);

        }
        IActionResult InserPlanLevel(RequestPushSetting pushSetting)
        {
            
            var processCode = IdHelper.Generate<string>();
            _sigerKpiPushSetting.Insert(new SigerProjectKpiPushSetting
            {
                projectId = ProjectId,
                kpi_item = pushSetting.KpiItem,
                repeattime = pushSetting.Refresh,
                section_id = pushSetting.Depart,
                process_code = processCode,
                user_id = UserId,
                datetime = DateTime.Now,
                status = (int)RowState.Valid,
            });
            // level 1 
            for (int i = 0; i < 4; i++)
            {
                var startlevel = i + 1;
                var endlevl = startlevel + 1;
                //levet1 -type
                for (int t = 0; t < 3; t++)
                {
                    var type = t + 1;
                    var _spaceTime = 0;
                    if (startlevel == (int)KpiPushSettingLevel.First && type == (int)KpiPushSettingType.Exception)
                        _spaceTime = pushSetting.Level1.Type1.Min;
                    if (startlevel == (int)KpiPushSettingLevel.First && type == (int)KpiPushSettingType.Processing)
                        _spaceTime = pushSetting.Level1.Type2.Min;
                    if (startlevel == (int)KpiPushSettingLevel.First && type == (int)KpiPushSettingType.Done)
                        _spaceTime = pushSetting.Level1.Type3.Min;

                    if (startlevel == (int)KpiPushSettingLevel.Second && type == (int)KpiPushSettingType.Exception)
                        _spaceTime = pushSetting.Level2.Type1.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Second && type == (int)KpiPushSettingType.Processing)
                        _spaceTime = pushSetting.Level2.Type2.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Second && type == (int)KpiPushSettingType.Done)
                        _spaceTime = pushSetting.Level2.Type3.Min;

                    if (startlevel == (int)KpiPushSettingLevel.Three && type == (int)KpiPushSettingType.Exception)
                        _spaceTime = pushSetting.Level3.Type1.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Three && type == (int)KpiPushSettingType.Processing)
                        _spaceTime = pushSetting.Level3.Type2.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Three && type == (int)KpiPushSettingType.Done)
                        _spaceTime = pushSetting.Level3.Type3.Min;

                    if (startlevel == (int)KpiPushSettingLevel.Four && type == (int)KpiPushSettingType.Exception)
                        _spaceTime = pushSetting.Level4.Type1.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Four && type == (int)KpiPushSettingType.Processing)
                        _spaceTime = pushSetting.Level4.Type2.Min;
                    if (startlevel == (int)KpiPushSettingLevel.Four && type == (int)KpiPushSettingType.Done)
                        _spaceTime = pushSetting.Level4.Type3.Min;

                    //if (_spaceTime == 0)
                    //    continue;
                    _sigerPlanReport.Insert(new siger_project_plan_report
                    {
                        mode = 0,
                        projectId = ProjectId,
                        start_level = startlevel,
                        end_level = endlevl,
                        type = type,
                        space_time = _spaceTime,
                        create_mid = UserId,
                        create_time = UnixTimeHelper.GetNow(),
                        process_code = processCode,
                        status = (int)RowState.Valid
                    });
                }
                // user 岗位
                var TempSections = new List<int>();
                if (startlevel == (int)KpiPushSettingLevel.First)
                    TempSections = pushSetting.Level1.Sections;
                if (startlevel == (int)KpiPushSettingLevel.Second)
                    TempSections = pushSetting.Level2.Sections;
                if (startlevel == (int)KpiPushSettingLevel.Three)
                    TempSections = pushSetting.Level3.Sections;
                if (startlevel == (int)KpiPushSettingLevel.Four)
                    TempSections = pushSetting.Level4.Sections;

                foreach (var u in TempSections)
                {
                    _sigerPlanReportLevel.Insert(new siger_project_plan_report_level
                    {
                        //mode=0,
                        project_id = ProjectId,
                        level = startlevel,
                        usergroup_id = u,
                        process_code = processCode,
                        status = (int)RowState.Valid
                    });
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Del(int id)
        {
            var obj = _sigerKpiPushSetting.Get(f => f.id == id);
            if (obj==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var plan = _sigerPlanReport.GetList(f => f.projectId == ProjectId && f.process_code == obj.process_code);
            foreach (var p in plan)
            {
                _sigerPlanReport.Delete(p);
            }
            var planlevel = _sigerPlanReportLevel.GetList(f => f.project_id == ProjectId && f.process_code == obj.process_code);
            foreach (var pl in planlevel)
            {
                _sigerPlanReportLevel.Delete(pl);
            }
            _sigerKpiPushSetting.Delete(obj);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);

        }
    }
}
