using WCS.BLL.Config;
using WCS.BLL.DbModels;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.DAL.Db;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel.InOutRecord;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.MatDetailCurrentInfo;
using WCS.Model.ApiModel.MatDetailHistoryInfo;
using WCS.Model.ApiModel.Stocktaking;
using WCS.Model.WebSocketModel;

namespace WCS.BLL.Services.Service
{
    public class StockTakingService : IStockTakingService
    {
        #region SysStockTakingOrder
        public async Task<ResponseBase> SysStockTakingOrder(SysStockTakingOrderRequest request)
        {
            //先判断盘点单据号是否已存在（避免前端多次提交后生成多个的情况）
            var stocktakingOrder = await DbHelp.db.Queryable<StockTakingOrder>()
                                                  .Where(t => t.StocktakingOrderNumber == request.StocktakingOrderNumber)
                                                  .FirstAsync();
            if (stocktakingOrder != null)
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：盘点单据{stocktakingOrder.StocktakingOrderNumber}已存在！"
                };
            else
            {
                //分成三类
                switch (request.StocktakingOrderType)
                {
                    case "shelfCodes":
                        return await SysStockTakingOrderByShelfCodes(request);
                    case "matCodes":
                        return await SysStockTakingOrderByMatCodes(request);
                    case "snList":
                        return await SysStockTakingOrderSnList(request);
                    default:
                        return new SysStockTakingOrderResponse()
                        {
                            Code = 201,
                            Message = $"操作失败：[{request.StocktakingOrderType}]不支持的操作！!"
                        };
                }
            }
        }

        public async Task<ResponseBase> SysStockTakingOrderByShelfCodes(SysStockTakingOrderRequest request)
        {
            //校验参数
            if (request.List == null || request.List.Count == 0)
                return new SysStockTakingOrderResponse()
                {

                    Code = 201,
                    Message = $"操作失败：缺少必要参数"
                };
            //先判断是否有这些货架
            var shelfs = ShelfManager.Shelves
                                     .Where(t => request.List.Contains(t.ShelfCode))
                                     .ToList();
            if (shelfs.Count < request.List.Count)
            {
                foreach (var shelf in shelfs)
                {
                    request.List.RemoveAll(t => t == shelf.ShelfCode);
                }
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：货架[{string.Join(",", request.List)}]不存在！"
                };
            }
            try
            {
                //获取库存数据 生成盘点单据
                var inventoryDetails = await DbHelp.db.Queryable<InventoryDetail>()
                                            .Includes(t => t.StoreInfo)
                                            .Where(t => request.List.Contains(t.StoreInfo.ShelfCode))
                                            .ToListAsync();
                if (inventoryDetails == null || inventoryDetails.Count == 0)
                {
                    return new SysStockTakingOrderResponse()
                    {
                        Code = 201,
                        Message = $"操作失败：未找到需要盘点的库存数据！"
                    };
                }

                await DbHelp.db.BeginTranAsync();

                //盘点单据保存
                var stockTakingOrder = new StockTakingOrder()
                {
                    StocktakingOrderNumber = request.StocktakingOrderNumber,
                    StocktakingOrderSource = request.StocktakingOrderSource,
                    CreateUser = request.UserName,
                    GroupName = LocalFile.Config.GroupName,
                };
                var stockTakingOrderId = await DbHelp.db.Insertable(stockTakingOrder).ExecuteReturnIdentityAsync();
                stockTakingOrder.Id = stockTakingOrderId;
                //盘点物料明细保存
                foreach (var inventoryDetail in inventoryDetails)
                {
                    var stockTakingOrderMatDetail = new StockTakingOrderMatDetail()
                    {
                        StocktakingOrderId = stockTakingOrderId,
                        StocktakingOrderNumber = request.StocktakingOrderNumber,

                        StoreId = inventoryDetail.StoreId,
                        StoreCode = inventoryDetail.StoreCode,

                        InventoryDetailId = inventoryDetail.Id,
                        MatSN = inventoryDetail.MatSN,
                        MatCode = inventoryDetail.MatCode,
                        MatName = inventoryDetail.MatName,
                        MatBatch = inventoryDetail.MatBatch,
                        MatSpec = inventoryDetail.MatSpec,
                        MatQty = inventoryDetail.MatQty,
                        MatCustomer = inventoryDetail.MatCustomer,
                        MatSupplier = inventoryDetail.MatSupplier,

                        IsStocktaking = false,
                        StocktakingQty = inventoryDetail.MatQty,
                        UpdateUser = request.UserName
                    };
                    await DbHelp.db.Insertable(stockTakingOrderMatDetail).ExecuteReturnIdentityAsync();
                }
                await DbHelp.db.CommitTranAsync();
                return new SysStockTakingOrderResponse()
                {
                    Data = new SysStockTakingOrderData() { StocktakingOrderNumber = request.StocktakingOrderNumber },
                    Code = 200,
                    Message = $"Success"
                };
            }
            catch (Exception ex)
            {
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：{ex.Message}"
                };
            }
        }

        public async Task<ResponseBase> SysStockTakingOrderByMatCodes(SysStockTakingOrderRequest request)
        {
            //校验参数
            if (request.List == null || request.List.Count == 0)
                return new SysStockTakingOrderResponse()
                {

                    Code = 201,
                    Message = $"操作失败：缺少必要参数"
                };
            //获取库存数据 生成盘点单据
            var inventoryDetails = await DbHelp.db.Queryable<InventoryDetail>()
                                            .Where(t => request.List.Contains(t.MatCode))
                                            .ToListAsync();
            if (inventoryDetails == null || inventoryDetails.Count == 0)
            {
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：未找到需要盘点的库存数据！"
                };
            }
            try
            {
                await DbHelp.db.BeginTranAsync();

                //盘点单据保存
                var stockTakingOrder = new StockTakingOrder()
                {
                    StocktakingOrderNumber = request.StocktakingOrderNumber,
                    StocktakingOrderSource = request.StocktakingOrderSource,
                    GroupName = LocalFile.Config.GroupName,
                    CreateUser = request.UserName
                };
                var stockTakingOrderId = await DbHelp.db.Insertable(stockTakingOrder).ExecuteReturnIdentityAsync();
                stockTakingOrder.Id = stockTakingOrderId;
                //盘点物料明细保存
                foreach (var inventoryDetail in inventoryDetails)
                {
                    var stockTakingOrderMatDetail = new StockTakingOrderMatDetail()
                    {
                        StocktakingOrderId = stockTakingOrderId,
                        StocktakingOrderNumber = request.StocktakingOrderNumber,

                        StoreId = inventoryDetail.StoreId,
                        StoreCode = inventoryDetail.StoreCode,

                        InventoryDetailId = inventoryDetail.Id,
                        MatSN = inventoryDetail.MatSN,
                        MatCode = inventoryDetail.MatCode,
                        MatName = inventoryDetail.MatName,
                        MatBatch = inventoryDetail.MatBatch,
                        MatSpec = inventoryDetail.MatSpec,
                        MatQty = inventoryDetail.MatQty,
                        MatCustomer = inventoryDetail.MatCustomer,
                        MatSupplier = inventoryDetail.MatSupplier,

                        IsStocktaking = false,
                        StocktakingQty = inventoryDetail.MatQty,
                        UpdateUser = request.UserName
                    };
                    await DbHelp.db.Insertable(stockTakingOrderMatDetail).ExecuteReturnIdentityAsync();
                }
                await DbHelp.db.CommitTranAsync();
                return new SysStockTakingOrderResponse()
                {
                    Data = new SysStockTakingOrderData() { StocktakingOrderNumber = request.StocktakingOrderNumber },
                    Code = 200,
                    Message = $"Success"
                };
            }
            catch (Exception ex)
            {
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：{ex.Message}"
                };
            }
        }

        public async Task<ResponseBase> SysStockTakingOrderSnList(SysStockTakingOrderRequest request)
        {
            //校验参数
            if (request.List == null || request.List.Count == 0)
                return new SysStockTakingOrderResponse()
                {

                    Code = 201,
                    Message = $"操作失败：缺少必要参数"
                };
            //获取库存数据 生成盘点单据
            var inventoryDetails = await DbHelp.db.Queryable<InventoryDetail>()
                                            .Where(t => request.List.Contains(t.MatSN))
                                            .WhereIF(!string.IsNullOrEmpty(LocalFile.Config.GroupName), t => t.GroupName == LocalFile.Config.GroupName)
                                            .ToListAsync();
            if (inventoryDetails == null || inventoryDetails.Count == 0)
            {
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：未找到需要盘点的库存数据！"
                };
            }
            try
            {
                await DbHelp.db.BeginTranAsync();

                //盘点单据保存
                var stockTakingOrder = new StockTakingOrder()
                {
                    StocktakingOrderNumber = request.StocktakingOrderNumber,
                    StocktakingOrderSource = request.StocktakingOrderSource,
                    GroupName = LocalFile.Config.GroupName,
                    CreateUser = request.UserName
                };
                var stockTakingOrderId = await DbHelp.db.Insertable(stockTakingOrder).ExecuteReturnIdentityAsync();
                stockTakingOrder.Id = stockTakingOrderId;
                //盘点物料明细保存
                foreach (var inventoryDetail in inventoryDetails)
                {
                    var stockTakingOrderMatDetail = new StockTakingOrderMatDetail()
                    {
                        StocktakingOrderId = stockTakingOrderId,
                        StocktakingOrderNumber = request.StocktakingOrderNumber,

                        StoreId = inventoryDetail.StoreId,
                        StoreCode = inventoryDetail.StoreCode,

                        InventoryDetailId = inventoryDetail.Id,
                        MatSN = inventoryDetail.MatSN,
                        MatCode = inventoryDetail.MatCode,
                        MatName = inventoryDetail.MatName,
                        MatBatch = inventoryDetail.MatBatch,
                        MatSpec = inventoryDetail.MatSpec,
                        MatQty = inventoryDetail.MatQty,
                        MatCustomer = inventoryDetail.MatCustomer,
                        MatSupplier = inventoryDetail.MatSupplier,

                        IsStocktaking = false,
                        StocktakingQty = inventoryDetail.MatQty,
                        UpdateUser = request.UserName
                    };
                    await DbHelp.db.Insertable(stockTakingOrderMatDetail).ExecuteReturnIdentityAsync();
                }
                await DbHelp.db.CommitTranAsync();
                return new SysStockTakingOrderResponse()
                {
                    Data = new SysStockTakingOrderData() { StocktakingOrderNumber = request.StocktakingOrderNumber },
                    Code = 200,
                    Message = $"生成盘点单据成功！\r\n单据号为：{request.StocktakingOrderNumber}"
                };
            }
            catch (Exception ex)
            {
                return new SysStockTakingOrderResponse()
                {
                    Code = 201,
                    Message = $"操作失败：{ex.Message}"
                };
            }
        }
        #endregion

        public async Task<PageQueryResponse<StockTakingOrder>> getStockTakingOrders(GetStockTakingOrdersRequest request)
        {
            try
            {

                var recordsQueryable = DbHelp.db.Queryable<StockTakingOrder>()
                                                .WhereIF(!string.IsNullOrEmpty(request.StocktakingOrderNumber), t => t.StocktakingOrderNumber.Contains(request.StocktakingOrderNumber))
                                                .WhereIF(!string.IsNullOrEmpty(request.StocktakingOrderSource), t => t.StocktakingOrderSource != null && t.StocktakingOrderSource.Contains(request.StocktakingOrderSource))
                                                .WhereIF(!string.IsNullOrEmpty(LocalFile.Config.GroupName), t => t.GroupName == LocalFile.Config.GroupName);

                switch (request.StocktakingOrderStatus)
                {
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.未盘点:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.未盘点);
                        break;
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.部分盘点:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.部分盘点);
                        break;
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.已提交:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.已提交);
                        break;
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.盘点完成:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.盘点完成);
                        break;
                    default:
                        break;
                }

                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .OrderByDescending(t => t.Id)
                                    .Skip((request.PageNumber - 1) * request.PageSize).Take(request.PageSize)
                                    .Select<StockTakingOrder>()
                                    .ToListAsync();
                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = (request.PageNumber - 1) * request.PageSize + i + 1;
                }

                return new PageQueryResponse<StockTakingOrder>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<StockTakingOrder>()
                    {
                        TotalCount = totalCount,
                        MaxPage = request.PageSize == 0 ? 0 : (int)Math.Ceiling((decimal)totalCount / request.PageSize),
                        Count = records.Count,
                        Lists = records.ToList()
                    }
                };

            }
            catch (Exception ex)
            {
                return new PageQueryResponse<StockTakingOrder>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<PageQueryResponse<StockTakingOrder>> getStockTakingOrdersByStatus(GetStockTakingOrdersRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<StockTakingOrder>();

                switch (request.StocktakingOrderStatus)
                {
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.未盘点:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.未盘点);
                        break;
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.部分盘点:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.部分盘点);
                        break;
                    case Model.ApiModel.Stocktaking.StocktakingOrderStatus.盘点完成:
                        recordsQueryable = recordsQueryable.Where(t => t.StocktakingOrderStatus == StocktakingOrderStatus.盘点完成);
                        break;
                    default:
                        break;
                }

                var records = await recordsQueryable
                                    .Where(t => t.StocktakingOrderStatus != StocktakingOrderStatus.已提交)
                                    .WhereIF(!string.IsNullOrEmpty(LocalFile.Config.GroupName), t => t.GroupName == LocalFile.Config.GroupName)
                                    .OrderByDescending(t => t.UpdateTime)
                                    .Take(40)
                                    .ToListAsync();

                return new PageQueryResponse<StockTakingOrder>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<StockTakingOrder>()
                    {
                        Lists = records.ToList()
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<StockTakingOrder>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<ResponseBase> getStockTakingOrderMatDetail(GetStockTakingOrderMatDetailRequest request)
        {
            #region 查询盘点单
            StockTakingOrder order = null;
            if (request.StockTakingOrderId != 0)
            {
                order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.Id == request.StockTakingOrderId).FirstAsync();
                if (order == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"查询失败：不存在Id为{request.StockTakingOrderId}的盘点单！",
                    };
                }
            }
            else if (!string.IsNullOrEmpty(request.StockTakingOrderNumber))
            {
                order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.StocktakingOrderNumber == request.StockTakingOrderNumber)
                                                                     .FirstAsync();
                if (order == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"查询失败：不存在单据号为{request.StockTakingOrderNumber}的盘点单！",
                    };
                }
            }
            else
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"查询失败：缺少必要参数！",
                };
            }
            #endregion

            //查询物料明细
            var stockTakingOrderMatDetail = await DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                        .Where(t => t.StocktakingOrderId == order.Id)
                                        .ToListAsync();
            //生成序号
            for (int i = 0; i < stockTakingOrderMatDetail.Count; i++)
            {
                stockTakingOrderMatDetail[i].RowNumber = i + 1;
            }
            return new ResponseCommon<List<StockTakingOrderMatDetail>>()
            {
                Code = 200,
                Message = "success",
                Data = stockTakingOrderMatDetail
            };
        }

        public async Task<ResponseBase> startStockTakingOrder(GetStockTakingOrderMatDetailRequest request)
        {
            try
            {
                #region 查询盘点单
                StockTakingOrder order = null;
                if (request.StockTakingOrderId != 0)
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.Id == request.StockTakingOrderId).FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在Id为{request.StockTakingOrderId}的盘点单！",
                        };
                    }
                    if (order.StocktakingOrderStatus == StocktakingOrderStatus.已提交)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：盘点单据:{request.StockTakingOrderNumber}已提交！",
                        };
                    }
                }
                else if (!string.IsNullOrEmpty(request.StockTakingOrderNumber))
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.StocktakingOrderNumber == request.StockTakingOrderNumber)
                                                                         .FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在单据号为{request.StockTakingOrderNumber}的盘点单！",
                        };
                    }
                    if (order.StocktakingOrderStatus == StocktakingOrderStatus.已提交)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：盘点单据:{request.StockTakingOrderNumber}已提交！",
                        };
                    }
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"操作失败：缺少必要参数！",
                    };
                }
                #endregion

                #region 查询需要盘点的物料明细
                //查询物料明细
                var stockTakingOrderMatDetails = await DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                            .Where(t => t.StocktakingOrderId == order.Id)
                                            //.Where(t => t.IsStocktaking == false)
                                            .Includes(t => t.StoreInfo)
                                            .ToListAsync();
                if (stockTakingOrderMatDetails == null || stockTakingOrderMatDetails.Count == 0)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"盘点单据{order.StocktakingOrderNumber}物料已全部盘点！",
                        Data = null
                    };
                }

                #endregion

                #region 按货架进入盘点模式
                var shelfIds = stockTakingOrderMatDetails.Select(t => t.StoreInfo.ShelfId)
                                 .Distinct()
                                 .ToList();
                var shelfs = ShelfManager.Shelves.Where(t => shelfIds.Contains(t.ShelfId)).ToList(); ;

                var outherModeShelfs = shelfs.Where(t => t.CurrentMode != HardWare.Mode.待机模式).Select(t => t.ShelfCode).ToList();
                if (outherModeShelfs != null && outherModeShelfs.Count > 0)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"进入盘点模式失败：货架{string.Join("", outherModeShelfs)}不在待机模式",
                        Data = null
                    };
                }
                //对应的货架对应位置 进入盘点模式 亮灯
                shelfs.ForEach(shelf =>
                {
                    var matDetails = stockTakingOrderMatDetails.Where(t => t.StoreInfo.ShelfCode == shelf.ShelfCode)
                                                       .Distinct()
                                                       .ToList();
                    shelf.GoInStocktaking(matDetails, order);
                    shelf.OrderNumber = order.StocktakingOrderNumber;
                });
                //更新Order
                order.UpdateTime = DateTime.Now;
                DbHelp.db.Updateable(order).ExecuteCommand();

                //返回
                return new ResponseCommon()
                {
                    Code = 200,
                    Message = "Success",
                    Data = null
                };
                #endregion
            }
            catch (Exception ex)
            {
                await endStockTakingOrder(request);
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"操作失败，{ex.Message}",
                };
            }
        }

        public async Task<ResponseBase> endStockTakingOrder(GetStockTakingOrderMatDetailRequest request)
        {
            try
            {
                #region 查询盘点单
                StockTakingOrder order = null;
                if (request.StockTakingOrderId != 0)
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.Id == request.StockTakingOrderId).FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在Id为{request.StockTakingOrderId}的盘点单！",
                        };
                    }
                }
                else if (!string.IsNullOrEmpty(request.StockTakingOrderNumber))
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.StocktakingOrderNumber == request.StockTakingOrderNumber)
                                                                         .FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在单据号为{request.StockTakingOrderNumber}的盘点单！",
                        };
                    }
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"操作失败：缺少必要参数！",
                    };
                }
                #endregion

                #region 查询当前盘点单 已启动的货架
                var shelfs = ShelfManager.Shelves.Where(t => t.CurrentMode == HardWare.Mode.盘点模式 && t.OrderNumber == order.StocktakingOrderNumber).ToList();
                shelfs.ForEach(t =>
                {
                    t.GoOutStocktaking();
                });
                #endregion

                return new ResponseCommon()
                {
                    Code = 200,
                    Message = $"success",
                    Data = shelfs.Select(t => t.ShelfCode).ToList(),
                };
            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"操作失败，{ex.Message}",
                };
            }
        }

        public async Task<ResponseBase> queryMatInfoInStocktakingOrder(QueryMatInfoInStocktakingOrderRequest request)
        {
            //判断库存中是否有这个物料
            var inventoryDetail = await DbHelp.db.Queryable<InventoryDetail>()
                                            .LeftJoin<StoreInfo>((id, si) => id.StoreId == si.Id)
                                            .Where((id, si) => id.MatSN == request.MatSN)
                                            .Select((id, si) => si)
                                            .FirstAsync();
            if (inventoryDetail == null)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"库存中不存在物料[{request.MatSN}]",
                };
            }

            //判断货架是否已进入盘点模式
            var shelf = ShelfManager.Shelves
                                     .Where(t => t.ShelfCode == inventoryDetail.ShelfCode)
                                     .FirstOrDefault(); ;
            if (shelf == null)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"货架{inventoryDetail.ShelfCode}不存在！",
                };
            }
            else if (shelf.CurrentMode != HardWare.Mode.盘点模式)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"货架{inventoryDetail.ShelfCode}不在盘点模式！",
                };
            }

            var stockTakingOrder = await DbHelp.db.Queryable<StockTakingOrder>()
                                                  .Where(t => t.StocktakingOrderNumber == shelf.OrderNumber)
                                                  .FirstAsync();
            if (stockTakingOrder == null)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"未找到对应盘点单据{shelf.OrderNumber}",
                };
            }
            //返回具体的单据信息
            var stockTakinOrderMatDetail = await DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                                   .Where(t => t.StocktakingOrderId == stockTakingOrder.Id)
                                                   .Where(t => t.MatSN == request.MatSN)
                                                   .FirstAsync();
            if (stockTakinOrderMatDetail != null)
                return new ResponseCommon<StockTakingOrderMatDetail>()
                {
                    Code = 200,
                    Message = "success",
                    Data = stockTakinOrderMatDetail
                };
            else
                return new ResponseCommon<StockTakingOrderMatDetail>()
                {
                    Code = 201,
                    Message = "不是本次盘点的物料！",
                    Data = null
                };
        }

        public async Task<ResponseBase> confirmStocktakingOrder(ConfirmStocktakingOrderRequest request)
        {
            try
            {
                //获取盘点物料明细
                var stockTakingMatDetail = await DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                                .Where(t => t.Id == request.Id)
                                                .Includes(t => t.StoreInfo)
                                                .FirstAsync();

                if (stockTakingMatDetail == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"不存在的盘点明细",
                    };
                }

                DbHelp.db.BeginTran();
                //修改盘点物料明细的数量
                stockTakingMatDetail.StocktakingQty = request.Qty;
                stockTakingMatDetail.IsStocktaking = true;
                DbHelp.db.Updateable(stockTakingMatDetail)
                               .ExecuteCommand();



                #region 发送指令 对应货架对应模组确认盘点
                //判断货架是否已进入盘点模式
                var shelf = ShelfManager.Shelves
                                         .Where(t => t.ShelfCode == stockTakingMatDetail.StoreInfo.ShelfCode)
                                         .FirstOrDefault(); ;
                if (shelf == null)
                {
                    DbHelp.db.RollbackTran();
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"货架{stockTakingMatDetail.StoreInfo.ShelfCode}不存在！",
                    };
                }
                else if (shelf.CurrentMode != HardWare.Mode.盘点模式)
                {
                    DbHelp.db.RollbackTran();
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"货架{stockTakingMatDetail.StoreInfo.ShelfCode}不在盘点模式！",
                    };
                }
                if (shelf.OrderNumber != request.StocktakingOrderNumber)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"盘点单据{request.StocktakingOrderNumber}不在盘点模式！",
                    };
                }
                shelf.ConfirmStocktakingSingle(stockTakingMatDetail.StoreInfo.BoardId, stockTakingMatDetail.StoreInfo.LightNumber);


                #endregion

                DbHelp.db.CommitTran();

                //通知前台刷新
                Task.Run(() =>
                {
                    var messageMode = new WebSocketMessageModel()
                    {
                        IsWarning = false,
                        ClientIp = shelf.WebSocketIpAddress,
                        WarningType = WarningTypeEnum.通知刷新盘点
                    };
                    WarningManager.SendWarning(messageMode);
                });

                //更新时间 避免被自动退出
                Task.Run(() =>
                {
                    var shelves = ShelfManager.Shelves.Where(t => t.CurrentMode == HardWare.Mode.盘点模式 && t.OrderNumber == request.StocktakingOrderNumber)
                                                      .ToList();
                    foreach (var shelf in shelves)
                    {
                        shelf.SetCurrentModeTime = DateTime.Now;
                    }
                });
                #region 更新Order状态
                Task.Run(() =>
                {
                    //获取Order
                    var order = DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.Id == stockTakingMatDetail.StocktakingOrderId).First();
                    if (order != null)
                    {
                        var orderDetails = DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                                    .Where(t => t.StocktakingOrderId == stockTakingMatDetail.StocktakingOrderId)
                                                    .ToList();
                        var stocktakedDetailCount = orderDetails.Where(t => t.IsStocktaking).Count();
                        if (stocktakedDetailCount < orderDetails.Count && order.StocktakingOrderStatus == StocktakingOrderStatus.未盘点)
                        {
                            order.StocktakingOrderStatus = StocktakingOrderStatus.部分盘点;
                            DbHelp.db.Updateable(order).ExecuteCommand();
                        }
                        else if (stocktakedDetailCount == orderDetails.Count)
                        {
                            order.StocktakingOrderStatus = StocktakingOrderStatus.盘点完成;
                            DbHelp.db.Updateable(order).ExecuteCommand();
                        }
                    }
                });
                #endregion

                return new ResponseCommon()
                {
                    Code = 200,
                    Message = $"success",
                };
            }
            catch (Exception ex)
            {
                DbHelp.db.RollbackTran();
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"确认盘点失败：{ex.Message}",
                };
            }
        }

        public async Task<ResponseBase> commitStockTakingOrder(GetStockTakingOrderMatDetailRequest request)
        {
            try
            {
                #region 查询盘点单
                StockTakingOrder order = null;
                if (request.StockTakingOrderId != 0)
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.Id == request.StockTakingOrderId).FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在Id为{request.StockTakingOrderId}的盘点单！",
                        };
                    }
                }
                else if (!string.IsNullOrEmpty(request.StockTakingOrderNumber))
                {
                    order = await DbHelp.db.Queryable<StockTakingOrder>().Where(t => t.StocktakingOrderNumber == request.StockTakingOrderNumber)
                                                                         .FirstAsync();
                    if (order == null)
                    {
                        return new ResponseCommon()
                        {
                            Code = 201,
                            Message = $"操作失败：不存在单据号为{request.StockTakingOrderNumber}的盘点单！",
                        };
                    }
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"操作失败：缺少必要参数！",
                    };
                }
                #endregion

                #region 判断单据状态
                if (order.StocktakingOrderStatus == StocktakingOrderStatus.已提交)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"单据已提交，请勿重复提交！",
                    };
                }
                //else if (order.StocktakingOrderStatus != StocktakingOrderStatus.盘点完成)
                //{
                //    return new ResponseCommon()
                //    {
                //        Code = 201,
                //        Message = $"单据未盘点完成！！！",
                //    };
                //}
                #endregion

                #region 查询盘点明细
                var stockTakingOrderMatDetails = await DbHelp.db.Queryable<StockTakingOrderMatDetail>()
                                                          .Where(t => t.StocktakingOrderId == order.Id && t.IsStocktaking)
                                                          .ToListAsync();
                if (stockTakingOrderMatDetails == null || stockTakingOrderMatDetails.Count == 0)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"不存在已盘点的物料！",
                    };
                }
                #endregion

                #region 提交盘点 修改数量 生成记录
                try
                {
                    DbHelp.db.BeginTran();

                    var inventoryDetailIds = stockTakingOrderMatDetails.Select(t => t.InventoryDetailId)
                                                                       .ToList();
                    //查询对应的库存数据
                    var inventoryDetails = DbHelp.db.Queryable<InventoryDetail>()
                                                              .Where(t => inventoryDetailIds.Contains(t.Id))
                                                              .ToList();
                    inventoryDetails.ForEach(inventoryDetail =>
                    {
                        //对应的盘点明细
                        var stockTakingOrderMatDetail = stockTakingOrderMatDetails.Where(t => t.InventoryDetailId == inventoryDetail.Id).FirstOrDefault();
                        if (stockTakingOrderMatDetail == null)
                        {
                            //这个分支应该是不用管的哦
                        }
                        else
                        {
                            //比对数量变化
                            var changedQty = stockTakingOrderMatDetail.StocktakingQty - inventoryDetail.MatQty;
                            if (changedQty != 0)
                            {
                                //库存表修改数量
                                inventoryDetail.MatQty = stockTakingOrderMatDetail.StocktakingQty;
                                //出入库记录表生成记录
                                var inOutRecord = new InOutRecord()
                                {
                                    StoreCode = inventoryDetail.StoreCode,
                                    StoreId = inventoryDetail.StoreId,

                                    R = inventoryDetail.R,
                                    C = inventoryDetail.C,
                                    Wei = inventoryDetail.Wei,
                                    BigShelfCode = inventoryDetail.BigShelfCode,
                                    GroupName = inventoryDetail.GroupName,

                                    MatSN = inventoryDetail.MatSN,
                                    MatCode = inventoryDetail.MatCode,
                                    MatName = inventoryDetail.MatName,
                                    MatBatch = inventoryDetail.MatBatch,
                                    MatQty = changedQty,
                                    MatSpec = inventoryDetail.MatSpec,
                                    MatCustomer = inventoryDetail.MatCustomer,
                                    MatSupplier = inventoryDetail.MatSupplier,
                                    OrderNumber = stockTakingOrderMatDetail.StocktakingOrderNumber,

                                    Direction = DirectionEnum.盘点,
                                    OperateUser = request.UserName
                                };
                                DbHelp.db.Updateable(inventoryDetail).ExecuteCommand();
                                DbHelp.db.Insertable(inOutRecord).ExecuteCommand();
                            }
                            //数量相等的情况 暂时不用管 不动库存数据也不生成记录
                            else
                            {

                            }
                        }
                    });

                    order.StocktakingOrderStatus = StocktakingOrderStatus.已提交;
                    DbHelp.db.Updateable(order).ExecuteCommand();

                    DbHelp.db.CommitTran();
                }
                catch (Exception ex)
                {
                    DbHelp.db.RollbackTran();
                    return new ResponseCommon()
                    {
                        Code = 300,
                        Message = $"操作失败，{ex.Message}",
                    };
                }
                #endregion

                return new ResponseCommon()
                {
                    Code = 200,
                    Message = $"success",
                };
            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"操作失败，{ex.Message}",
                };
            }
        }


        #region 赛特制冷
        public async Task<ResponseCommon> stockTakingById(StockTakingByIdRequest request)
        {
            //先查询有无这一条库存记录
            var matDetailCurrentInfo = await DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                                .Where(t => t.Id == request.MatDetailCurrentInfoId)
                                                .FirstAsync();
            if (matDetailCurrentInfo == null)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"操作失败:所选记录不存在！",
                    Data = null,
                };
            }

            //查询是否已经存在未提交的盘点记录
            var stocktakingInfo = await DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                           .Where(t => t.MatDetailCurrentId == request.MatDetailCurrentInfoId)
                                           .Where(t => t.StocktakingStatus == StocktakingStatusEnum.未提交)
                                           .FirstAsync();
            //如果存在未提交的盘点记录 将上一次的记录更新即可
            if (stocktakingInfo != null)
            {
                stocktakingInfo.StocktakingQty = request.StocktakingQty;
                stocktakingInfo.StocktakingUser = request.UserName;
                stocktakingInfo.StocktakingTime = DateTime.Now;
                DbHelp.db.Updateable(stocktakingInfo).ExecuteCommand();
            }
            //不存在盘点记录 新增即可
            else
            {
                stocktakingInfo = new MatDetailStocktakingInfo()
                {
                    MatDetailCurrentId = matDetailCurrentInfo.Id,
                    ShlefId = matDetailCurrentInfo.ShelfId,
                    ShelfCode = matDetailCurrentInfo.ShelfCode,
                    ShelfType = matDetailCurrentInfo.ShelfType,
                    ShelfArea = "",
                    MatCode = matDetailCurrentInfo.MatCode,
                    MatName = matDetailCurrentInfo.MatName,
                    MatBatch = matDetailCurrentInfo.MatBatch,
                    
                    MatSpec = matDetailCurrentInfo.MatSpec,
                    MatQty = matDetailCurrentInfo.MatQty,
                    StocktakingQty = request.StocktakingQty,
                    MatSupplier = matDetailCurrentInfo.MatSupplier,
                    StocktakingUser = request.UserName,
                    StocktakingTime = DateTime.Now,
                    StocktakingStatus = StocktakingStatusEnum.未提交,
                };
                DbHelp.db.Insertable(stocktakingInfo).ExecuteCommand();
            }

            return new ResponseCommon()
            {
                Code = 200,
                Message = $"success",
            };
        }

        public async Task<PageQueryResponse<MatDetailStocktakingInfoModel>> getStocktakingInfos(GetStocktakingInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                                .LeftJoin<ShelfInfo>((mci, si) => mci.ShlefId == si.Id)
                                                .LeftJoin<LocationInfo>((mci, si, li) => (si.TransStatus == TransStatusEnum.静止 && si.CurrentLocationId == li.Id)
                                                || (si.TransStatus == TransStatusEnum.运输中 && si.DestinationLocationId == li.Id))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatCode), (mci, si, li) => mci.MatCode.Contains(request.MatCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatName), (mci, si, li) => mci.MatName.Contains(request.MatName))
                                                .WhereIF(!string.IsNullOrEmpty(request.StocktakingUser), (mci, si, li) => mci.StocktakingUser.Contains(request.StocktakingUser))
                                                .WhereIF(request.StocktakingStatus != null, (mci, si, li) => mci.StocktakingStatus == request.StocktakingStatus)
                                                .Select((mci, si, li) => new MatDetailStocktakingInfoModel()
                                                {
                                                    Id = mci.Id,
                                                    MatDetailCurrentId = mci.MatDetailCurrentId,

                                                    ShlefId = mci.ShlefId,
                                                    ShelfCode = mci.ShelfCode,
                                                    ShelfType = si.ShelfTypeName,
                                                    ShelfArea = li.LocationArea,

                                                    MatCode = mci.MatCode,
                                                    MatName = mci.MatName,
                                                    MatBatch = mci.MatBatch,
                                                    MatSpec = mci.MatSpec,
                                                    MatQty = mci.MatQty,
                                                    StocktakingQty = mci.StocktakingQty,
                                                    MatSupplier = mci.MatSupplier,
                                                    MatCustomer = mci.MatCustomer,

                                                    StocktakingUser = mci.StocktakingUser,
                                                    StocktakingTime = mci.StocktakingTime,
                                                    StocktakingStatus = mci.StocktakingStatus,
                                                });

                //分页
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .OrderByDescending(mci => mci.Id)
                                    .Skip((request.PageNumber - 1) * request.PageSize).Take(request.PageSize)
                                    .ToListAsync();
                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = (request.PageNumber - 1) * request.PageSize + i + 1;
                }
                return new PageQueryResponse<MatDetailStocktakingInfoModel>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<MatDetailStocktakingInfoModel>()
                    {
                        TotalCount = totalCount,
                        MaxPage = request.PageSize == 0 ? 0 : (int)Math.Ceiling((decimal)totalCount / request.PageSize),
                        Count = records.Count,
                        Lists = records.ToList()
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<MatDetailStocktakingInfoModel>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<PageQueryResponse<MatDetailStocktakingInfoModel>> exportStocktakingInfos(GetStocktakingInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                                .LeftJoin<ShelfInfo>((mci, si) => mci.ShlefId == si.Id)
                                                .LeftJoin<LocationInfo>((mci, si, li) => (si.TransStatus == TransStatusEnum.静止 && si.CurrentLocationId == li.Id)
                                                || (si.TransStatus == TransStatusEnum.运输中 && si.DestinationLocationId == li.Id))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatCode), (mci, si, li) => mci.MatCode.Contains(request.MatCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatName), (mci, si, li) => mci.MatName.Contains(request.MatName))
                                                .WhereIF(!string.IsNullOrEmpty(request.StocktakingUser), (mci, si, li) => mci.StocktakingUser.Contains(request.StocktakingUser))
                                                .WhereIF(request.StocktakingStatus != null, (mci, si, li) => mci.StocktakingStatus == request.StocktakingStatus)
                                                .Select((mci, si, li) => new MatDetailStocktakingInfoModel()
                                                {
                                                    Id = mci.Id,
                                                    MatDetailCurrentId = mci.MatDetailCurrentId,

                                                    ShlefId = mci.ShlefId,
                                                    ShelfCode = mci.ShelfCode,
                                                    ShelfType = si.ShelfTypeName,
                                                    ShelfArea = li.LocationArea,

                                                    MatCode = mci.MatCode,
                                                    MatName = mci.MatName,
                                                    MatBatch = mci.MatBatch,

                                                    MatSpec = mci.MatSpec,
                                                    MatQty = mci.MatQty,
                                                    StocktakingQty = mci.StocktakingQty,
                                                    MatSupplier = mci.MatSupplier,
                                                    MatCustomer = mci.MatCustomer,

                                                    StocktakingUser = mci.StocktakingUser,
                                                    StocktakingTime = mci.StocktakingTime,
                                                    StocktakingStatus = mci.StocktakingStatus,
                                                });

                //分页
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .OrderByDescending(mci => mci.Id)
                                    .Take(65535)
                                    .ToListAsync();

                //生成序号
                var index = 1;
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = index++;
                }

                return new PageQueryResponse<MatDetailStocktakingInfoModel>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<MatDetailStocktakingInfoModel>()
                    {
                        TotalCount = totalCount,
                        MaxPage = request.PageSize == 0 ? 0 : (int)Math.Ceiling((decimal)totalCount / request.PageSize),
                        Count = records.Count,
                        Lists = records.ToList()
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<MatDetailStocktakingInfoModel>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<PageQueryResponse<MatDetailCurrentInfoModel>> getStocktakingInfosByShelfCode(GetStocktakingInfosByShelfCodeRequest request)
        {
            try
            {
                //获取货架是否存在
                var shelf = await DbHelp.db.Queryable<ShelfInfo>()
                                           .Where(t => t.ShelfCode == request.ShelfCode && t.IsEnable == true)
                                           .FirstAsync();
                if (shelf == null)
                {
                    return new PageQueryResponse<MatDetailCurrentInfoModel>()
                    {
                        Code = 201,
                        Message = $"货架[{request.ShelfCode}]不存在或已被禁用！",
                        Data = null
                    };
                }

                //获取当前的未提交的盘点数据
                var stockTaking = DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                           .Where(t => t.ShlefId == shelf.Id)
                                           .Where(t => t.StocktakingStatus == StocktakingStatusEnum.未提交)
                                           .ToList();
                //获取当前货架绑定的库存数据
                var matDetailCurrentInfo = DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                           .Where(t => t.ShelfId == shelf.Id)
                                           .ToList();

                var recordsQueryable = DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                               .LeftJoin<ShelfInfo>((mci, si) => mci.ShelfId == si.Id)
                                               .LeftJoin<LocationInfo>((mci, si, li) => (si.TransStatus == TransStatusEnum.静止 && si.CurrentLocationId == li.Id)
                                               || (si.TransStatus == TransStatusEnum.运输中 && si.DestinationLocationId == li.Id))
                                               .Where((mci, si, li) => mci.ShelfId == shelf.Id)
                                               .Select((mci, si, li) => new MatDetailCurrentInfoModel()
                                               {
                                                   Id = mci.Id,
                                                   ShelfId = mci.ShelfId,
                                                   ShelfCode = mci.ShelfCode,
                                                   ShelfType = mci.ShelfType,

                                                   LocationArea = li.LocationArea,
                                                   LocationCode = li.LocationCode,

                                                   MatCode = mci.MatCode,
                                                   MatName = mci.MatName,
                                                   MatBatch = mci.MatBatch,
                                                   MatSpec = mci.MatSpec,
                                                   MatUnit = mci.MatUnit,
                                                   MatCustomer = mci.MatCustomer,
                                                   MatQty = mci.MatQty,
                                                   MatSupplier = mci.MatSupplier,

                                                   StationCode = mci.StationCode,
                                                   ModifyUser = mci.ModifyUser,
                                                   ModifyTime = mci.ModifyTime
                                               });

                //分页
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .OrderByDescending(mci => mci.Id)
                                    .Skip((request.PageNumber - 1) * request.PageSize).Take(request.PageSize)
                                    .ToListAsync();
                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = (request.PageNumber - 1) * request.PageSize + i + 1;
                    var stockTakingRecord = stockTaking.Where(t => t.MatDetailCurrentId == records[i].Id)
                                                       .FirstOrDefault();
                    if (stockTakingRecord != null)
                    {
                        records[i].StocktakingQty = stockTakingRecord.StocktakingQty;
                    }
                }
                //按盘点状态排序(未盘点的为-1)
                //records = records.OrderBy(t => t.StocktakingQty)
                //    .ThenBy(t => t.Id)
                //    .ToList();
                return new PageQueryResponse<MatDetailCurrentInfoModel>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<MatDetailCurrentInfoModel>()
                    {
                        TotalCount = totalCount,
                        MaxPage = request.PageSize == 0 ? 0 : (int)Math.Ceiling((decimal)totalCount / request.PageSize),
                        Count = records.Count,
                        Lists = records.ToList()
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<MatDetailCurrentInfoModel>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }
        /// <summary>
        /// 更新盘点数据的数量
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ResponseCommon<object>> updateStocktakingInfo(UpdateStocktakingInfoRequest request)
        {
            try
            {
                var matDetailCurrentInfo = await DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                                          .Where(t => t.Id == request.MatDetailStocktakingInfoId)
                                                          .FirstAsync();
                if (matDetailCurrentInfo == null)
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 205,
                        Message = $"更新盘点数据失败：此条数据不存在，请确认！",
                        Data = null
                    };
                }
                matDetailCurrentInfo.StocktakingQty = request.StocktakingQty;
                matDetailCurrentInfo.StocktakingUser = request.UserName;
                matDetailCurrentInfo.StocktakingTime = DateTime.Now;
                var rowNum = await DbHelp.db.Updateable(matDetailCurrentInfo).ExecuteCommandAsync();
                if (rowNum == 0)
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 201,
                        Message = $"更新盘点数据失败：请重试！",
                        Data = null
                    };
                }
                else
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 200,
                        Message = $"更新盘点数据成功！",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<object>> deleteStocktakingInfos(DeleteInfosRequest request)
        {
            //先查询出具体的Id
            var MatDetailCurrentInfos = await DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                               .Where(t => request.needDeleteIds.Contains(t.Id))
                                               .ToListAsync();
            //执行删除
            try
            {
                var deleteRows = await DbHelp.db.Deleteable(MatDetailCurrentInfos).ExecuteCommandAsync();
                return new ResponseCommon<Object>
                {
                    Code = 200,
                    Message = $"已删除{deleteRows}条数据！",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<object>> commitStocktakingInfos(DeleteInfosRequest request)
        {
            try
            {
                //先查询出具体的Id
                var stocktakingInfos = await DbHelp.db.Queryable<MatDetailStocktakingInfo>()
                                                   .Where(t => request.needDeleteIds.Contains(t.Id))
                                                   .ToListAsync();
                if (stocktakingInfos == null || stocktakingInfos.Count < request.needDeleteIds.Count)
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 201,
                        Message = $"操作失败:请刷新后重试！",
                        Data = null
                    };
                }

                if (stocktakingInfos.Where(t => t.StocktakingStatus == StocktakingStatusEnum.已提交).Any())
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 201,
                        Message = $"操作失败:存在已提交的盘点数据！",
                        Data = null
                    };
                }

                var marCurrentInfoIds = stocktakingInfos.Select(t => t.MatDetailCurrentId)
                                                        .Distinct()
                                                        .ToList();
                var matCurrentInfos = await DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                                   .Where(t => marCurrentInfoIds.Contains(t.Id))
                                                   .ToListAsync();
                DbHelp.db.BeginTran();
                foreach (var matCurrentInfo in matCurrentInfos)
                {
                    var stocktakingInfo = stocktakingInfos.Where(t => t.MatDetailCurrentId == matCurrentInfo.Id)
                                                          .FirstOrDefault();
                    if (stocktakingInfo == null)
                    {
                        continue;
                    }
                    if (stocktakingInfo.StocktakingQty != 0 && stocktakingInfo.StocktakingQty != matCurrentInfo.MatQty)
                    {
                        //库存修改记录
                        var historyInfo = new MatDetailHistoryInfo()
                        {
                            ShlefId = matCurrentInfo.ShelfId,
                            ShelfType = matCurrentInfo.ShelfType,
                            ShelfCode = matCurrentInfo.ShelfCode,

                            MatCode = matCurrentInfo.MatCode,
                            MatName = matCurrentInfo.MatName,
                            MatBatch = matCurrentInfo.MatBatch,
                            MatSpec = matCurrentInfo.MatSpec,
                            MatCustomer = matCurrentInfo?.MatCustomer,
                            MatSupplier = matCurrentInfo?.MatSupplier,

                            BeforeQty = matCurrentInfo.MatQty,
                            AfterQty = stocktakingInfo.StocktakingQty,

                            ModifyTime = DateTime.Now,
                            ModifyUser = request.UserName,
                            RecordType = RecordTypeEnum.修改,
                            FunctionType =  FunctionTypeEnum.库存盘点,
                        };
                        DbHelp.db.Insertable(historyInfo).ExecuteCommand();

                        matCurrentInfo.MatQty = stocktakingInfo.StocktakingQty;
                        matCurrentInfo.ModifyUser = request.UserName;
                        matCurrentInfo.ModifyTime = DateTime.Now;

                        DbHelp.db.Updateable(matCurrentInfo).ExecuteCommand();
                    }
                    else if(stocktakingInfo.StocktakingQty == 0)
                    {
                        //库存修改记录
                        var historyInfo = new MatDetailHistoryInfo()
                        {
                            ShlefId = matCurrentInfo.ShelfId,
                            ShelfType = matCurrentInfo.ShelfType,
                            ShelfCode = matCurrentInfo.ShelfCode,

                            MatCode = matCurrentInfo.MatCode,
                            MatName = matCurrentInfo.MatName,
                            MatBatch = matCurrentInfo.MatBatch,

                            MatSpec = matCurrentInfo.MatSpec,
                            MatCustomer = matCurrentInfo?.MatCustomer,
                            MatSupplier = matCurrentInfo?.MatSupplier,

                            BeforeQty = matCurrentInfo.MatQty,
                            AfterQty = 0,

                            ModifyTime = DateTime.Now,
                            ModifyUser = request.UserName,
                            RecordType = RecordTypeEnum.删除,
                            FunctionType = FunctionTypeEnum.库存盘点,
                        };
                        DbHelp.db.Insertable(historyInfo).ExecuteCommand();

                        DbHelp.db.Deleteable(matCurrentInfo).ExecuteCommand();
                    }
                    stocktakingInfo.StocktakingStatus = StocktakingStatusEnum.已提交;
                    DbHelp.db.Updateable(stocktakingInfo).ExecuteCommand();
                }
                DbHelp.db.CommitTran();
                DataProcessManager.UpdateShelfStatus();
                return new ResponseCommon<object>()
                {
                    Code = 200,
                    Message = "success",
                    Data = null,
                };
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }
        #endregion
    }
}
