using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Request;
using Siger.Middlelayer.CncRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis.Model;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiCNC.Controllers
{
    //生产参数监控-参数异常设置
    public class MachineParamAlarmController : BaseController
    {
        private readonly IMachineParamAlarmRepository _machineParamAlarmRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IUnitOfWork _unitOfWork;

        public MachineParamAlarmController(IUnitOfWork unitOfWork, IMachineParamAlarmRepository machineParamAlarmRepository,
            ISigerProjectMachineRepository machineRepository)
        {
            _unitOfWork = unitOfWork;
            _machineParamAlarmRepository = machineParamAlarmRepository;
            _machineRepository = machineRepository;
        }
        
        [HttpGet]
        public IActionResult ListAlarm(int sectionID, int page, int pagesize)
        {
            var data = _machineParamAlarmRepository.GetPagedParamAlarm(sectionID, ProjectId, page, pagesize);
            var result = new List<ResponseGetListAlarm>();

            var validMachines = _machineRepository.GetNCLevelSectionNames(sectionID, ProjectId);
            foreach (var machineParamAlarm in data.Data)
            {
                var entity = Mapper<MachineParamAlarm, ResponseGetListAlarm>.Map(machineParamAlarm);

                var section = validMachines.FirstOrDefault(q => q.machine_id == machineParamAlarm.machine_id);
                entity.machineLocation = section != null ? section.lastSecondSectionTitle + "-" + section.lastSectionTitle : "";

                result.Add(entity);
            }

            return new PagedObjectResult(result, data.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddAlarm([FromBody] RequestAddAlarm request)
        {
            var machineId = _machineRepository.GetNCMahcineIdBySection(request.sectionID);
            if (machineId == 0)
            {
                throw new ServerException(100177);
            }

            var entity = _machineParamAlarmRepository.Get(q => q.status == (int) RowState.Valid
                                                               && q.project_id == ProjectId &&
                                                               q.machine_id == machineId);
            if (entity != null)
            {
                throw new ServerException(100178);
            }

            var alarm = new siger_project_machine_param_alarm
            {
                axis_speed_top = request.axisSpeedTop,
                axis_speed_low = request.axisSpeedLow,
                axis_rate_top = request.axisRateTop,
                axis_rate_low = request.axisRateLow,
                feed_rate_low = request.feedRateLow,
                feed_rate_top = request.feedRateTop,
                project_id = ProjectId,
                machine_id = machineId
            };

            _machineParamAlarmRepository.Insert(alarm);
            if (_unitOfWork.Commit() > 0)
            {
                //sync redis data
                var repository = new CncParameterExceptionConfigRepository(CompanyId, ProjectId);
                var model = Mapper<siger_project_machine_param_alarm, RedisMachineParamAlarmModellarm>.Map(alarm);
                repository.SetParameterExceptionConfig(model);

                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult UpdateAlarm([FromBody] RequestEditAlarm request)
        {
            var entity = _machineParamAlarmRepository.Get(q => q.status == (int)RowState.Valid
                                                               && q.project_id == ProjectId &&
                                                               q.id == request.id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.axis_speed_top = request.axisSpeedTop;
            entity.axis_speed_low = request.axisSpeedLow;
            entity.axis_rate_top = request.axisRateTop;
            entity.axis_rate_low = request.axisRateLow;
            entity.feed_rate_low = request.feedRateLow;
            entity.feed_rate_top = request.feedRateTop;

            _machineParamAlarmRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                //sync redis data
                var repository = new CncParameterExceptionConfigRepository(CompanyId, ProjectId);
                var model = Mapper<siger_project_machine_param_alarm, RedisMachineParamAlarmModellarm>.Map(entity);
                repository.SetParameterExceptionConfig(model);

                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult DeleteAlarm(int id)
        {
            var entity = _machineParamAlarmRepository.Get(q => q.status == (int)RowState.Valid
                                                               && q.project_id == ProjectId &&
                                                               q.id == id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.status = (int) RowState.Invalid;
            _machineParamAlarmRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                var repository = new CncParameterExceptionConfigRepository(CompanyId, ProjectId);
                repository.DeleteParameterExceptionConfig(entity.machine_id);

                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult DeleteAlarms([FromBody]RequestDeleteEntities request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            var entities = _machineParamAlarmRepository.GetList(q => q.status == (int)RowState.Valid
                                                               && q.project_id == ProjectId &&
                                                               request.ids.Contains(q.id)).ToList();
            if (entities.Any())
            {
                foreach (var entity in entities)
                {
                    entity.status = (int)RowState.Invalid;
                    _machineParamAlarmRepository.Update(entity);

                    var repository = new CncParameterExceptionConfigRepository(CompanyId, ProjectId);
                    repository.DeleteParameterExceptionConfig(entity.machine_id);
                }
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}