using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCNC.Result;
using Siger.ApiCommon.Filters;
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.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiCNC.Controllers
{
    public class ProductController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductPlanRepository _planRepository;
        private readonly ISigerProjectProductRepository _productRepository;
        private readonly ISigerProjectProductReport _productionReportRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IProductPlanDetailRepository _planDetailRepository;
        public ProductController(IUnitOfWork unitOfWork, IProductPlanRepository planRepository, ISigerProjectProductRepository productRepository,
            ISigerProjectProductReport productionReportRepository, ISigerProjectMachineRepository machineRepository,
            IProductPlanDetailRepository planDetailRepository)
        {
            _unitOfWork = unitOfWork;
            _planRepository = planRepository;
            _productRepository = productRepository;
            _productionReportRepository = productionReportRepository;
            _machineRepository = machineRepository;
            _planDetailRepository = planDetailRepository;
        }

        [HttpGet]
        public IActionResult GetPlanList(string product_name, string draw_number, string code, string ordernumber, string status,string ordertype, string startTime, string endTime,
            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 data = _planRepository.GetPagedProductPlan(product_name, draw_number, code, ordernumber, status, ordertype.ToInt(), dtStart,
                dtEnd, string.Empty, ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        [HttpGet]
        public IActionResult GetPlanListNew(string product_name, string draw_number, string code, string ordernumber, string status, string startTime, string endTime,
            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 data = _planRepository.GetPagedProductPlan(product_name, draw_number, code, ordernumber, status,0, dtStart,
                dtEnd, string.Empty, ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        [HttpGet]
        public async Task<IActionResult> GetProducetname()
        {
            var products = await _productRepository.GetListAsync(q => q.projectid == ProjectId && q.status == (int)RowState.Valid);

            var response = products.Select(m => new ProductInfo
            {
                id = m.id,
                name = m.name,
                drawingcode = m.drawingcode,
                product_code = m.code
            });

            return new ObjectResult(response);
        }

        [HttpPost]
        public IActionResult AddProduceplan([FromBody]RequestAddProduceplan 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
            {
                code = request.code,
                create_time = UnixTimeHelper.GetNow(),
                delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd),
                draw_number = product.drawingcode,
                product_id = product.id,
                product_name = product.name,
                producted_number = 0,
                nok_number = 0,
                quantity = request.quantity,
                projectid = ProjectId,
                status = (int)PlanProcess.UnPlan,
                product_code = product.code,
                ordernumber = request.ordernumber,
                workordertype = request.workordertype,
                partnumber = request.partnumber,
                autogenerate = request.autogenerate,
                source = (int)PlanSource.Manual,
                install_count = request.install_count.ToInt()
            };
            _planRepository.Insert(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult AddProduceplanNew([FromBody]RequestAddProduceplan 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
            {
                code = request.code,
                create_time = UnixTimeHelper.GetNow(),
                delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd),
                draw_number = product.drawingcode,
                product_id = product.id,
                product_name = product.name,
                producted_number = 0,
                nok_number = 0,
                quantity = request.quantity,
                projectid = ProjectId,
                status = (int)PlanProcess.UnPlan,
                product_code = product.code,
                ordernumber = request.ordernumber,
                workordertype = request.workordertype,
                //2.0料号去除
                //partnumber = request.partnumber,
                autogenerate = request.autogenerate,
                source = (int)PlanSource.Manual,
                install_count = request.install_count.ToInt()
            };
            _planRepository.Insert(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public async Task<IActionResult> GetProducePlan(int id)
        {
            var entity = await _planRepository.GetAsync(q => q.id == id && q.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var products = await _productRepository.GetListAsync(q => q.projectid == ProjectId && q.status == (int)RowState.Valid);
            var productInfos = products.Select(m => new ProductInfo
            {
                id = m.id,
                name = m.name,
                drawingcode = m.drawingcode,
                product_code = m.code
            });

            var response = Mapper<siger_project_product_plan, ResponseGetProducePlan>.Map(entity);
            response.products = productInfos.ToList();

            return new ObjectResult(response);
        }

        [HttpGet]
        public async Task<IActionResult> GetProducePlanForSchedule(int id)
        {
            var entity = await _planRepository.GetAsync(q => q.id == id && q.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var response = Mapper<siger_project_product_plan, ResponseGetProducePlanForSchedule>.Map(entity);

            return new ObjectResult(response);
        }

        [HttpPost]
        public IActionResult EditProduceplan([FromBody]RequestEditProduceplan 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.code = request.code;
            plan.delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd);
            plan.quantity = request.quantity;
            plan.ordernumber = request.ordernumber;
            plan.workordertype = request.workordertype;
            plan.partnumber = request.partnumber;
            plan.install_count = request.install_count.ToInt();

            _planRepository.Update(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult EditProduceplanNew([FromBody]RequestEditProduceplan 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.code = request.code;
            plan.delivery_time = UnixTimeHelper.GetUnixByShortDate(request.deliverytime + ParameterConstant.TimeToEnd);
            plan.quantity = request.quantity;
            plan.ordernumber = request.ordernumber;
            plan.workordertype = request.workordertype;
            //2.0料号去除
            //partnumber = request.partnumber,
            plan.install_count = request.install_count.ToInt();

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

        [HttpPost]
        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);
            }
            _planRepository.Delete(id);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetProducePlanList(string product_name, string draw_number, string code, string status)
        {
            var products = _planRepository.GetNoPagedProductPlan(product_name, draw_number, code, status, ProjectId);
           
            var response = new List<ResponseProducePlanList>();
            foreach (var product in products.ToList())
            {
                var entity = Mapper<siger_project_product_plan, ResponseProducePlanList>.Map(product);
                entity.create_time = UnixTimeHelper.ConvertIntDate(product.create_time);
                entity.delivery_time = UnixTimeHelper.ConvertIntDate(product.delivery_time);
                entity.num = product.producted_number;
                entity.status = EnumHelper.GetEnumDesc((PlanProcess)product.status);
                response.Add(entity);
            }

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetPlanDetails(int planId, int num)
        {
            if (num == 0)
            {
                throw new BadRequestException(CncEnum.BatchMustGreaterZero);
            }
            var plan = _planRepository.Get(planId);
            if (plan == null)
            {
                throw new BadRequestException(CncEnum.PlanNotFound);
            }

            if (num > plan.quantity)
            {
                num = plan.quantity;
            }

            var batch = plan.quantity / num;
            var residual = plan.quantity % num;
            var response = new List<ResponseGetWorkOrders>();
            if (residual == 0)
            {
                for (var i = 1; i <= num; i++)
                {
                    response.Add(new ResponseGetWorkOrders
                    {
                        orderNumber = $"{plan.code}-{i}",
                        count = batch
                    });
                }
            }
            else
            {
                var count = batch;
                for (var i = 1; i <= num; i++)
                {
                    if (i == num)
                    {
                        count = batch + residual;
                    }
                    response.Add(new ResponseGetWorkOrders
                    {
                        orderNumber = $"{plan.code}-{i}",
                        count = count
                    });
                }
                
            }
            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetPlanListForSchedule(string product_name, string draw_number, string code, string ordernumber, string status, string isdelay,
            string startTime, string endTime, 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 data = _planRepository.GetPagedProductPlan(product_name, draw_number, code, ordernumber, status,0, dtStart,
                dtEnd, isdelay, ProjectId, page, pagesize);

            var response = new List<ResponseGetProductPlan>();

            foreach (var plan in data.Data)
            {
                var batch = _planDetailRepository.GetList(m =>
                    m.planId == plan.id && m.status == (int) RowState.Valid && m.projectId == ProjectId).Count();

                var planInfo = Mapper<ResponseGetProductPlan, ResponseGetProductPlan>.Map(plan);
                planInfo.batch = batch;

                var planDetails = _planDetailRepository.GetList(q => q.planId == plan.id && q.status == (int) RowState.Valid);
                if (planDetails.Any())
                {
                    planInfo.plan_start = planDetails.Min(m => m.startTime);
                    planInfo.plan_end = planDetails.Max(m => m.endTime);
                    planInfo.has_schedule = planDetails.Sum(q => q.quantity);//已排产数量
                }

                var deliveryDate = UnixTimeHelper.ConvertStringDateTime(plan.delivery_time.ToString());
                planInfo.leaveDays = deliveryDate.Date.Subtract(DateTime.Now.Date).Days;
                response.Add(planInfo);
            }

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

        [HttpPost]
        public async Task<IActionResult> GetProductPlanAlysis([FromBody] RequestGetPlanAlysis request)
        {
            var dtStart = UnixTimeHelper.GetTodayUnix() - 86400 * 7;
            var dtEnd = UnixTimeHelper.GetTodayUnix() + 86400;
            var startTime = string.IsNullOrWhiteSpace(request.startTime)
                ? dtStart
                : UnixTimeHelper.GetUnixByShortDate(request.startTime);
            var endTime = string.IsNullOrWhiteSpace(request.endTime)
                ? dtEnd
                : UnixTimeHelper.GetUnixByShortDate(request.endTime) + 86400 - 1;

            var query1 = await _planRepository.GetListAsync(q => q.projectid == ProjectId && q.delivery_time >= startTime &&
                                                                 q.delivery_time <= endTime);
            var query2 = query1.Where(q => q.status == (int)PlanProcess.Finished && q.delivery_time >= q.finish_time);
            var query3 = query1.Where(q => q.status == (int)PlanProcess.Finished);

            var count1 = query1.Count();
            var count2 = query2.Count();
            var count3 = query3.Count();

            var result = new ProductPlanAlysisResult
            {
                plan_num =
                {
                    first = new FirstParameter
                    {
                        num1 = count1,
                        num2 = count2,
                        num3 = count3
                    }
                }
            };
            result.plan_num.second.Add(new SecondParameter
            {
                name = "500167", //准时完成数
                num1 = count2,
                num2 = count1 - count2
            });
            result.plan_num.second.Add(new SecondParameter
            {
                name = "500169",//最终完成数
                num1 = count3,
                num2 = count1 - count3
            });

            if (request.xtype == "time")
            {
                if (request.x_id == "day")
                {
                    result.data.AddRange(GetProduces(startTime, endTime, 1));
                }
                if (request.x_id == "week")
                {
                    result.data.AddRange(GetProduces(startTime, endTime, 7));
                }
                if (request.x_id == "mon")
                {
                    result.data.AddRange(GetProduces(startTime, endTime, 30));
                }
            }
            else
            {
                var productNames = _productionReportRepository.GetList(q => q.projectid == ProjectId)
                    .Select(m => m.product_name).Distinct().ToList();
                if (!productNames.Any())
                {
                    throw new ServerException(500170);
                }

                foreach (var productName in productNames)
                {
                    var query = _productionReportRepository.GetList(q =>
                        q.projectid == ProjectId && q.product_name == productName && q.time >= startTime && q.time <= endTime);
                    result.data.Add(new HasProduce
                    {
                        actual_output = query.Sum(q => q.actual_output),
                        nok_number = query.Sum(q => q.nok_number),
                        type = productName
                    });
                }
            }

            return result;
        }

        [HttpPost]
        public IActionResult GetProductReportAlysis([FromBody] RequestGetReportAlysis request)
        {
            var dtStart = UnixTimeHelper.GetTodayUnix() - 86400 * 7;
            var dtEnd = UnixTimeHelper.GetTodayUnix() + 86400;
            var startTime = string.IsNullOrWhiteSpace(request.startTime)
                ? dtStart
                : UnixTimeHelper.GetUnixByShortDate(request.startTime);
            var endTime = string.IsNullOrWhiteSpace(request.endTime)
                ? dtEnd
                : UnixTimeHelper.GetUnixByShortDate(request.endTime) + 86400 - 1;

            var result = new ProductReportAlysisResult();
            if (request.xtype == "time")
            {
                if (request.x_id == "day")
                {
                    result.data.AddRange(GetReportProduces(startTime, endTime, 1, request.machinearr));
                }
                if (request.x_id == "week")
                {
                    result.data.AddRange(GetReportProduces(startTime, endTime, 7, request.machinearr));
                }
                if (request.x_id == "mon")
                {
                    result.data.AddRange(GetReportProduces(startTime, endTime, 30, request.machinearr));
                }
            }

            if (request.xtype == "machine")
            {
                if (string.IsNullOrEmpty(request.x_id))
                {
                    throw new ServerException(1037);
                }
                //patchId 为levelId
                var patchId = request.x_id.ToInt();
                //取sectionID下面的设备
                var sections = _machineRepository.GetNCLevelSections(request.sectionID.ToInt(), ProjectId);
                var levels = sections.Where(q => q.levelid == patchId).ToList();
                foreach (var levelSection in levels)
                {
                    var outPut = 0;
                    var nokNumber = 0;
                    var machineIds = _machineRepository.GetNCLevelSectionMachineIds(levelSection.id, ProjectId);
                    var query = _productionReportRepository.GetList(q => q.projectid == ProjectId && q.time >= startTime 
                                                                         && q.time <= endTime && machineIds.Contains(q.machineid));
                    foreach (var sigerProjectProductReport in query.ToList())
                    {
                        outPut += sigerProjectProductReport.actual_output;
                        nokNumber += sigerProjectProductReport.nok_number;
                    }

                    result.data.Add(new HasProduce
                    {
                        actual_output = outPut,
                        nok_number = nokNumber,
                        type = levelSection.title
                    });
                }
            }

            if (request.xtype == "product_name" || request.xtype == "worker_name")
            {
                var query = _productionReportRepository.GetList(q => q.projectid == ProjectId && q.time >= startTime && q.time <= endTime && request.machinearr.Contains(q.machineid));
                if (!query.Any())
                {
                    throw new ServerException(500166);
                }

                IQueryable<HasProduce> yields;
                if (request.xtype == "product_name")
                {
                    yields = from m in query
                        group m by new
                        {
                            m.product_name
                        }
                        into temp
                        select new HasProduce
                        {
                            type = temp.Key.product_name,
                            actual_output = temp.Sum(m => m.actual_output),
                            nok_number = temp.Sum(m => m.nok_number)
                        };
                }
                else
                {
                    yields = from m in query
                        group m by new
                        {
                            m.worker_name
                        }
                        into temp
                        select new HasProduce
                        {
                            type = temp.Key.worker_name,
                            actual_output = temp.Sum(m => m.actual_output),
                            nok_number = temp.Sum(m => m.nok_number)
                        };
                }
                foreach (var hasProduce in yields.ToList())
                {
                    result.data.Add(new HasProduce
                    {
                        actual_output = hasProduce.actual_output,
                        nok_number = hasProduce.nok_number,
                        type = hasProduce.type
                    });
                }
            }

            return result;
        }

        private IEnumerable<HasProduce> GetProduces(int startTime, int endTime, int num)
        {
            var list = new List<HasProduce>();
            if (num == 30) //按月统计
            {
                var dtStart = DateTime.Parse(UnixTimeHelper.ConvertIntDateTime(startTime));
                var dtEnd = DateTime.Parse(UnixTimeHelper.ConvertIntDateTime(endTime));
                var dateTimes = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, 2);
                foreach (var dateTime in dateTimes)
                {
                    var dtCompareStart = DateTime.Parse(dateTime + "-01");
                    var dtCompareEnd = dtCompareStart.AddMonths(1).AddSeconds(-1);

                    var unixStart = UnixTimeHelper.ConvertDataTimeLong(dtCompareStart);
                    var unixEnd = UnixTimeHelper.ConvertDataTimeLong(dtCompareEnd);

                    var query = _productionReportRepository.GetList(q => q.projectid == ProjectId && q.time >= unixStart && q.time <= unixEnd);
                    var output = 0;
                    var nokNumber = 0;
                    foreach (var report in query.ToList())
                    {
                        output += report.actual_output;
                        nokNumber += report.nok_number;
                    }
                    list.Add(new HasProduce
                    {
                        actual_output = output,
                        nok_number = nokNumber,
                        type = dateTime
                    });
                }
            }
            else
            {
                for (var stime = startTime; stime < endTime; stime += 86400 * num)
                {
                    var etime = stime + 86400 * num;
                    var query = _productionReportRepository.GetList(q =>
                        q.projectid == ProjectId && q.time >= stime && q.time <= etime);
                    list.Add(new HasProduce
                    {
                        actual_output = query.Sum(q => q.actual_output),
                        nok_number = query.Sum(q => q.nok_number),
                        type = UnixTimeHelper.ConvertIntDate(stime)
                    });
                }
            }
            

            return list;
        }

        private IEnumerable<HasProduce> GetReportProduces(int startTime, int endTime, int num, IEnumerable<int> machineIds)
        {
            var list = new List<HasProduce>();
            if (num == 30) //按月统计
            {
                var dtStart = DateTime.Parse(UnixTimeHelper.ConvertIntDateTime(startTime));
                var dtEnd = DateTime.Parse(UnixTimeHelper.ConvertIntDateTime(endTime));
                var dateTimes = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, 2);
                foreach (var dateTime in dateTimes)
                {
                    var dtCompareStart = DateTime.Parse(dateTime + "-01");
                    var dtCompareEnd = dtCompareStart.AddMonths(1).AddSeconds(-1);

                    var unixStart = UnixTimeHelper.ConvertDataTimeLong(dtCompareStart);
                    var unixEnd = UnixTimeHelper.ConvertDataTimeLong(dtCompareEnd);

                    var query = _productionReportRepository.GetList(q => q.projectid == ProjectId && q.time >= unixStart &&
                                                                         q.time <= unixEnd && machineIds.Contains(q.machineid));
                    var output = 0;
                    var nokNumber = 0;
                    foreach (var report in query.ToList())
                    {
                        output += report.actual_output;
                        nokNumber += report.nok_number;
                    }
                    list.Add(new HasProduce
                    {
                        actual_output = output,
                        nok_number = nokNumber,
                        type = dateTime
                    });
                }
            }
            else
            {
                for (var stime = startTime; stime < endTime; stime += 86400 * num)
                {
                    var etime = stime + 86400 * num;
                    var query = _productionReportRepository.GetList(q => q.projectid == ProjectId && q.time >= stime &&
                                                                         q.time < etime && machineIds.Contains(q.machineid));
                    var output = 0;
                    var nokNumber = 0;
                    foreach (var report in query.ToList())
                    {
                        output += report.actual_output;
                        nokNumber += report.nok_number;
                    }
                    list.Add(new HasProduce
                    {
                        actual_output = output,
                        nok_number = nokNumber,
                        type = UnixTimeHelper.ConvertIntDate(stime)
                    });
                }
            }
            

            return list;
        }
    }
}