using System;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using System.Linq;
using System.Linq.Expressions;
using Siger.Middlelayer.Common.ModuleEnum;

namespace Siger.ApiTPM.Controllers
{
    /// <summary>
    /// 安灯参数设置
    /// </summary>
    public class AndonStationConfigController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerAndonStationConfigRepository _andonStationConfigRepository;
        private readonly ISigerProjectMachineAttributionRepository _attributionRepository;
        private readonly ISigerAndonExpectionTypeRepository _expectionTypeRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;

        public AndonStationConfigController(IUnitOfWork unitOfWork,
            ISigerAndonStationConfigRepository andonStationConfigRepository, ISigerProjectMachineAttributionRepository attributionRepository
            , ISigerAndonExpectionTypeRepository expectionTypeRepository, ISigerProjectLevelSectionRepository levelSectionRepository)
        {
            _unitOfWork = unitOfWork;
            _andonStationConfigRepository = andonStationConfigRepository;
            _attributionRepository = attributionRepository;
            _expectionTypeRepository = expectionTypeRepository;
            _levelSectionRepository = levelSectionRepository;
        }

        [HttpGet]
        public IActionResult GetPagedStationConfig(int page = 1, int pagesize = 10)
        {
            var data = _andonStationConfigRepository.GetPagedConfig(ProjectId, page, pagesize);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 添加配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddUpdateConfig([FromBody]RequestAddAndonConfig request)
        {
            if (request.section_id == 0)
            {
                throw new BadRequestException(RequestEnum.SectionMachineNull);
            }
            var expections = _expectionTypeRepository.GetExpectionParent(request.default_error_id, ProjectId);
            if (!expections.Any())
            {
                throw new BadRequestException(TpmEnum.ExpectionNotFound);
            }
            var defaul_type = expections.First(f => f.level == 1);

            if (request.id == 0) //添加
            {
                var machine = _attributionRepository.Get(q => q.station == request.section_id && q.attribution == 1 && q.status == (int)RowState.Valid
                                                              && q.projectid == ProjectId);
                if (machine == null)
                {
                    throw new BadRequestException(RequestEnum.SectionMachineNull);
                }

                var set = _andonStationConfigRepository.Get(q =>
                    q.machine_id == machine.machine && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (set != null)
                {
                    throw new BadRequestException(RequestEnum.SectionHasConfig);
                }

                var config = new siger_andon_station_config
                {
                    machine_id = machine.machine,
                    change_cycle = request.change_cycle,
                    create_time = DateTime.Now,
                    creator_mid = UserId,
                    default_error_id = request.default_error_id,
                    kicktank_time = request.kicktank_time,
                    qualified_time = request.qualified_time,
                    project_id = ProjectId,
                    selfdeal_time = request.selfdeal_time,
                    station_type = request.station_type,
                    speed_time = request.speed_time,
                    defaul_type = defaul_type.id
                };
                _andonStationConfigRepository.Insert(config);

                SetConfig(config);
            }
            else
            {
                var config = _andonStationConfigRepository.Get(request.id);
                if (config == null || config.status != (int)RowState.Valid)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }

                config.change_cycle = request.change_cycle;
                config.default_error_id = request.default_error_id;
                config.kicktank_time = request.kicktank_time;
                config.qualified_time = request.qualified_time;
                config.selfdeal_time = request.selfdeal_time;
                config.station_type = request.station_type;
                config.speed_time = request.speed_time;
                config.defaul_type = defaul_type.id;
                _andonStationConfigRepository.Update(config);

                SetConfig(config);
            }

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

        private void SetConfig(siger_andon_station_config config)
        {
            var rep = new QMSRatedTimeLifeConfigRepository(CompanyId, ProjectId);
            //获取产线信息
            var station = _attributionRepository.Get(f => f.machine == config.machine_id && f.projectid == ProjectId && f.status == (int)RowState.Valid)?.station ?? 0;
            var line = _levelSectionRepository.Get(f => f.id == station && f.projectid == ProjectId && f.status == (int)RowState.Valid)?.parentid ?? 0;
            rep.AddRateLifeConfig(config.machine_id, config.qualified_time, config.kicktank_time, config.change_cycle, config.defaul_type, config.speed_time, line);
        }

        [HttpPost]
        public IActionResult DeleteConfigs([FromBody]RequestKeyArry param)
        {
            //if (string.IsNullOrWhiteSpace(ids))
            //{
            //    throw new BadRequestException(RequestEnum.ParameterError);
            //}

            //var requestIds = ids.Split(',');
            if (!param.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterError);

            var rep = new QMSRatedTimeLifeConfigRepository(CompanyId, ProjectId, false);
            foreach (var requestId in param.ids)
            {
                var config = _andonStationConfigRepository.Get(requestId);
                if (config != null)
                {
                    config.status = (int)RowState.Invalid;
                    _andonStationConfigRepository.Update(config);

                    rep.RemoveRateLifeConfig(config.machine_id);
                }
            }

            rep.Dispose();
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}