/// <summary>
        /// 金生金办理
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="operationEntity"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public static int CreateJSJOrder(OrderEntity entity, OrderOperationEntity operationEntity, string loginId)
        {
            List<DeliverEntity> deliverList = new List<DeliverEntity>();//需要更新的交割单列表
            List<DeliverRecordEntity> deliverRecordList = new List<DeliverRecordEntity>();//交割单记录列表
            #region 赋值

            entity.OrderId = Guid.NewGuid().ToString("n");
            entity.OrderNo = "JSJ" + DateTime.Now.ToString("yyMMddhhmmssffff");
            entity.OrderCode = "";
            entity.OrderType = (int)OrderType.金生金;
            entity.State = (int)OrderState.新订单;
            entity.CreateDate = DateTime.Now.ToString();
            entity.EndDate = DateTime.Now.ToString();

            operationEntity.OperationId = Guid.NewGuid().ToString("n");
            operationEntity.OperationDate = DateTime.Now.ToString();
            operationEntity.Account = entity.Account;
            operationEntity.OperationId = Guid.NewGuid().ToString("n");
            operationEntity.OrderId = entity.OrderId;
            operationEntity.OrderNo = entity.OrderNo;
            operationEntity.Type = 5;
            operationEntity.Remark = string.Format("用户:{0} 创建金生金订单", entity.Account);

            #endregion

            List<DeliverEntity> list = GetListByAccount(entity.Account, Direction.提货单, 1);

            #region 计算交割单信息

            Dictionary<GoodsType, decimal> dic = new Dictionary<GoodsType, decimal>();
            dic.Add(GoodsType.Au, entity.Au);
            dic.Add(GoodsType.Ag, entity.Ag);
            dic.Add(GoodsType.Pd, entity.Pd);
            dic.Add(GoodsType.Pt, entity.Pt);
            foreach (var key in dic.Keys)
            {
                var tmp = list.Where(m => m.Goods.Equals((int)key)).ToList();
                var values = dic[key];
                if (values <= 0) continue;
                foreach (var mm in tmp)
                {
                    DeliverRecordEntity recordEntity = new DeliverRecordEntity
                    {
                        DeliverId = mm.DeliverId,
                        DeliverNo = mm.DeliverNo,
                        Goods = mm.Goods,
                        Direction = mm.Direction,
                        LockPrice = mm.LockPrice,
                        OrderType = (int)OrderType.金生金,
                        OrderId = entity.OrderId,
                        OrderNo = entity.OrderNo
                    };
                    if (values > mm.AvailableTotal)
                    {
                        recordEntity.UseTotal = mm.AvailableTotal;
                        values -= mm.AvailableTotal;
                        mm.AvailableTotal = 0;
                        mm.State = 0;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                        break;
                    }
                    else
                    {
                        mm.State = values.Equals(mm.AvailableTotal) ? 0 : 1;
                        recordEntity.UseTotal = values;
                        mm.AvailableTotal -= values;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                        break;
                    }
                }
            }

            #endregion
            StockEntity userEntity = new StockEntity();
            userEntity = LoadByAccount(entity.UserId);

            entity.AuP = userEntity.AuPrice;
            entity.AgP = userEntity.AgPrice;
            UserLogEntity userLogEntity = new UserLogEntity();

            userLogEntity.Account = entity.UserId;
            userLogEntity.DESC = string.Format(@"用户{0}金生金办理:Ag:{1},Au:{2};订单号:{3}", entity.Account, entity.Au, entity.Ag, entity.OrderNo);
            userLogEntity.UserType = (int)LogType.用户库存调整减少;
            YicelTransaction tran = new YicelTransaction();
            try
            {
                tran.BeginTransaction();
                CreateOrder(entity, tran);//创建订单信息
                CreateOrderOperation(operationEntity, tran);//创建金生金订单操作记录
                deliverRecordList.ForEach(m => CreateDeliverRecord(m, tran));//插入交割单记录信息
                deliverList.ForEach(m => UpdateDeliver(m, entity, operationEntity.OperationId, tran));//更新交割单信息
                UpdateUserTotal(entity, userEntity, tran);//更新用户库存数量
                CreateLog(userLogEntity, tran);
                tran.Commit();
                return 1;
            }
            catch (Exception ex)
            {
                tran.Rollback();
                ManagerLog.WriteErr(ex);
                return 0;
            }
        }
 /// <summary>
 /// 后台用户库存查询
 /// </summary>
 /// <param name="userId">用户ID</param>
 /// <returns></returns>
 public static StockEntity GetAdminUserStockInfo(string userId)
 {
     SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@UserID", userId) };
     DataTable dt = DbHelper.RunProcedure("P_UserAdminStockInfo", paras, "Stock_BZJ").Tables[0];
     if (dt.Rows.Count > 0)
     {
         StockEntity stockEntity = CreateEntity(dt);
         return stockEntity;
     }
     StockEntity sEntity = new StockEntity();
     sEntity.Ag = 0;
     sEntity.Au = 0;
     sEntity.Pd = 0;
     sEntity.Pt = 0;
     sEntity.AuPrice = 0;
     sEntity.AgPrice = 0;
     sEntity.PdPrice = 0;
     sEntity.PtPrice = 0;
     return sEntity;
 }
 /// <summary>
 /// 创建个人库存实体
 /// </summary>
 /// <param name="dt"></param>
 /// <returns></returns>
 private static StockEntity CreateEntity(DataTable dt)
 {
     StockEntity entity = new StockEntity();
     entity.StockID = dt.Rows[0]["StockID"].ToString();
     entity.UserId = dt.Rows[0]["UserId"].ToString();
     entity.Au = Convert.ToDecimal(dt.Rows[0]["Au"]);
     entity.Ag = Convert.ToDecimal(dt.Rows[0]["Ag"]);
     entity.Pt = Convert.ToDecimal(dt.Rows[0]["Pt"]);
     entity.Pd = Convert.ToDecimal(dt.Rows[0]["Pd"]);
     entity.Au_b = Convert.ToDecimal(dt.Rows[0]["Au_b"]);
     entity.Ag_b = Convert.ToDecimal(dt.Rows[0]["Ag_b"]);
     entity.Pt_b = Convert.ToDecimal(dt.Rows[0]["Pt_b"]);
     entity.Pd_b = Convert.ToDecimal(dt.Rows[0]["Pd_b"]);
     entity.AuTotal = Convert.ToDecimal(dt.Rows[0]["AuTotal"]);
     entity.AgTotal = Convert.ToDecimal(dt.Rows[0]["AgTotal"]);
     entity.PtTotal = Convert.ToDecimal(dt.Rows[0]["PtTotal"]);
     entity.PdTotal = Convert.ToDecimal(dt.Rows[0]["PdTotal"]);
     entity.AuPrice = Convert.ToDecimal(dt.Rows[0]["AuPrice"]);
     entity.AgPrice = Convert.ToDecimal(dt.Rows[0]["AgPrice"]);
     entity.PtPrice = Convert.ToDecimal(dt.Rows[0]["PtPrice"]);
     entity.PdPrice = Convert.ToDecimal(dt.Rows[0]["PdPrice"]);
     entity.AuAmount = Convert.ToDecimal(dt.Rows[0]["AuAmount"]);
     entity.AgAmount = Convert.ToDecimal(dt.Rows[0]["AgAmount"]);
     entity.PtAmount = Convert.ToDecimal(dt.Rows[0]["PtAmount"]);
     entity.PdAmount = Convert.ToDecimal(dt.Rows[0]["PdAmount"]);
     return entity;
 }
 /// <summary>
 /// 更新员工库存数量
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="userEntity"></param>
 /// <param name="tran"></param>
 private static void UpdateUserTotal(OrderEntity entity, StockEntity userEntity, YicelTransaction tran)
 {
     if (entity.OrderType == (int)OrderType.提货单 || entity.OrderType == (int)OrderType.回购单)
     {
         if (entity.Au != 0)
             UpdateTotal(entity.UserId, Direction.提货单, GoodsType.Au, entity.Au * -1, userEntity, tran);
         if (entity.Ag != 0)
             UpdateTotal(entity.UserId, Direction.提货单, GoodsType.Ag, entity.Ag * -1, userEntity, tran);
         if (entity.Pt != 0)
             UpdateTotal(entity.UserId, Direction.提货单, GoodsType.Pt, entity.Pt * -1, userEntity, tran);
         if (entity.Pd != 0)
             UpdateTotal(entity.UserId, Direction.提货单, GoodsType.Pd, entity.Pd * -1, userEntity, tran);
     }
     if (entity.OrderType == (int)OrderType.卖单)
     {
         if (entity.Au != 0)
             UpdateTotal(entity.UserId, Direction.卖单, GoodsType.Au, entity.Au * -1, userEntity, tran);
         if (entity.Ag != 0)
             UpdateTotal(entity.UserId, Direction.卖单, GoodsType.Ag, entity.Ag * -1, userEntity, tran);
         if (entity.Pt != 0)
             UpdateTotal(entity.UserId, Direction.卖单, GoodsType.Pt, entity.Pt * -1, userEntity, tran);
     }
     if (entity.OrderType == (int)OrderType.金生金)
     {
         if (entity.Au != 0)
             UpdateTotal(entity.UserId, Direction.金生金, GoodsType.Au, entity.Au * -1, userEntity, tran);
         if (entity.Ag != 0)
             UpdateTotal(entity.UserId, Direction.金生金, GoodsType.Ag, entity.Ag * -1, userEntity, tran);
         if (entity.Pt != 0)
             UpdateTotal(entity.UserId, Direction.金生金, GoodsType.Pt, entity.Pt * -1, userEntity, tran);
         if (entity.Pd != 0)
             UpdateTotal(entity.UserId, Direction.金生金, GoodsType.Pd, entity.Pd * -1, userEntity, tran);
     }
     if (entity.OrderType == (int)OrderType.库存调整)
     {
         if (entity.Au != 0)
             UpdateTotal(entity.UserId, Direction.库存调整, GoodsType.Au, entity.Au, userEntity, tran);
         if (entity.Ag != 0)
             UpdateTotal(entity.UserId, Direction.库存调整, GoodsType.Ag, entity.Ag, userEntity, tran);
         if (entity.Pt != 0)
             UpdateTotal(entity.UserId, Direction.库存调整, GoodsType.Pt, entity.Pt, userEntity, tran);
         if (entity.Pd != 0)
             UpdateTotal(entity.UserId, Direction.库存调整, GoodsType.Pd, entity.Pd, userEntity, tran);
     }
 }
 /// <summary>
 /// 检查库存中心是否与交割信息相等
 /// </summary>
 private static bool CheckTotal(OrderEntity entity, StockEntity userEntity)
 {
     //获取用户交割单各物品总重量
     Dictionary<GoodsType, GoodsEntity> goodsDic = null;
     //判断用户物品数量是否与交割物品数量相等 2013/4/6
     if (entity.OrderType == (int)OrderType.提货单 || entity.OrderType == (int)OrderType.金生金 || entity.OrderType == (int)OrderType.回购单)
     {
         goodsDic = ComFunction.GetGoodsDic(entity.Account, Direction.提货单);
         if (goodsDic[GoodsType.Au].Total != userEntity.Au)
             return false;
         if (goodsDic[GoodsType.Ag].Total != userEntity.Ag)
             return false;
         if (goodsDic[GoodsType.Pt].Total != userEntity.Pt)
             return false;
         if (goodsDic[GoodsType.Pd].Total != userEntity.Pd)
             return false;
     }
     else if (entity.OrderType == (int)OrderType.卖单)
     {
         goodsDic = ComFunction.GetGoodsDic(entity.Account, Direction.卖单);
         if (goodsDic[GoodsType.Au].Total != userEntity.Au_b)
             return false;
         if (goodsDic[GoodsType.Ag].Total != userEntity.Ag_b)
             return false;
         if (goodsDic[GoodsType.Pt].Total != userEntity.Pt_b)
             return false;
         if (goodsDic[GoodsType.Pd].Total != userEntity.Pd_b)
             return false;
     }
     else
     {
         return false;
     }
     return true;
 }
        /// <summary>
        /// 更新用户库存数量
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="d">提货 卖</param>
        /// <param name="type">物品类型</param>
        /// <param name="total"></param>
        /// <param name="userEntity">数量</param>
        /// <param name="tran"></param>
        public static void UpdateTotal(string uid, Direction d, GoodsType type, decimal total, StockEntity userEntity, YicelTransaction tran)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update Stock_BZJ set ");
            #region
            if (d == Direction.提货单)
            {
                switch (type)
                {
                    case GoodsType.Au:
                        if (userEntity.AuTotal + total * userEntity.AuPrice >= 0)
                        {
                            strSql.Append("Au=Au+@Total,AuTotal=AuTotal+@Total*AuPrice,AuAmount=AuAmount+@Total ");
                        }
                        else
                        {
                            strSql.Append("Au=Au+@Total,AuTotal=0,AuAmount=0 ");
                        }
                        break;
                    case GoodsType.Ag:
                        if (userEntity.AgTotal + total * userEntity.AgPrice >= 0)
                        {
                            strSql.Append("Ag=Ag+@Total,AgTotal=AgTotal+@Total*AgPrice,AgAmount=AgAmount+@Total ");
                        }
                        else
                        {
                            strSql.Append("Ag=Ag+@Total,AgTotal=0,AgAmount=0 ");
                        }
                        break;
                    case GoodsType.Pt:
                        if (userEntity.PtTotal + total * userEntity.PtPrice >= 0)
                        {
                            strSql.Append("Pt=Pt+@Total,PtTotal=PtTotal+@Total*PtPrice,PtAmount=PtAmount+@Total ");
                        }
                        else
                        {
                            strSql.Append("Pt=Pt+@Total,PtTotal=0,PtAmount=0 ");
                        }
                        break;
                    case GoodsType.Pd:
                        if (userEntity.PdTotal + total * userEntity.PdPrice >= 0)
                        {
                            strSql.Append("Pd=Pd+@Total,PdTotal=PdTotal+@Total*PdPrice,PdAmount=PdAmount+@Total ");
                        }
                        else
                        {
                            strSql.Append("Pd=Pd+@Total,PdTotal=0,PdAmount=0 ");
                        }
                        break;
                }
            }
            else if (d == Direction.卖单)
            {
                switch (type)
                {
                    case GoodsType.Au:
                        strSql.Append("Au_b=Au_b+@Total ");
                        break;
                    case GoodsType.Ag:
                        strSql.Append("Ag_b=Ag_b+@Total ");
                        break;
                    case GoodsType.Pt:
                        strSql.Append("Pt_b=Pt_b+@Total ");
                        break;
                }
            }
            else if (d == Direction.金生金 || d == Direction.到期单 || d == Direction.已生金单 || d == Direction.提成单 || d == Direction.金店库存同步 || d == Direction.库存调整)
            {
                switch (type)
                {
                    case GoodsType.Au:
                        strSql.Append("Au=Au+@Total ");
                        break;
                    case GoodsType.Ag:
                        strSql.Append("Ag=Ag+@Total ");
                        break;
                    case GoodsType.Pt:
                        strSql.Append("Pt=Pt+@Total ");
                        break;
                    case GoodsType.Pd:
                        strSql.Append("Pd=Pd+@Total ");
                        break;
                }
            }
            #endregion
            strSql.Append("where UserId=@UserId");

            SqlParameter[] parms = new SqlParameter[] {
                new SqlParameter("@UserId",uid),
                new SqlParameter("@Total",total)
            };
            DbHelper.ExecuteNonQuery(strSql.ToString(), parms, tran.Transaction);
        }
        /// <summary>
        /// 更新订单状态为已提货或卖
        /// </summary>
        /// <param name="agentId"></param>
        /// <param name="order"></param>
        /// <param name="dataMember"></param>
        /// <param name="operationEntity"></param>
        /// <param name="dList"></param>
        /// <param name="userId"></param>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public static bool UpdateBackOrder(string agentId, OrderEntity order, List<UpdateDataMember> dataMember, OrderOperationEntity operationEntity, List<DeliverEntity> dList, string userId, StockEntity userEntity)
        {
            List<DeliverEntity> deliverList = new List<DeliverEntity>();//需要更新的交割单列表
            List<DeliverRecordEntity> deliverRecordList = new List<DeliverRecordEntity>();
            List<UpdateDataMember> updateList = new List<UpdateDataMember>();//需要更新的订单信息
            List<UpdateDataMember> userList = new List<UpdateDataMember>();//需要更新用户数量

            OrderEntity entity = LoadByOrderCode(order.OrderCode);//获取订单信息
            StockEntity stockEntity = LoadByAccount(entity.UserId);//获取订单所属用户信息
            Direction d = entity.OrderType == (int)OrderType.提货单 ? Direction.提货单 : Direction.卖单;

            #region 合法性验证
            //获取用户交割单各物品总重量
            Dictionary<GoodsType, GoodsEntity> goodsDic = GetGoodsDic(entity.Account, d);
            //判断用户交割单种类是否小于0 或者小于提交的种类数量
            if (goodsDic.Count <= 0 || goodsDic.Count < dataMember.Count)
                return false;
            //判断用户物品数量是否与交割物品数量相等 2013/4/6
            if (!CheckTotal(order, stockEntity))
                return false;

            //循环判断提交重量是否大于用户交割单总重量
            foreach (var m in dataMember)
            {
                foreach (var g in goodsDic.Values)
                {
                    if (m.field.ToLower() == g.Symbol.ToString().ToLower() && Convert.ToDecimal(m.value) > g.Total)
                    {
                        return false;
                    }
                    else
                    {
                        if (m.field.ToLower() == "au")
                        {
                            entity.Au = Convert.ToDecimal(m.value);
                            updateList.Add(new UpdateDataMember { field = "Au", value = m.value });

                            updateList.Add(new UpdateDataMember { field = "AuP", value = stockEntity.AuPrice });
                            if (Convert.ToDecimal(m.value) > stockEntity.AuAmount)
                            {
                                updateList.Add(new UpdateDataMember { field = "AuQuantity", value = stockEntity.AuAmount });
                            }
                            else
                            {
                                updateList.Add(new UpdateDataMember { field = "AuQuantity", value = m.value });
                            }
                            break;
                        }
                        if (m.field.ToLower() == "ag")
                        {
                            entity.Ag = Convert.ToDecimal(m.value);
                            updateList.Add(new UpdateDataMember { field = "Ag", value = m.value });

                            updateList.Add(new UpdateDataMember { field = "AgP", value = stockEntity.AgPrice });
                            if (Convert.ToDecimal(m.value) > stockEntity.AuAmount)
                            {
                                updateList.Add(new UpdateDataMember { field = "AgQuantity", value = stockEntity.AgAmount });
                            }
                            else
                            {
                                updateList.Add(new UpdateDataMember { field = "AgQuantity", value = m.value });
                            }
                            break;
                        }
                        if (m.field.ToLower() == "pt")
                        {
                            entity.Pt = Convert.ToDecimal(m.value);
                            updateList.Add(new UpdateDataMember { field = "Pt", value = m.value });

                            updateList.Add(new UpdateDataMember { field = "PtP", value = stockEntity.PtPrice });
                            if (Convert.ToDecimal(m.value) > stockEntity.AuAmount)
                            {
                                updateList.Add(new UpdateDataMember { field = "PtQuantity", value = stockEntity.PtAmount });
                            }
                            else
                            {
                                updateList.Add(new UpdateDataMember { field = "PtQuantity", value = m.value });
                            }
                            break;
                        }
                        if (m.field.ToLower() == "pd")
                        {
                            entity.Pd = Convert.ToDecimal(m.value);
                            updateList.Add(new UpdateDataMember { field = "Pd", value = m.value });

                            updateList.Add(new UpdateDataMember { field = "PdP", value = stockEntity.PdPrice });
                            if (Convert.ToDecimal(m.value) > stockEntity.AuAmount)
                            {
                                updateList.Add(new UpdateDataMember { field = "PdQuantity", value = stockEntity.PdAmount });
                            }
                            else
                            {
                                updateList.Add(new UpdateDataMember { field = "PdQuantity", value = m.value });
                            }
                            break;
                        }
                    }
                }
            }

            #endregion

            //获取交割单信息
            List<DeliverEntity> list = GetListByAccount(entity.Account, d, 1);
            if (list == null || list.Count <= 0)
                return false;

            #region 计算交割单信息

            Dictionary<GoodsType, decimal> dic = new Dictionary<GoodsType, decimal>();
            dic.Add(GoodsType.Au, entity.Au);
            dic.Add(GoodsType.Ag, entity.Ag);
            dic.Add(GoodsType.Pd, entity.Pd);
            dic.Add(GoodsType.Pt, entity.Pt);
            foreach (var key in dic.Keys)
            {
                var tmp = list.Where(m => m.Goods.Equals((int)key)).ToList(); var values = dic[key];
                if (values <= 0) continue;
                foreach (var mm in tmp)
                {
                    DeliverRecordEntity recordEntity = new DeliverRecordEntity
                    {
                        DeliverId = mm.DeliverId,
                        DeliverNo = mm.DeliverNo,
                        Goods = mm.Goods,
                        Direction = mm.Direction,
                        LockPrice = mm.LockPrice,
                        OrderType = order.OrderType,
                        OrderId = entity.OrderId,
                        OrderNo = entity.OrderNo
                    };
                    if (values > mm.AvailableTotal)
                    {
                        recordEntity.UseTotal = mm.AvailableTotal;
                        values -= mm.AvailableTotal;
                        mm.AvailableTotal = 0;
                        mm.State = 0;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                    }
                    else
                    {
                        mm.State = values.Equals(mm.AvailableTotal) ? 0 : 1;
                        recordEntity.UseTotal = values;
                        mm.AvailableTotal -= values;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                        break;
                    }
                }
            }

            #endregion

            #region 部分实体赋值
            AgentDeliverEntity agentDeliverEntity = new AgentDeliverEntity
            {
                AgentInfoId = agentId,
                OrderId = entity.OrderId,
                FromTo = 1,
                Direction = d,
                Ag = entity.Ag,
                Au = entity.Au,
                Pd = entity.Pd,
                Pt = entity.Pt
            };
            #endregion
            updateList.Add(new UpdateDataMember { field = "State", value = "2" });
            updateList.Add(new UpdateDataMember { field = "Version", value = (entity.Version + 1).ToString() });
            updateList.Add(new UpdateDataMember { field = "EndDate", value = DateTime.Now.ToString() });

            UserLogEntity userLogEntity = new UserLogEntity();

            userLogEntity.Account = agentId;
            userLogEntity.DESC = string.Format(@"金商{5},用户{0}提货:Ag:{1},Au:{2},Pt:{3},Pd:{4};", entity.Account, entity.Au, entity.Ag, entity.Pt, entity.Pd, entity.AgentName);
            userLogEntity.UserType = (int)LogType.用户库存调整减少;

            operationEntity.OrderId = entity.OrderId;
            operationEntity.OrderNo = entity.OrderNo;
            operationEntity.OperationId = Guid.NewGuid().ToString("n");
            StockEntity stock = new StockEntity();
            stock = LoadByAccount(userId);//获取订单所属用户信息

            stock.Au = stock.Au + Math.Abs(order.Au);
            stock.Ag = stock.Ag + Math.Abs(order.Ag);
            stock.Pt = stock.Pt + Math.Abs(order.Pt);
            stock.Pd = stock.Pd + Math.Abs(order.Pd);

            stock.AuAmount = stock.AuAmount + Math.Abs(order.Au);
            stock.AgAmount = stock.AgAmount + Math.Abs(order.Ag);
            stock.PtAmount = stock.PtAmount + Math.Abs(order.Pt);
            stock.PdAmount = stock.PdAmount + Math.Abs(order.Pd);

            stock.AuTotal = stock.AuTotal + Math.Abs(order.Au) * userEntity.AuPrice;
            stock.AgTotal = stock.AgTotal + Math.Abs(order.Ag) * userEntity.AgPrice;
            stock.PtTotal = stock.PtTotal + Math.Abs(order.Pt) * userEntity.PtPrice;
            stock.PdTotal = stock.PdTotal + Math.Abs(order.Pd) * userEntity.PdPrice;

            if (stock.AuAmount > 0)
            {
                stock.AuPrice = stock.AuTotal / stock.AuAmount;
            }
            if (stock.AgAmount > 0)
            {
                stock.AgPrice = stock.AgTotal / stock.AgAmount;
            }
            if (stock.PtAmount > 0)
            {
                stock.PtPrice = stock.PtTotal / stock.PtAmount;
            }
            if (stock.PdAmount > 0)
            {
                stock.PdPrice = stock.PdTotal / stock.PdAmount;
            }

            YicelTransaction tran = new YicelTransaction();
            try
            {
                tran.BeginTransaction();
                CreateOrderOperation(operationEntity, tran);//创建订单操作记录
                deliverList.ForEach(m => UpdateDeliver(m, entity, operationEntity.OperationId, tran));//更新交割单信息
                deliverRecordList.ForEach(m => CreateDeliverRecord(m, tran));//创建订单对应交割单信息
                UpdateUserTotal(entity, stockEntity, tran);//更新用户库存数量

                CreateAgent(agentDeliverEntity, tran);//创建金商库存
                dList.ForEach(m => CreateDeliver(m, tran));//创建绑定帐号交割单
                UpdateAgentTotal(stock, tran);    //更新金商绑定用户库存信息

                UpdateColumns(entity.OrderId, updateList, tran);
                UpdateOrderState(entity.OrderId, agentId, userId, operationEntity.Account, tran);

                CreateLog(userLogEntity, tran);
                tran.Commit();
                return true;
            }
            catch
            {
                tran.Rollback();
                return false;
            }
        }
 //public static int CreateDeliverAgent(DeliverEntity entity, YicelTransaction tran)
 //{
 //    SqlParameter[] paras = new SqlParameter[] {
 //        new SqlParameter("@OrderNo", entity.DeliverNo),
 //        new SqlParameter("@Account", entity.Account),
 //        new SqlParameter("@UserID", entity.UserID),
 //        new SqlParameter("@Price", entity.LockPrice),
 //        new SqlParameter("@Goodst", entity.Goods),
 //        new SqlParameter("@Quantity", entity.Total),
 //        new SqlParameter("@Direction", entity.Direction),
 //        new SqlParameter("@OperUserID", entity.OperationUserID)
 //        };
 //    int result;
 //    return DbHelper.RunProcedure("P_CreateDeliverAgent", paras, out result);
 //}
 /// <summary>
 /// 更新金商绑定用户库存信息
 /// </summary>
 /// <param name="stock"></param>
 /// <param name="tran"></param>
 public static void UpdateAgentTotal(StockEntity stock, YicelTransaction tran)
 {
     StringBuilder strSql = new StringBuilder();
     strSql.AppendFormat(@"update Stock_BZJ SET Au={0},Ag={1},Pt ={2},Pd={3},AuPrice={4},AgPrice={5},PtPrice={6},PdPrice={7},AuTotal={8},AgTotal={9},PtTotal={10},PdTotal={11},AuAmount={12},AgAmount={13},PtAmount={14},PdAmount={15}",
     stock.Au, stock.Ag, stock.Pt, stock.Pd, stock.AuPrice, stock.AgPrice,
     stock.PtPrice, stock.PdPrice, stock.AuTotal, stock.AgTotal, stock.PtTotal, stock.PdTotal, stock.AuAmount,
     stock.AgAmount, stock.PtAmount, stock.PdAmount);
     strSql.Append("where UserId=@UserId");
     SqlParameter[] parms = new SqlParameter[] {
         new SqlParameter("@UserId",stock.UserId)
     };
     DbHelper.ExecuteNonQuery(strSql.ToString(), parms, tran.Transaction);
 }
        /// <summary>
        /// 创建回购订单
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="operationEntity"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public static bool CreateBackOrder(OrderEntity entity, OrderOperationEntity operationEntity, string loginId)
        {
            List<DeliverEntity> deliverList = new List<DeliverEntity>();//需要更新的交割单列表
            List<DeliverRecordEntity> deliverRecordList = new List<DeliverRecordEntity>();//交割单记录列表

            StockEntity stockEntity = new StockEntity();
            stockEntity = LoadByAccount(entity.UserId); //用户信息
            #region 赋值

            entity.OrderId = Guid.NewGuid().ToString("n");
            entity.OrderNo = "HG" + DateTime.Now.ToString("yyMMddhhmmssffff");
            entity.OrderCode = "";
            entity.OrderType = (int)OrderType.回购单;
            entity.State = (int)OrderState.新订单;
            entity.CreateDate = DateTime.Now.ToString();
            entity.EndDate = DateTime.Now.AddDays(7).ToString();

            decimal temp = 0;
            if (stockEntity.Au < entity.Au)
            {
                temp = entity.Au - stockEntity.Au;
                entity.AuP = temp * entity.AuP + entity.Au * (entity.AuP - 3);
            }
            if (stockEntity.Ag < entity.Ag)
            {
                temp = entity.Ag - stockEntity.Ag;
                entity.AgP = temp * entity.AgP + entity.Ag * (entity.AgP - 1);
            }

            if (stockEntity.Pt < entity.Pt)
            {
                temp = entity.Pt - stockEntity.Pt;
                entity.PtP = temp * entity.PtP + entity.Pt * (entity.PtP - 3);
            }

            if (stockEntity.Pd < entity.Pd)
            {
                temp = entity.Pd - stockEntity.Pd;
                entity.PdP = temp * entity.PdP + entity.Pd * (entity.PdP - 3);
            }

            entity.AuQuantity = entity.Au * entity.AuP;
            entity.AgQuantity = entity.Ag * entity.AgP;
            entity.PtQuantity = entity.Pt * entity.PtP;
            entity.PdQuantity = entity.Pd * entity.PdP;

            operationEntity.OperationId = Guid.NewGuid().ToString("n");
            operationEntity.OperationDate = DateTime.Now.ToString();
            operationEntity.OrderNo = entity.OrderNo;
            operationEntity.Remark = string.Format("用户:{0} 创建回购订单", entity.Account);
            operationEntity.OrderId = entity.OrderId;
            operationEntity.Account = entity.Account;
            operationEntity.Type = entity.OrderType;

            OrderPriceEntity orderPriceEntity = new OrderPriceEntity();
            orderPriceEntity.OrderId = entity.OrderId;
            orderPriceEntity.OrderNo = entity.OrderNo;
            orderPriceEntity.PriceId = "";
            orderPriceEntity.AuPrice = stockEntity.AuPrice;
            orderPriceEntity.AgPrice = stockEntity.AgPrice;
            orderPriceEntity.PtPrice = stockEntity.PtPrice;
            orderPriceEntity.PdPrice = stockEntity.PdPrice;

            #endregion

            //判断用户是否存在交割单
            List<DeliverEntity> list = GetListByAccount(entity.Account, Direction.提货单, 1);
            if (list == null || list.Count <= 0)
            {
                return false;
            }
            #region 计算交割单信息

            Dictionary<GoodsType, decimal> dic = new Dictionary<GoodsType, decimal>();
            dic.Add(GoodsType.Au, entity.Au);
            dic.Add(GoodsType.Ag, entity.Ag);
            dic.Add(GoodsType.Pd, entity.Pd);
            dic.Add(GoodsType.Pt, entity.Pt);
            foreach (var key in dic.Keys)
            {
                var tmp = list.Where(m => m.Goods.Equals((int)key)).ToList();
                var values = dic[key];
                if (values <= 0) continue;
                foreach (var mm in tmp)
                {
                    DeliverRecordEntity recordEntity = new DeliverRecordEntity
                    {
                        DeliverId = mm.DeliverId,
                        DeliverNo = mm.DeliverNo,
                        Goods = mm.Goods,
                        Direction = mm.Direction,
                        LockPrice = mm.LockPrice,
                        OrderType = (int)OrderType.回购单,
                        OrderId = entity.OrderId,
                        OrderNo = entity.OrderNo
                    };
                    if (values > mm.AvailableTotal)
                    {
                        recordEntity.UseTotal = mm.AvailableTotal;
                        values -= mm.AvailableTotal;
                        mm.AvailableTotal = 0;
                        mm.State = 0;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                    }
                    else
                    {
                        mm.State = values.Equals(mm.AvailableTotal) ? 0 : 1;
                        recordEntity.UseTotal = values;
                        mm.AvailableTotal -= values;
                        deliverList.Add(mm);
                        deliverRecordList.Add(recordEntity);
                        break;
                    }
                }
            }

            #endregion

            UserLogEntity userLogEntity = new UserLogEntity();

            userLogEntity.Account = entity.UserId;
            userLogEntity.DESC = string.Format(@"用户{0}创建回购订单,订单号:{1}", entity.Account, entity.OrderNo);
            userLogEntity.UserType = (int)LogType.创建回购订单;

            YicelTransaction tran = new YicelTransaction();
            try
            {
                tran.BeginTransaction();
                CreateOrder(entity, tran);//创建订单信息
                CreateOrderOperation(operationEntity, tran);//创建回购订单操作记录
                CreatePrice(orderPriceEntity, tran);//创建回购单价格信息
                deliverRecordList.ForEach(m => CreateDeliverRecord(m, tran));//插入交割单记录信息
                deliverList.ForEach(m => UpdateDeliver(m, entity, operationEntity.OperationId, tran));//更新交割单信息
                UpdateUserTotal(entity, stockEntity, tran);//更新用户库存数量
                CreateLog(userLogEntity, tran);
                tran.Commit();
                return true;
            }
            catch
            {
                tran.Rollback();
                return false;
            }
        }