using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiConfig.Controller
{
    public class ProductRouteController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductRouteRepository _productRouteRepository;
        private readonly ISigerProjectProductRepository _productRepository;
        public ProductRouteController(IUnitOfWork unitOfWork, IProductRouteRepository productRouteRepository,
            ISigerProjectProductRepository productRepository)
        {
            _unitOfWork = unitOfWork;
            _productRouteRepository = productRouteRepository;
            _productRepository = productRepository;
        }

        [HttpGet]
        public IActionResult GetPagedRoutes(string productId, int page = 1, int pagesize = 10)
        {
            var routes = _productRouteRepository.GetPagedRoutesList(productId.ToInt(), page, pagesize, ProjectId);

            return new PagedObjectResult(routes.Data, routes.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddRoute([FromBody]RequestAddRoute request)
        {
            if (request.routes == null || !request.routes.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            var routes = _productRouteRepository.GetList(q =>
                q.productId == request.productid && q.productId == request.productid
                                                 && q.projectId == ProjectId && q.status == (int) RowState.Valid);
            if (routes.Any())
            {
                //不能再次添加
                throw new BadRequestException(RequestEnum.ProductRouteHasexist);

                //删除
                //foreach (var route in routes.ToList())
                //{
                //    route.status = (int) RowState.Invalid;
                //    _productRouteRepository.Delete(route);
                //}
            }

            foreach (var route in request.routes)
            {
                var entity = new siger_project_product_route
                {
                    addTime = DateTime.Now,
                    productId = request.productid,
                    projectId = ProjectId,
                    name = route.route_name,
                    description = route.description,
                    working_hours = route.hours.ToDouble(),
                    serialNumber = route.route_ordernumber.ToInt(),
                    machine_type = route.machine_type.ToInt(),
                    create_usermid = UserId,
                    prepare = route.prepare.ToDouble()
                };
                _productRouteRepository.Insert(entity);
            }

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

        [HttpGet]
        public IActionResult DeleteRoute(string ids)
        {
            if (ids == null || !ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            var routeIds = ids.Split(',').ToList();
            var routes = _productRouteRepository.GetList(q => q.projectId == ProjectId 
                                                              && routeIds.Contains(q.id.ToString()) 
                                                              && q.status == (int) RowState.Valid).ToList();
            //已排产则不能删除
            foreach (var route in routes)
            {
                route.status = (int) RowState.Invalid;
                _productRouteRepository.Update(route);
            }
            
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetRoutesByProduct(int productId)
        {
            var routes = _productRouteRepository.GetList(q =>
                    q.projectId == ProjectId && q.productId == productId && q.status == (int) RowState.Valid)
                .Select(m => new
                {
                    m.id,
                    m.name,
                    m.serialNumber,
                    m.working_hours,
                    m.prepare
                }).OrderBy(q => q.serialNumber).ToList();

            return new ObjectResult(routes);
        }

        [HttpGet]
        public IActionResult GetRoutesByProductCode(string productcode)
        {
            var product = _productRepository.Get(t => t.code == productcode && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            var productId = product?.id ?? 0;
            var routes = _productRouteRepository.GetList(q =>
                    q.projectId == ProjectId && q.productId == productId && q.status == (int)RowState.Valid)
                .Select(m => new
                {
                    m.id,
                    m.name,
                    m.serialNumber,
                    m.working_hours,
                    m.prepare
                }).OrderBy(q => q.serialNumber).ToList();

            return new ObjectResult(routes);
        }

        [HttpGet]
        public IActionResult GetRoute(int id)
        {
            var route = _productRouteRepository.Get(q =>
                q.projectId == ProjectId && q.id == id && q.status == (int) RowState.Valid);
            if (route == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(route);
        }

        [HttpGet]
        public IActionResult GetRouteName(int sectionId, int productId)
        {
            var routes = _productRouteRepository.Get(q => q.projectId == ProjectId && q.productId == productId
                                                                                       && q.sectionId == sectionId &&
                                                                                       q.status == (int)RowState.Valid);
            if (routes != null)
            {
                return new ObjectResult(routes.name);
            }
            return new ObjectResult("");
        }

        [HttpPost]
        public IActionResult UpdateRoute([FromBody] RequestUpdateRoute request)
        {
            var route = _productRouteRepository.Get(q =>
                q.projectId == ProjectId && q.id == request.id && q.status == (int)RowState.Valid);
            if (route == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            route.description = request.description.ToStr();
            route.working_hours = request.hours.ToDouble();
            route.prepare = request.prepare.ToDouble();
            _productRouteRepository.Update(route);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}