using System;
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.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiCNC.Controllers
{
    public class ProductionAllocationController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductionAllocationRepository _allocationRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        public ProductionAllocationController(IUnitOfWork unitOfWork, IProductionAllocationRepository allocationRepository,
            ISigerProjectMachineRepository machineRepository)
        {
            _unitOfWork = unitOfWork;
            _allocationRepository = allocationRepository;
            _machineRepository = machineRepository;
        }

        [HttpGet]
        public IActionResult GetAllocations(int sectionid, int page, int pagesize)
        {
            var data = _allocationRepository.GetPagedList(sectionid,  ProjectId, page,  pagesize);
            var list = new List<ResponseGetAllocation>();
            var validMachines = _machineRepository.GetLevelSectionNames(sectionid, ProjectId);
            foreach (var time in data.Data)
            {
                var entity = Mapper<siger_project_production_allocation, ResponseGetAllocation>.Map(time);

                var section = validMachines.FirstOrDefault(q => q.machine_id == time.machine_id);
                entity.sectionName = section != null ? section.lastSecondSectionTitle + "-" + section.lastSectionTitle : "";
                list.Add(entity);
            }
            return new PagedObjectResult(list, data.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddAllocation([FromBody]RequestAddProductionAllocation request)
        {
            var machineId = _machineRepository.GetMahcineIdBySection(request.sectionid);
            if (machineId == 0)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }
            var allocation = _allocationRepository.IsExist(q => q.section_id == request.sectionid && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            if (allocation)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            var entity = new siger_project_production_allocation
            {
                machine_id = machineId,
                section_id = request.sectionid,
                add_time = DateTime.Now,
                projectid = ProjectId,
                transfer_time = request.transfer_time,
                rate = request.rate,
                creator_id = UserId
            };
            _allocationRepository.InsertAsync(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditAllocation([FromBody]RequestUpdateProductionAllocation request)
        {
            var allocation = _allocationRepository.Get(request.id);
            if (allocation == null || allocation.status != (int) RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            allocation.transfer_time = request.transfer_time;
            allocation.rate = request.rate;
            _allocationRepository.Update(allocation);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetAllocation(int id)
        {
            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpPost]
        public IActionResult DeleteAllocation(int id)
        {
            var setting = _allocationRepository.Get(id);
            if (setting == null || setting.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            setting.status = (int)RowState.Invalid;
            _allocationRepository.Update(setting);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult DeleteAllocations([FromBody]RequestDeleteEntities request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            var settings = _allocationRepository.GetList(q => q.status == (int)RowState.Valid
                                                             && q.projectid == ProjectId &&
                                                             request.ids.Contains(q.id)).ToList();
            if (settings.Any())
            {
                foreach (var setting in settings)
                {
                    setting.status = (int)RowState.Invalid;
                    _allocationRepository.Update(setting);
                }
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}