using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiKPI.Controllers
{
    public class ActionController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiAction _sigerKpiAction;
        private readonly ISigerKpiActionResult _sigerKpiActionResult;
        private readonly ISigerKpiTasklist _kpiTasklist;
        private readonly ISigerKpiPushMessage _sigerKpiPushMessage;
        private readonly ISigerKpiAuthority _kpiAuthority;

        public ActionController(IUnitOfWork unitOfWork, ISigerKpiAction sigerKpiAction, ISigerKpiActionResult sigerKpiActionResult, ISigerKpiTasklist kpiTasklist, ISigerKpiPushMessage kpiPushMessage, ISigerKpiAuthority kpiAuthority)
        {
            _unitOfWork = unitOfWork;
            _sigerKpiAction = sigerKpiAction;
            _sigerKpiActionResult = sigerKpiActionResult;
            _kpiTasklist = kpiTasklist;
            _sigerKpiPushMessage = kpiPushMessage;
            _kpiAuthority = kpiAuthority;
        }

        /// <summary>
        /// 创建行动计划
        /// </summary>
        /// <param name="itemAction"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody] RequestKpiItemAction itemAction)
        {
            var taskObj = _kpiTasklist.Get(itemAction.TaskId);
            if (taskObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

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


            var action = _sigerKpiAction.Get(f => f.projectId == ProjectId && f.id== itemAction.ActionId );
            if (action == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            if (itemAction.Plantime.ToDateTime() < taskObj.Busidate)
                throw new BadRequestException(CommonEnum.LessBusidate);

            taskObj.Excption = KpiExecption.Processing;
            _kpiTasklist.Update(taskObj);

            action.Plantime = itemAction.Plantime.ToDateTime();
            action.Reposible = itemAction.Reposible;
            action.Cause = itemAction.Cause;
            action.Solution = itemAction.Solution;
            action.Checktime = UnixTimeHelper.GetUnixByDate(itemAction.CheckTime.ToStr());
            action.Excutetime = UnixTimeHelper.GetUnixByDate(itemAction.ExcuteTime.ToStr());
            action.Desc1 = itemAction.Desc;
            _sigerKpiAction.Update(action);


            if (!string.IsNullOrEmpty(itemAction.SloveTime))
            {
                var msgDoneObj = _sigerKpiPushMessage.Get(f =>
                    f.ProjectId == ProjectId && f.TaskId == taskObj.id && f.SectionId == taskObj.Section &&
                    f.ItemId == taskObj.ItemId);
                if (msgDoneObj != null)
                {
                    msgDoneObj.LevelType = KpiPushSettingType.Done;
                    msgDoneObj.Push = 0;
                    msgDoneObj.LastUpdate = DateTime.Now;
                    _sigerKpiPushMessage.Update(msgDoneObj);
                }
                //最小行动计划id关闭时 TASK 变正常
                var actionMin = _sigerKpiAction.GetList(f => f.projectId == ProjectId && f.TaskId == itemAction.TaskId,"id").FirstOrDefault();
                if (actionMin != null)
                { 
                    if (actionMin.id == itemAction.ActionId)
                    {
                        taskObj.Result = KpiTaskResult.Normal;
                        taskObj.Excption = KpiExecption.Complated;
                        _kpiTasklist.Update(taskObj);
                    }
                }else
                {
                    taskObj.Result = KpiTaskResult.Normal;
                    taskObj.Excption = KpiExecption.Complated;
                    _kpiTasklist.Update(taskObj);
                }

                _sigerKpiActionResult.Insert(new SigerProjectKpiActionResult
                {
                    actionid= action.id,
                    TaskId = taskObj.id,
                    projectId = ProjectId,
                    Operater = UserId,
                    Solution = itemAction.Solution,
                    status = (int)RowState.Valid,
                    Result = 1,
                    Creater = UserId,
                    Time = itemAction.SloveTime.ToDateTime()
                });
            }

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="itemAction"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody] RequestKpiItemAction itemAction)
        {
            var taskObj = _kpiTasklist.Get(itemAction.TaskId);
            if (taskObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

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

            if (itemAction.Plantime.ToDateTime() < taskObj.Busidate)
                throw new BadRequestException(CommonEnum.LessBusidate);

            taskObj.Excption = KpiExecption.Processing;
            _kpiTasklist.Update(taskObj);

            var msgObj = _sigerKpiPushMessage.Get(f =>
            f.ProjectId == ProjectId && f.TaskId == taskObj.id && f.SectionId == taskObj.Section &&
            f.ItemId == taskObj.ItemId);
            if (msgObj != null)
            {
                msgObj.LevelType = KpiPushSettingType.Processing;
                msgObj.Push = 0;
                msgObj.LastUpdate = DateTime.Now;
                _sigerKpiPushMessage.Update(msgObj);
            }

            _sigerKpiAction.Insert(new SigerProjectKpiAction
            {
                projectId = ProjectId,
                TaskId = itemAction.TaskId,
                CreateUser = UserId,
                Plantime = itemAction.Plantime.ToDateTime(),
                Reposible = itemAction.Reposible,
                Cause = itemAction.Cause,
                Solution = itemAction.Solution,
                status = (int)RowState.Valid,
                Checktime = UnixTimeHelper.GetUnixByDate(itemAction.CheckTime.ToStr()),
                Excutetime = UnixTimeHelper.GetUnixByDate(itemAction.ExcuteTime.ToStr()),
                Desc1 = itemAction.Desc
            });

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
    }
}
