using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Request;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;

namespace Siger.ApiConfig.Controller
{
    public class ProductionLocationController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductionConfigRepository _productConfigRepository;
        private readonly ISigerProjectLevelRepository _sigerProjectLevel;
        private readonly ISigerProjectMachineAttributionRepository _attributionRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSection;
        public ProductionLocationController(IUnitOfWork unitOfWork, IProductionConfigRepository productConfigRepository, ISigerProjectLevelRepository sigerProjectLevel,
            ISigerProjectMachineAttributionRepository attributionRepository, ISigerProjectMachineRepository machineRepository,
            ISigerProjectLevelSectionRepository levelSection)
        {
            _unitOfWork = unitOfWork;
            _productConfigRepository = productConfigRepository;
            _sigerProjectLevel = sigerProjectLevel;
            _attributionRepository = attributionRepository;
            _machineRepository = machineRepository;
            _levelSection = levelSection;
        }

        [HttpGet]
        public IActionResult GetLocations(int lineid)
        {
            var responses = new List<ResponseGetMachineLocation>();
            var machines = _attributionRepository.GetList(q =>
                q.attribution == (int)MachineAttributionEnum.equipment
                && q.status == (int)RowState.Valid && q.projectid == ProjectId).Select(m => m.machine).Distinct().ToList();
            if (machines.Any())
            {
                var attributions = _machineRepository.GetMachineStationInfos(machines, ProjectId).Where(q => q.id == lineid);
                foreach (var attribution in attributions)
                {
                    var location = _productConfigRepository
                        .Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.machine_id == attribution.machineId);
                    if (location != null)
                    {
                        var response = new ResponseGetMachineLocation
                        {
                            production_section_id = location.production_section_id,
                            production_section_title = location.production_section_title,
                            machine_id = location.machine_id,
                            machine_section_id = location.machine_section_id,
                            machine_section_title = location.machine_section_title,
                            x = location.x,
                            y = location.y,
                            h = location.h,
                            w = location.w,
                            v = location.v
                        };
                        responses.Add(response);
                    }
                    else
                    {
                        var response = new ResponseGetMachineLocation
                        {
                            production_section_id = attribution.id,
                            production_section_title = attribution.section_name,
                            machine_id = attribution.machineId,
                            machine_section_id = attribution.sectionId,
                            machine_section_title = attribution.station_name,
                            x = 0,
                            y = 0
                        };
                        responses.Add(response);
                    }
                }
            }
            return new ObjectResult(responses);
        }

        [HttpPost]
        public IActionResult SetLocations([FromBody] RequestSetLocation request)
        {
            if (request.locations == null || !request.locations.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var location in request.locations)
            {
                var config = _productConfigRepository.Get(q => q.projectid == ProjectId && q.machine_id == location.machine_id &&
                    q.status == (int)RowState.Valid);
                if (config == null)
                {
                    var entity = new siger_project_production_configuration
                    {
                        production_section_id = location.production_section_id,
                        production_section_title = location.production_section_title,
                        projectid = ProjectId,
                        add_time = UnixTimeHelper.GetNow(),
                        edit_time = 0,
                        machine_id = location.machine_id,
                        machine_section_id = location.machine_section_id,
                        machine_section_title = location.machine_section_title,
                        x = location.x,
                        y = location.y,
                        v = location.v,
                        w = location.w,
                        h = location.h
                    };
                    _productConfigRepository.Insert(entity);
                }
                else
                {
                    config.production_section_title = location.production_section_title;
                    config.edit_time = UnixTimeHelper.GetNow();
                    config.machine_section_title = location.machine_section_title;
                    config.x = location.x;
                    config.y = location.y;
                    config.v = location.v;
                    config.w = location.w;
                    config.h = location.h;
                    _productConfigRepository.Update(config);
                }
            }

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

        /// <summary>
        /// 获取所有工站
        /// </summary>
        /// <param name="lineid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetLevelList(int lineid)
        {
            //var sectionID = 0;
            //var patchId = 0;

            //while (sectionID>=0)
            //{
            //    var patchs = _levelSection.GetList(q => q.parentid == sectionID && q.projectid == ProjectId).ToList();
            //    if (patchs.Any())
            //    {
            //        sectionID = patchs.FirstOrDefault().id;
            //    }
            //    else
            //    {
            //        var patches = _levelSection.Get(q => q.id == sectionID && q.projectid == ProjectId);
            //        patchId = patches.levelid;
            //        sectionID = -1;
            //    }
            //}
            //var responses = new List<ResponseGetLevels>();
            //var query = _levelSection.Getline(ProjectId, lineid).ToList();
            //if (query != null)
            //{
            //    foreach (var items in query)
            //    {
            //        if (items.levelid != patchId)
            //        {
            //            continue;
            //        }
            //        var response = new ResponseGetLevels
            //        {
            //            title = items.title,
            //            section_id = items.id,
            //            x = 0,
            //            y = 0
            //        };
            //        responses.Add(response);
            //    }
            //}
            //return new ObjectResult(responses);

            var level = _sigerProjectLevel.GetList(f => f.projectid == ProjectId,"id").FirstOrDefault();
            if (level==null)
            {
                throw new BadRequestException(ConfigEnum.UserLevelNull);
            }
            var responses = new List<ResponseGetLevels>();
            var levels = _levelSection.GetLevelSectionIds(lineid, ProjectId).ToList();
           
           
                var levelSection =_levelSection.GetList(f => f.projectid == ProjectId && levels.Contains(f.id)  && f.levelid == level.id);
            foreach (var items in levelSection)
            {
                var response = new ResponseGetLevels
                {
                    title = items.title,
                    section_id = items.id,
                    x = 0,
                    y = 0
                };
                responses.Add(response);
            }
            
            return new ObjectResult(responses);
        }

       
    }
}
