using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using System.Linq;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Log;
using System;

namespace Siger.ApiQMS.Controllers
{
    public class AbnormalRuleController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAbnormalRuleRepository _abnormalRule;
        public AbnormalRuleController(IUnitOfWork unitOfWork, IAbnormalRuleRepository abnormalRule)
        {
            _unitOfWork = unitOfWork;
            _abnormalRule = abnormalRule;
        }

        [HttpGet]
        public IActionResult GetRules()
        {
            var res = _abnormalRule.GetList(t => t.projectid == ProjectId && t.status == (int) RowState.Valid).ToList();
            return new ObjectResult(res);
        }

        [HttpPost]
        public IActionResult SaveRules([FromBody]RequestSaveRules req)
        {
            if (req.rules == null || !req.rules.Any())
            {
                throw new BadRequestException(RequestEnum.SelectData);
            }

            foreach (var rule in req.rules)
            {
                var entity = _abnormalRule.Get(t =>
                    t.projectid == ProjectId && t.status == (int) RowState.Valid && t.id == rule.id);
                if (entity != null)
                {
                    entity.continuous = rule.continuous;
                    entity.discrete = rule.discrete;
                    entity.k_value = rule.k_value.ToInt();
                    entity.trigger_andon = rule.trigger_andon;
                }
                _abnormalRule.Update(entity);
            }

            if (_unitOfWork.Commit() > 0)
            {
                try
                {
                    var rules = _abnormalRule.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid)
                        .OrderBy(t => t.key).ToList();
                    var kValues = rules.Select(t => t.k_value).ToList();
                    var andonRules = rules.Where(t => t.trigger_andon == 1).OrderBy(t => t.key).ToList();
                    var andonRuleKeys = andonRules.Select(t => t.key).ToList();
                    var qmsRepository = new QMSParameterRuleKValueConfigRepository(CompanyId, ProjectId);
                    qmsRepository.SaveRuleKValue(kValues, andonRuleKeys);
                }
                catch(Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}