using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiTPM.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data.Tpm;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;

namespace Siger.ApiTPM.Controllers
{
    public class PlanReportController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerSystemConfigRepository _configRepository;
        private readonly IPlanReportRepository _planReportRepository;
        private readonly IPlanReportLevelRepository _planReportLevelRepository;
        public PlanReportController(IUnitOfWork unitOfWork, ISigerSystemConfigRepository configRepository, IPlanReportRepository planReportRepository,
            IPlanReportLevelRepository planReportLevelRepository)
        {
            _unitOfWork = unitOfWork;
            _configRepository = configRepository;
            _planReportRepository = planReportRepository;
            _planReportLevelRepository = planReportLevelRepository;
        }

        [HttpPost]
        public IActionResult SetLevel([FromBody]RequestPlanSetLevel res)
        {
            var mode = res.mode > 0 ? res.mode : 0;
            var levelid = res.level > 0 ? res.level : 0;
            if (mode == 0)
            {
                throw new ServerException(100206);
            }
            if (levelid == 0)
            {
                throw new ServerException(100205);
            }

            var models = _planReportLevelRepository.GetList(t =>
                t.mode == mode && t.level == levelid && t.status == (int) RowState.Valid && t.project_id == ProjectId);
            if (models.Any())
            {
                foreach(var model in models)
                {
                    model.status = (int)RowState.Invalid;
                    _planReportLevelRepository.Update(model);
                }
            }
            if (res.usergroup!=null&&res.usergroup.Any())
            {
                var usergroups = res.usergroup.Distinct();
                foreach (var p in usergroups)
                {
                    _planReportLevelRepository.Insert(new siger_project_plan_report_level
                    {
                        level = levelid,
                        mode = mode,
                        project_id = ProjectId,
                        usergroup_id = p
                    });
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new PlanReportResult()
                {
                    ret = 1,
                    msg = "1",//1112
                    data = null
                };
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult SetTime([FromBody]RequestPlanSetTime res)
        {
            if (res.data == null)
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var p in res.data)
            {
                var reports = _planReportRepository.Get(t =>
                    t.mode == p.mode && t.start_level == p.start_level && t.end_level.ToString() == p.end_level &&
                    t.type == p.type
                    && t.projectid == ProjectId && t.status == (int) RowState.Valid);
                if (reports != null)
                {
                    reports.space_time = p.space_time;
                    reports.repeat_time = res.message_repeat_time.ToInt();
                    _planReportRepository.Update(reports);
                }
                else
                {
                    _planReportRepository.Insert(new siger_project_plan_report
                    {
                        space_time = p.space_time,
                        create_mid = UserId,
                        create_time = UnixTimeHelper.GetNow(),
                        start_level = p.start_level,
                        end_level = p.end_level.ToInt(),
                        mode = p.mode,
                        type = p.type,
                        projectid = ProjectId,
                        repeat_time= res.message_repeat_time.ToInt()
                });
                }
            }

           // var setResult = _planReportRepository.SetMessageRepeatTime(res.message_repeat_time);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取设置异常上报的等级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult getSetLevel(int mode)
        {
            mode = mode > 0 ? mode : 1;
            var result = _planReportRepository.GetSetLevelInfoList(mode,ProjectId).ToList();
            if (result.Any())
            {
                var bes = new GetSetLevel();
                foreach(var p in result)
                {
                    bes.level1 = result.Where(t => t.level == 1).ToList();
                    bes.level2 = result.Where(t => t.level == 2).ToList();
                    bes.level3 = result.Where(t => t.level == 3).ToList();
                    bes.level4 = result.Where(t => t.level == 4).ToList();

                }
                return new PlanReportResult()
                {
                    ret = 1,
                    msg = "1",//1055
                    data = bes
                };
            }

            throw new BadRequestException(CommonEnum.NoData);
        }

        /// <summary>
        /// 展示已选择的时间
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSelectedtime(int mode)
        {
            mode = mode > 0 ? mode : 1;
            var selectRes = _planReportRepository.GetList(t => t.status == (int)RowState.Valid && t.projectid == ProjectId && t.mode == mode).ToList();
            var config = _configRepository.Get(q =>
                q.key == SystemConfigKey.MessagePlanTime && q.status == (int) RowState.Valid);
            var time = config != null ? config.value : "1";
            if (selectRes.Any())
            {
                return new SelectedTimeResult()
                {
                    ret = 1,
                    msg = "1",
                    data = selectRes,
                    time = time
                };
            }

            throw new BadRequestException(CommonEnum.NoData);
        }
    }
}