using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Logical;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Data.Acc;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class SigerProductReportRepository : AccRepositoryBase<SigerTrProductReport>, ISigerProductReport
    {
        private ApiAccDbContext accDbContext;
        public SigerProductReportRepository(ApiAccDbContext context) : base(context)
        {
            accDbContext = context;
        }
        
        /// <summary>
        /// 获取最近上下料信息列表
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="line"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public List<WorkReportInfo> GetReportInfos(int projectId, int line, int station)
        {
            Expression<Func<WorkReportInfo, bool>> FunUpload = f => f.WorkStaus == (int)Basket_Status.upload;
            Expression<Func<WorkReportInfo, bool>> FunReport = f => f.WorkStaus == (int)Basket_Status.report;

            var cancellst = accDbContext.siger_tr_product_report.Where(f => f.projectId == projectId && f.status == (int)RowState.Valid && (f.Type == (int)Type_Status.basket || f.Type == (int)Type_Status.workCode) && f.ReportStatus == (int)Basket_Status.CancelUpload);
            var keys = new List<int>();
            if (cancellst.Any())
            {
                keys = cancellst.Select(f => f.id).ToList();
            }

            var querylist = from p in accDbContext.siger_tr_basketful_position
                            join r in accDbContext.siger_tr_product_report on p.traceid equals r.TraceId
                            join u in accDbContext.siger_project_user on r.Uid equals u.mid into temp
                            from user in temp.DefaultIfEmpty()
                            where p.projectId == projectId && p.station == line && r.Machine == station && p.status != (int)BasketPosition_Status.Deleted
                                  && (r.Type == (int)Type_Status.basket || r.Type == (int)Type_Status.workCode)
                                  && r.ReportStatus != (int)Basket_Status.CancelUpload
                                  && !keys.Contains(r.id)
                            select new WorkReportInfo
                            {
                                WorkCode = p.workcode,
                                WorkCodeType = r.Type,
                                WorkStaus = r.ReportStatus,
                                Number = r.Number == null ? "" : r.Number,
                                ProductId = p.productbh,
                                ProductName = p.productname,
                                ProductType = p.producttype,
                                OrderCount = p.upload,
                                OkCount = r.OkCount,
                                UserName = user == null ? r.Uid.ToString() : user.name,
                                Time = r.Time,
                                UpCount= p.upload
                            };

            var predicate = FunUpload.Or(FunReport);

            return querylist.Where(predicate).OrderByDescending(o => o.Time).Skip(0).Take(100).ToList();

        }

        /// <summary>
        /// 可以报工的工单信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="station"></param>
        /// <param name="position"></param>
        /// <param name="workcode"></param>
        /// <param name="number"></param>
        /// <param name="bUnReport">未报工</param>
        /// <returns></returns>
        public List<WorkReportInfo> GetUnReport(int projectId, int station, int position, string workcode, string number,bool bUnReport=false)
        {
            Expression<Func<WorkReportInfo, bool>> Funworkcode = f => true;
            Expression<Func<WorkReportInfo, bool>> Funnumber = f => true;
            Expression<Func<WorkReportInfo, bool>> Funposition = f => true;
            Expression<Func<WorkReportInfo, bool>> Funreport = f => true;
            var query = from p in accDbContext.siger_tr_basketful_position

                        where p.projectId == projectId
                        && p.status == (int)BasketPosition_Status.validate
                        select new WorkReportInfo
                        {
                            TraceId = p.traceid,
                            Station = p.station,
                            Position = p.position,
                            Machine = p.position,
                            MachineId = p.position,
                            WorkCode = p.workcode,
                            Number = p.basket,
                            ProductId = p.productbh,
                            ProductName = p.productname,
                            ProductType = p.producttype,
                            UpCount = p.upload,
                            OkCount = p.report,
                            NokCount = p.nok,
                            NokCount2 = p.nok2,
                            OrderCount = p.upload,
                            Time = p.uploadtime,
                            BasketId = p.currbasket
                        };
            if (bUnReport)
                Funreport = q => q.OkCount == 0;

            if (!string.IsNullOrEmpty(workcode))
                Funworkcode = q => q.WorkCode.Contains(workcode);
            if (!string.IsNullOrEmpty(number))
                Funnumber = q => q.Number == number;
            if (position != 0)
                Funposition = q => q.Position == position;
            var predicate = Funworkcode.And(Funnumber).And(Funposition).And(Funreport);
            var data = query.Where(predicate).OrderByDescending(o => o.Time).Skip(0).Take(100).ToList();
            return data;
        }

        /// <summary>
        /// 转框信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="number"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public List<WorkReportInfo> GetWorkByBasketNum(int projectId, string number, string guid)
        {
            var querylist = from b in accDbContext.siger_tr_basketlist
                            join p in accDbContext.siger_tr_basketful_position on b.traceId equals p.traceid
                            where b.projectId == b.projectId && b.traceId == guid && b.number == number
                            select new WorkReportInfo
                            {
                                Station = b.station,
                                Position = b.position,
                                WorkCode = b.workcode,
                                Number = b.number,
                                OrderCount = p.upload,
                                ProductId = p.productbh,
                                ProductName = p.productname,
                                ProductType = p.producttype,
                                UpCount = b.count,
                                OkCount = b.count,
                                TraceId = b.traceId,
                                Time = p.uploadtime
                            };
            return querylist.OrderBy(o => o.Time).ToList();

        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="machineCode"></param>
        /// <param name="workCode"></param>
        /// <returns></returns>
        public List<WorkReportInfo> GetWorkByWorkCode(int projectId, string machineCode, string workCode)
        {


            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            // where p.status == (int)CncPlan_Status.plan &&
                            where pd.projectId == projectId && pd.OrderNumber == workCode
                            select new WorkReportInfo
                            {

                                WorkCode = pd.OrderNumber,
                                Number = "",
                                WorkStaus = p.status,
                                ProductId = p.product_id.ToString(),
                                ProductName = p.product_name,
                                ProductType = p.draw_number,
                                OrderCount = p.quantity,
                                UpCount = p.quantity,


                                Time = DateTime.Now

                            };
            return querylist.OrderBy(o => o.Time).ToList();
        }

        public List<MouldReport> GetMouldReports(int projectId, string serinum, int page = 1, int pageSize = 5)
        {

            var query = from p in accDbContext.siger_tr_product_report
                        join m in accDbContext.siger_project_level_section on p.Machine equals m.id
                        join u in accDbContext.siger_project_user on p.Uid equals u.mid
                        where p.projectId == projectId && p.Number == serinum &&
                        p.Type == (int)Type_Status.moulds
                        select new MouldReport
                        {
                            Name = m.title,
                            Status = p.ReportStatus,
                            Time = p.Time.ToString(UnixTimeHelper.DateTimeFormat),
                            Type = p.Type,
                            UserId = p.Uid.ToString(),
                            userName = u.name
                        };

            return query.OrderByDescending(o => o.Time).Skip(0).Take(5).ToList();

        }
        public IEnumerable<siger_project_user> GetUserlist(int project)
        {
            return accDbContext.siger_project_user.Where(f => f.projectid == project && f.status == (int)RowState.Valid).ToList();

        }

        public List<BasketReport> GetBasketReports(int projectId, int productId, string orderNum, string workCode, int section, string userId, int machineId, DateTime begin, DateTime end, out int totalCount, int page = 1, int pageSize = 10)
        {

            Expression<Func<BasketReport, bool>> Funcat = f => true;
            Expression<Func<BasketReport, bool>> Funworkcode = f => true;
            Expression<Func<BasketReport, bool>> FunorderNum = f => true;
            Expression<Func<BasketReport, bool>> Funsection = f => true;
            Expression<Func<BasketReport, bool>> FunuserId = f => true;
            Expression<Func<BasketReport, bool>> FunmachineId = f => true;

            var querylist = from r in accDbContext.siger_tr_product_report
                            join p in accDbContext.siger_tr_basketful_position on r.TraceId equals p.traceid
                            join st in accDbContext.siger_project_level_section on p.station equals st.id
                            join ps in accDbContext.siger_project_level_section on p.position equals ps.id
                            join u in accDbContext.siger_project_user on r.Uid equals u.mid into temp
                            from user in temp.DefaultIfEmpty()
                            join u1 in accDbContext.siger_project_user on r.login equals u1.mid into temp1
                            from user1 in temp1.DefaultIfEmpty()
                            where r.projectId == projectId && r.Time >= begin && r.Time < end && p.status != (int)BasketPosition_Status.Deleted
                            select new BasketReport
                            {
                                ProductId = p.productbh,
                                ProductName = p.productname,
                                Pn = "",
                                ProductType = p.producttype,
                                OrderNum = p.orderno,
                                Qty = p.orderqty,
                                WrokCode = r.WorkCode,
                                Machine = r.Machine,
                                MachineName = ps.title,
                                Section = p.station,
                                SectionName = st.title,
                                Basket = r.Number,
                                OkCount = r.OkCount,
                                NokCount = r.NokCount + r.NokCount2,
                                Type = r.Type,
                                Status = r.ReportStatus, //EnumHelper.GetEnumDesc((Basket_Status)r.ReportStatus),
                                Login = user1 == null ? r.login.ToString() : user1.name,
                                UserId = user == null ? r.Uid.ToString() : user.name,
                                Time = r.Time,
                                Remarks = r.Remark
                            };

            if (!string.IsNullOrEmpty(orderNum))
                FunorderNum = q => q.OrderNum.Contains(orderNum);
            if (!string.IsNullOrEmpty(workCode))
                Funworkcode = q => q.WrokCode == workCode;
            if (section != 0)
                Funsection = q => q.Section == section;
            if (!string.IsNullOrEmpty(userId))
                FunuserId = q => q.UserId == userId;
            if (machineId != 0)
                FunmachineId = q => q.Machine == machineId;


            var predicate = Funcat.And(FunorderNum).And(Funworkcode).And(Funsection).And(FunuserId).And(FunmachineId);
            totalCount = querylist.Count(predicate);

            var data = querylist.Where(predicate).OrderByDescending(o => o.Time).Skip((page - 1) * pageSize).Take(pageSize).ToList();
            var outRpt = new List<BasketReport>();
            foreach (var d in data)
            {
                var leveSection = GetLevel_Section(d.Machine, projectId);
                d.OperateType = EnumHelper.GetEnumDesc((Type_Status)d.Type);
                d.OperateStatus = EnumHelper.GetEnumDesc((Basket_Status)d.Status);

                if (d.Type == (int)Type_Status.basket && d.Status == (int)Basket_Status.Change)
                {
                    d.OperateStatus += "-" + d.Remarks + EnumHelper.GetEnumDesc((BasketChange_Status.Change_In));
                }
                if (d.Type == (int)Type_Status.machine && d.Status == (int)MachineChange_Status.Change)
                {
                    d.OperateStatus += "-" + EnumHelper.GetEnumDesc((MachineChange_Status.Change));
                }
                d.MachineName = leveSection == null ? "" : leveSection.title;
                outRpt.Add(d);

            }
            return outRpt.OrderByDescending(o => o.Time).ToList();

        }

        public List<WorkReportInfo> GetDataByWorkCode(int projectId, string workCode)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            join r in accDbContext.siger_tr_product_report on pd.OrderNumber equals r.WorkCode
                            join s in accDbContext.siger_project_level_section on r.Station equals s.id
                            join ps in accDbContext.siger_project_level_section on r.Machine equals ps.id
                            join lsm in accDbContext.siger_project_machine_attribution on ps.id equals lsm.station
                            join mc in accDbContext.siger_project_machine on lsm.machine equals mc.id
                            where
                            pd.projectId == projectId && pd.OrderNumber == workCode && r.Type == (int)Type_Status.basket && r.ReportStatus != (int)Basket_Status.upload
                            select new WorkReportInfo
                            {
                                Order = p.ordernumber,
                                WorkCode = r.WorkCode,
                                ProductId = p.product_id.ToString(),
                                ProductName = p.product_name,
                                ProductType = p.draw_number,
                                Station = r.Station,
                                StationDesc = s.title,
                                Position = r.Machine,
                                PositionDesc = ps.title,
                                Machine = r.Machine,
                                MachineId = mc.id,
                                MachineCode = mc.code,
                                MachineName = mc.title,
                                Remark = r.Remark,
                                TraceId = r.TraceId,
                                OrderCount = p.quantity,
                                OkCount = r.OkCount,
                                NokCount = r.NokCount,
                                NokCount2 = r.NokCount2,
                                Number = r.Number,
                                Uid = r.Uid,
                                WorkCodeType = r.Type,
                                WorkStaus = r.ReportStatus,
                                Time = DateTime.Now
                            };
            return querylist.OrderBy(o => o.Time).ToList();
        }

        public List<WorkReportInfo> GetDataDtlByWorkCode(int projectId, string workCode)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            join r in accDbContext.siger_tr_product_report on pd.OrderNumber equals r.WorkCode
                            join s in accDbContext.siger_project_level_section on r.Station equals s.id
                            join ps in accDbContext.siger_project_level_section on r.Machine equals ps.id
                            where
                            pd.projectId == projectId && pd.OrderNumber == workCode && r.Type == (int)Type_Status.basket
                            select new WorkReportInfo
                            {
                                Order = p.ordernumber,
                                WorkCode = r.WorkCode,
                                ProductId = p.product_id.ToString(),
                                ProductName = p.product_name,
                                ProductType = p.draw_number,
                                Station = r.Station,
                                StationDesc = s.title,
                                Position = r.Machine,
                                PositionDesc = ps.title,
                                Remark = r.Remark,
                                TraceId = r.TraceId,
                                OrderCount = p.quantity,
                                OkCount = r.OkCount,
                                NokCount = r.NokCount,
                                NokCount2 = r.NokCount2,
                                Number = r.Number,
                                Uid = r.Uid,
                                WorkCodeType = r.Type,
                                WorkStaus = r.ReportStatus,
                                Time = DateTime.Now
                            };
            var data = querylist.OrderBy(o => o.Time).ToList();
            foreach (var d in data)
            {
                var name = GetUserName(d.Uid);
                d.UserName = name == "" ? d.Uid.ToString() : name;
            }
            return data;

        }

        public string GetUserName(int mid)
        {
            var name = string.Empty;
            var user = accDbContext.siger_project_user.FirstOrDefault(f => f.mid == mid);
            if (user != null)
                name = user.name;

            return name;

        }

        public List<WorkReportInfo> GetDataByDate(int projectId, DateTime begin, DateTime end)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            join r in accDbContext.siger_tr_product_report on pd.OrderNumber equals r.WorkCode
                            join s in accDbContext.siger_project_level_section on r.Station equals s.id
                            join ps in accDbContext.siger_project_level_section on r.Machine equals ps.id
                            where
                            pd.projectId == projectId && r.Time >= begin && r.Time <= end && r.Type == (int)Type_Status.basket && r.ReportStatus != (int)Basket_Status.upload
                            select new WorkReportInfo
                            {
                                Order = p.ordernumber,
                                WorkCode = r.WorkCode,
                                ProductId = p.product_id.ToString(),
                                ProductName = p.product_name,
                                ProductType = p.draw_number,
                                Station = r.Station,
                                StationDesc = s.title,
                                Position = r.Machine,
                                PositionDesc = ps.title,
                                Remark = r.Remark,
                                TraceId = r.TraceId,
                                OrderCount = p.quantity,
                                OkCount = r.OkCount,
                                NokCount = r.NokCount,
                                NokCount2 = r.NokCount2,
                                Number = r.Number,
                                Uid = r.Uid,
                                WorkCodeType = r.Type,
                                WorkStaus = r.ReportStatus,
                                Time = r.Time
                            };
            return querylist.OrderBy(o => o.Time).ToList();
        }

        public siger_user GetUser(int mid)
        {
            return accDbContext.siger_user.FirstOrDefault(f => f.id == mid);
        }

        public WorkPlan GetWorkPlan(int projectId, string workCode)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id

                            where
                            pd.projectId == projectId && pd.OrderNumber == workCode
                            select new WorkPlan
                            {
                                productId = p.product_code,
                                productName = p.product_name,
                                productType = p.draw_number
                            };

            return querylist.FirstOrDefault();

        }
        /// <summary>
        /// 设备获取数据
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        public List<WorkReportInfo> GetDataByDate(int projectId, DateTime begin, DateTime end, List<int> section)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            join r in accDbContext.siger_tr_product_report on pd.OrderNumber equals r.WorkCode
                            join s in accDbContext.siger_project_level_section on r.Station equals s.id
                            join ps in accDbContext.siger_project_level_section on r.Machine equals ps.id
                            join ls in accDbContext.siger_project_machine_attribution on ps.id equals ls.station
                            join mc in accDbContext.siger_project_machine on ls.machine equals mc.id
                            join sec in section on r.Machine equals sec
                            where
                            pd.projectId == projectId && r.Time >= begin && r.Time <= end && r.Type == (int)Type_Status.basket && r.ReportStatus != (int)Basket_Status.upload
                            select new WorkReportInfo
                            {
                                Order = p.ordernumber,
                                WorkCode = r.WorkCode,
                                ProductId = p.product_id.ToString(),
                                ProductName = p.product_name,
                                ProductType = p.draw_number,
                                Station = r.Station,
                                StationDesc = s.title,
                                Position = r.Machine,
                                PositionDesc = ps.title,
                                //  Machine=r.Machine,
                                MachineName = mc.title,
                                MachineCode = mc.code,
                                Remark = r.Remark,
                                TraceId = r.TraceId,
                                OrderCount = p.quantity,
                                OkCount = r.OkCount,
                                NokCount = r.NokCount,
                                NokCount2 = r.NokCount2,
                                Number = r.Number,
                                Uid = r.Uid,
                                WorkCodeType = r.Type,
                                WorkStaus = r.ReportStatus,
                                Time = r.Time
                            };
            return querylist.OrderBy(o => o.Time).ToList();
        }

        public WorkCodePlanInfo GetPlanInfo(string wrokCode, int project)
        {
            var querylist = from pd in accDbContext.siger_project_product_plan_detail
                            join p in accDbContext.siger_project_product_plan on pd.PlanId equals p.id
                            where pd.projectId == project && pd.OrderNumber == wrokCode
                            select new WorkCodePlanInfo
                            {
                                WorkCode = pd.OrderNumber,
                                OrderCount = p.quantity,
                                ProductId = p.product_code.ToString(),
                                ProductName = p.product_name.ToString(),
                                ProductType = p.draw_number
                            };

            return querylist.ToList().FirstOrDefault();
        }

        public IPagedCollectionResult<BasketOperateInfo> GetBasketOperateList(string productName, List<int> position, string orderno, string workcode, string machineCode, string basketNo, int uid, 
            int status, DateTime begin, DateTime end, int projectid, int page, int pagesize,int reportstatus = 0, int type = 0)
        {
            Expression<Func<BasketOperateInfo, bool>> Funproductbh = f => true;
            Expression<Func<BasketOperateInfo, bool>> Funorderno = f => true;
            Expression<Func<BasketOperateInfo, bool>> Funworkcode = f => true;
            Expression<Func<BasketOperateInfo, bool>> FunbasketNo = f => true;
            Expression<Func<BasketOperateInfo, bool>> FunmachineCode = f => true;
            Expression<Func<BasketOperateInfo, bool>> Funuid = f => true;
            Expression<Func<BasketOperateInfo, bool>> Funstatus = f => true;
            Expression<Func<BasketOperateInfo, bool>> FunReportStatus = f => true;
            Expression<Func<BasketOperateInfo, bool>> FunType = f => true;

            var query = from r in accDbContext.siger_tr_product_report
                        join p in accDbContext.siger_tr_basketful_position on r.TraceId equals p.traceid
                        join st in accDbContext.siger_project_level_section on r.Station equals st.id
                        join ps in accDbContext.siger_project_level_section on r.Machine equals ps.id
                        join psl in accDbContext.siger_project_machine_attribution on ps.id equals psl.station
                        join m in accDbContext.siger_project_machine on psl.machine equals m.id
                        join u in accDbContext.siger_user on r.login equals u.id
                        join ou in accDbContext.siger_user on r.Uid equals ou.id
                        where position.Contains(r.Machine) && r.Time > begin && r.Time < end && r.projectId == projectid
                        select new BasketOperateInfo
                        {
                            WorkCode = r.WorkCode,
                            OrderCode = p.orderno,
                            PrdNumber = p.productbh,
                            PrdtName = p.productname,
                            ModelType = p.producttype,
                            Station = st.title,
                            Position = ps.title,
                            BasketNumber = r.Number == null ? "" : r.Number,
                            MachineCode = m.code,
                            Report = r.ReportStatus,
                            Type = r.Type,
                            Login = r.login,
                            LoginDesc = u.nickname,
                            User = r.Uid,
                            UserDesc = ou.nickname,
                            TotalCount = p.orderqty,
                            OkCount = r.OkCount,
                            NgCount = r.NokCount,
                            NgCount2 = r.NokCount2,
                            Remarks = r.Remark == null ? "" : r.Remark,
                            Remarks1=r.Remark1,
                            Remarks2=r.Remark2,
                            status = r.status,
                            Rate = r.RateDefect == null ? "" : r.RateDefect,
                            LastUpdate = r.Time,
                        };
            if (!string.IsNullOrEmpty(productName))
                Funproductbh = q => q.PrdtName.Contains(productName);
            if (!string.IsNullOrEmpty(orderno))
                Funorderno = q => q.OrderCode.Contains(orderno);
            if (!string.IsNullOrEmpty(workcode))
                Funworkcode = q => q.WorkCode.Contains(workcode);
            if (!string.IsNullOrEmpty(basketNo))
                FunbasketNo = q => q.BasketNumber.Contains(basketNo);
            if (!string.IsNullOrEmpty(machineCode))
                FunmachineCode = q => q.MachineCode.Contains(machineCode);
            if (reportstatus!=0)
            {
                FunReportStatus = q => q.Report.Equals(reportstatus);
            }
            if (type != 0)
            {
                FunType = q => q.Type.Equals(type);
            }
            if (uid != 0)
                Funuid = q => q.User == uid;
            if (status != 0)
            {
                // 0 :all 1：不通过 2：通过
                if (status == 1)
                    Funstatus = q => q.status == 0;
                else
                    Funstatus = q => q.status == 1;
            }
            var predicate = Funproductbh.And(Funorderno).And(Funworkcode).And(FunbasketNo).And(FunmachineCode).And(Funuid).And(Funstatus).And(FunReportStatus).And(FunType);
            var entities = query.Where(predicate).OrderByDescending(q => q.LastUpdate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            var totalCount = query.Where(predicate).Count();

            foreach (var d in entities)
            {
                d.TypeDesc = EnumHelper.GetEnumDesc((Type_Status)d.Type);
                if (d.Type == (int)Type_Status.basket || d.Type == (int)Type_Status.workCode)
                {
                    d.ReportDesc = EnumHelper.GetEnumDesc((Basket_Status)d.Report);
                    if (d.Report == (int)Basket_Status.Change)
                    {
                        d.ReportDesc += "-" + d.Remarks + EnumHelper.GetEnumDesc((BasketChange_Status.Change_In));
                    }

                    if (d.Report == (int)Basket_Status.CancelUpload)
                    {
                        d.ReportDesc = d.Remarks1 + EnumHelper.GetEnumDesc((Basket_Status.CancelUpload));
                    }

                }
                if (d.Type == (int)Type_Status.machine)
                {
                    d.ReportDesc = EnumHelper.GetEnumDesc((MachineChange_Status)d.Report);
                    if (d.Report == (int)MachineChange_Status.Change)
                    {
                        d.ReportDesc += "-" + EnumHelper.GetEnumDesc((MachineChange_Status.Change));
                    }
                }
                if (d.Type == (int)Type_Status.box)
                {
                    d.ReportDesc = EnumHelper.GetEnumDesc((Box_Status)d.Report);
                }


            }
            return new PagedCollectionResult<BasketOperateInfo>(entities, totalCount);

        }

        public IEnumerable<BasketOperate> GetBasketOperateByBasketNo(int condiId, string basketno, int projectId)
        {
            var query = from b in accDbContext.siger_tr_basketlist
                        join p in accDbContext.siger_tr_basketful_position on b.traceId equals p.traceid
                        join r in accDbContext.siger_tr_product_report on b.traceId equals r.TraceId
                        join u in accDbContext.siger_user on r.Uid equals u.id
                        where r.Type == (int)Type_Status.basket && b.status == (int)BasketList_Status.Normal && b.number == basketno && b.number == r.Number && r.projectId == projectId
                        orderby r.Time descending
                        select new BasketOperate
                        {
                            mktnumber = r.Number,
                            datatype = r.ReportStatus,
                            wonumber = p.workcode,
                            prdtname = p.productname,
                            modeltype = p.producttype,
                            totalcnt = r.OkCount + r.NokCount + r.NokCount2,
                            okcnt = r.OkCount,
                            ngcnt = r.NokCount + r.NokCount2,
                            badratio = r.RateDefect,
                            premkt = r.Remark,
                            staff = u.nickname + string.Format("({0})", r.Uid),
                            remarks = r.Remark,
                            reportstatus = r.ReportStatus,
                            createtime = r.Time,
                            status = r.status,
                            remarks1 = r.Remark1,
                            finalcnt = r.OkCount
                        };

            var data = query.ToList();
            foreach (var d in data)
            {
                if (d.reportstatus == (int)Basket_Status.Modify)
                {
                    if (int.TryParse(d.remarks1, out int preCount))
                        d.precnt = preCount;
                }
                if (d.reportstatus == (int)Basket_Status.QC)
                {
                    d.ispassed = d.status.ToString();
                }
            }
            return data;
        }
    }
}
