using Microsoft.AspNetCore.Mvc;
using Siger.ApiCNC.Controllers;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiCNC.Controllers
{
    /// <summary>
    /// 计划生产管理控制器
    /// </summary>
    public class ProductionPlanManagementController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductPlanRepository _planRepository;
        private readonly ISigerProjectProductRepository _productRepository;
        private readonly ISigerProjectProductReport _productionReportRepository;
        private readonly IProductPlanDetailRepository _productPlanDetail;

        public ProductionPlanManagementController(IUnitOfWork unitOfWork, IProductPlanRepository planRepository, ISigerProjectProductRepository productRepository,
            ISigerProjectProductReport productionReportRepository,IProductPlanDetailRepository productPlanDetail)
        {
            _unitOfWork = unitOfWork;
            _planRepository = planRepository;
            _productRepository = productRepository;
            _productionReportRepository = productionReportRepository;
            _productPlanDetail = productPlanDetail;
        }

        /// <summary>
        /// 生产计划管理查询
        /// </summary>
        /// <param name="product_name">产品名称</param>
        /// <param name="draw_number">图纸号</param>
        /// <param name="code">工单号</param>
        /// <param name="ordernumber">订单号</param>
        /// <param name="status">订单状态:1=未下发(生产计划使用);2=未排产；3=已派工；4=生产中；5=已完工；6=已终止</param>
        /// <param name="startTime">添加时间--开始</param>
        /// <param name="endTime">添加时间--结束</param>
        /// <param name="isdelay">是否延期=>0-全部；1--是；2--否</param>
        /// <param name="deliverystart"></param>
        /// <param name="deliveryend"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>       
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPlanList(string product_name, string draw_number, string code, string ordernumber, int status, string startTime, string endTime, int isdelay,
            string deliverystart,string deliveryend, int page, int pagesize)
        {
            var dtStart = string.IsNullOrWhiteSpace(startTime) ? 0 : UnixTimeHelper.GetUnixByShortDate(startTime);
            var dtEnd = string.IsNullOrWhiteSpace(endTime) ? 0 : UnixTimeHelper.GetUnixByShortDate(endTime) + 86400 - 1;

            var delayStart= string.IsNullOrWhiteSpace(deliverystart) ? 0 : UnixTimeHelper.GetUnixByShortDate(deliverystart);
            var delayEnd = string.IsNullOrWhiteSpace(deliveryend) ? 0 : UnixTimeHelper.GetUnixByShortDate(deliveryend) + 86400 - 1;
            var data = _planRepository.GetPagedProductPlanManage(product_name, draw_number, code, ordernumber, status, dtStart,
                dtEnd, isdelay, ProjectId, delayStart, delayEnd, page, pagesize);
            var statusData = data.Data.ToList();
            //foreach(var d in statusData)
            //{
            //    var productReport = _productionReportRepository.GetList(f => f.plan_id == d.id);
            //    if (productReport.Any())
            //    {
            //        d.status = (int)PlanDispatch.Producing;
            //    }
            //    if (d.producted_number>d.install_count)
            //    {
            //        d.status = (int)PlanDispatch.Finished;
            //    }

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

        /// <summary>
        /// 生产计划管理添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddProduceplan([FromBody]RequestAddProducePlanManage request)
        {
            var entity = _planRepository.Get(q => q.code == request.code && q.projectid == ProjectId);
            if (entity != null)
            {
                throw new ServerException(500141);
            }

            var product = _productRepository.Get(q => q.id == request.produceid.ToInt() && q.status == (int)RowState.Valid);
            if (product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }

            if (request.quantity > 5000) // 限制订单数量
            {
                throw new BadRequestException(CncEnum.PlanQuanlityOverFlow);
            }
            var plan = new siger_project_product_plan
            {
                product_id = product.id,
                product_name = product.name,
                product_code = product.code,
                draw_number = product.drawingcode,
                workordertype = request.workordertype,
                code = request.code,
                ordernumber = request.ordernumber,
                quantity = request.quantity,
                //2.0改为工单数量
                install_count = request.install_count.ToInt(),
                delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd),
                create_time = UnixTimeHelper.GetNow(),
                projectid = ProjectId,
                status = 1,
                autogenerate = request.autogenerate,
                source = (int)PlanSource.Manual,
            };
            _planRepository.Insert(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 生产计划管理修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditProduceplan([FromBody]RequestEditProducePlanManage request)
        {
            var entity = _planRepository.Get(q => q.code == request.code && q.projectid == ProjectId
                                                  && q.id != request.id);
            if (entity != null)
            {
                throw new ServerException(500141);
            }
            var plan = _planRepository.Get(q => q.projectid == ProjectId && q.id == request.id);
            if (plan == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (request.quantity > 5000) // 限制订单数量
            {
                throw new BadRequestException(CncEnum.PlanQuanlityOverFlow);
            }

            plan.workordertype = request.workordertype;
            plan.code = request.code;
            plan.ordernumber = request.ordernumber;
            plan.quantity = request.quantity;
            //2.0改为工单数量
            plan.install_count = request.install_count.ToInt();
            plan.delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd);
            _planRepository.Update(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DeleteProduceplan(int id)
        {
            var entity = _planRepository.Get(q => q.id == id && q.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var report = _productionReportRepository.Get(q =>
                q.plan_id == id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            if (report != null)
            {
                throw new ServerException(500155);
            }
            var plandts = _productPlanDetail.GetList(f => f.planId == entity.id).ToList();
            foreach(var dts in plandts)
            {
                _productPlanDetail.Delete(dts.id);
            }
            _planRepository.Delete(id);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}
