/// <summary>
 /// 新增组织机构
 /// </summary>
 /// <param name="loginId">登录ID</param>
 /// <param name="orgEntity"></param>
 /// <returns></returns>
 public EntityBase AddOrg(string loginId, OrgEntity orgEntity)
 {
     TradeUser TdUser = new TradeUser();
     if (ComFunction.ExistUserLoginID(loginId, ref TdUser) == false)
     {
         return entityBase;
     }
     UserLogEntity userLogEntity = new UserLogEntity();
     userLogEntity.Account = TdUser.Account;
     userLogEntity.DESC = string.Format(@"后台新增组织机构;{0}", orgEntity.OrgName);
     userLogEntity.UserType = (int)TdUser.UType;
     //检测使用组织编码作为默认组织账户时,组织账户是否已经存在
     if(ComFunction.TradeAccountExist(orgEntity.TelePhone))
     {
         entityBase.Result = false;
         entityBase.Desc = string.Format("新增失败,已存在组织账户{0}!", orgEntity.TelePhone);
         return entityBase;
     }
     if (ComFunction.IsExitOrgName(orgEntity.OrgName, orgEntity.TelePhone) >= 1)
     {
         entityBase.Result = false;
         entityBase.Desc = "新增失败,存在相同的机构名称或组织编码!";
         return entityBase;
     }
     if (string.IsNullOrEmpty(orgEntity.ParentOrgId))
     {
         orgEntity.ParentOrgId = "";
         orgEntity.ParentOrgName = "";
     }
     YicelTransaction tran = new YicelTransaction();
     try
     {
         string ipmac = string.Empty;
         if (!string.IsNullOrEmpty(TdUser.Ip))
         {
             ipmac += string.Format("IP={0},", TdUser.Ip);
         }
         if (!string.IsNullOrEmpty(TdUser.Mac))
         {
             ipmac += string.Format("MAC={0},", TdUser.Mac);
         }
         tran.BeginTransaction();
         ComFunction.AddOrg(orgEntity, tran);
         ComFunction.CreateLogEx(userLogEntity,ipmac, tran);
         tran.Commit();
         entityBase.Result = true;
         entityBase.Desc = "组织机构新增成功";
     }
     catch (Exception ex)
     {
         tran.Rollback();
         entityBase.Result = false;
         entityBase.Desc = "组织机构新增失败";
         SetException("组织机构新增失败,原因:", ex);
     }
     return entityBase;
 }
 /// <summary>
 /// 修改组织机构数据
 /// </summary>
 /// <param name="loginId"></param>
 /// <param name="orgEntity"></param>
 /// <returns></returns>
 public EntityBase UpdateOrg(string loginId, OrgEntity orgEntity)
 {
     TradeUser TdUser = new TradeUser();
     if (ComFunction.ExistUserLoginID(loginId, ref TdUser) == false)
     {
         return entityBase;
     }
     UserLogEntity userLogEntity = new UserLogEntity();
     userLogEntity.Account = TdUser.Account;
     userLogEntity.DESC = string.Format(@"后台修改组织机构;{0}", orgEntity.OrgName);
     userLogEntity.UserType = (int)TdUser.UType;
     if (ComFunction.IsExitOrgName(orgEntity.OrgName, orgEntity.TelePhone,orgEntity.OrgID) >= 1)
     {
         entityBase.Result = false;
         entityBase.Desc = "修改失败,存在相同的机构名称或组织编码!";
         return entityBase;
     }
     if (ComFunction.IsExistHuWeiFuzi(orgEntity.OrgID, orgEntity.ParentOrgId)>=1)
     {
         entityBase.Result = false;
         entityBase.Desc = "修改失败,上级组织不能是该组织的下级组织!";
         return entityBase;
     }
     YicelTransaction tran = new YicelTransaction();
     try
     {
         string ipmac = string.Empty;
         if (!string.IsNullOrEmpty(TdUser.Ip))
         {
             ipmac += string.Format("IP={0},", TdUser.Ip);
         }
         if (!string.IsNullOrEmpty(TdUser.Mac))
         {
             ipmac += string.Format("MAC={0},", TdUser.Mac);
         }
         tran.BeginTransaction();
         ComFunction.UpdateOrg(orgEntity, tran);
         ComFunction.UpdateChileOrg(orgEntity, tran);
         ComFunction.CreateLogEx(userLogEntity,ipmac, tran);
         tran.Commit();
         entityBase.Result = true;
         entityBase.Desc = "组织机构修改成功";
     }
     catch (Exception ex)
     {
         tran.Rollback();
         SetException("组织机构修改失败,原因:", ex);
     }
     return entityBase;
 }
 /// <summary>
 /// 删除用户角色
 /// </summary>
 /// <param name="loginId">登录ID</param>
 /// <param name="account"></param>
 /// <returns></returns>
 public EntityBase DeleteUserRole(string loginId, string account)
 {
     TradeUser TdUser = new TradeUser();
     if (ComFunction.ExistUserLoginID(loginId, ref TdUser) == false)
     {
         return entityBase;
     }
     UserLogEntity userLogEntity = new UserLogEntity();
     userLogEntity.Account = TdUser.Account;
     userLogEntity.DESC = string.Format(@"后台删除用户角色;{0}", TdUser.Account);
     userLogEntity.UserType = (int)TdUser.UType;
     YicelTransaction tran = new YicelTransaction();
     try
     {
         string ipmac = string.Empty;
         if (!string.IsNullOrEmpty(TdUser.Ip))
         {
             ipmac += string.Format("IP={0},", TdUser.Ip);
         }
         if (!string.IsNullOrEmpty(TdUser.Mac))
         {
             ipmac += string.Format("MAC={0},", TdUser.Mac);
         }
         tran.BeginTransaction();
         ComFunction.DeleteUserRole(account, tran);
         ComFunction.CreateLogEx(userLogEntity,ipmac, tran);
         tran.Commit();
         entityBase.Result = true;
         entityBase.Desc = "用户角色删除成功";
     }
     catch (Exception ex)
     {
         SetException("用户角色删除失败,原因:", ex);
     }
     return entityBase;
 }
 /// <summary>
 /// 日志记录
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="ipmac"></param>
 /// <param name="tran"></param>
 /// <returns></returns>
 public static int CreateLogEx(UserLogEntity entity,string ipmac, YicelTransaction tran)
 {
     entity.OperTime = DateTime.Now.ToString();
     SqlParameter[] parms = new SqlParameter[] {
          new SqlParameter("@OperTime",entity.OperTime),
         new SqlParameter("@Account",entity.Account),
         new SqlParameter("@Remark",ipmac+entity.DESC),
         new SqlParameter("@UserType",entity.UserType)
     };
     StringBuilder strSql = new StringBuilder();
     strSql.AppendFormat("insert into Base_OperrationLog({0})", Fields.Log_FIELD_List);
     strSql.AppendFormat(" values ({0})", "@" + Fields.Log_FIELD_List.Replace(",", ",@"));
     object obj = DbHelper.ExecuteNonQuery(strSql.ToString(), parms, tran.Transaction);
     return obj == null || obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
 }
        /// <summary>
        /// 后台用户库存入库(库存减少用的)
        /// </summary>
        /// <param name="operationId"></param>
        /// <param name="entity"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public static bool CreateStockDeliverAdmin(string operationId, OrderEntity entity, string loginId)
        {
            List<DeliverEntity> deliverList = new List<DeliverEntity>();//需要更新的交割单列表
            List<DeliverRecordEntity> deliverRecordList = new List<DeliverRecordEntity>();
            List<UpdateDataMember> updateList = new List<UpdateDataMember>();//需要更新的订单信息
            List<UpdateDataMember> userList = new List<UpdateDataMember>();//需要更新用户数量

            StockEntity stockEntity = LoadByAccount(entity.UserId);//获取订单所属用户信息
            entity.OrderType = 13;//默认提货单
            Direction d = Direction.库存调整;

            //获取交割单信息
            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)
                {
                    if (values > mm.AvailableTotal)
                    {
                        values -= mm.AvailableTotal;
                        mm.AvailableTotal = 0;
                        mm.State = 0;
                        deliverList.Add(mm);
                    }
                    else
                    {
                        mm.State = values.Equals(mm.AvailableTotal) ? 0 : 1;
                        mm.AvailableTotal = mm.AvailableTotal + values;
                        if (mm.AvailableTotal == 0)
                        {
                            mm.State = 0;
                        }
                        deliverList.Add(mm);
                        break;
                    }
                }
            }

            #endregion

            List<DeliverAdjustmentEntity> listDeliver = new List<DeliverAdjustmentEntity>();

            DeliverAdjustmentEntity deliver = null;
            if (entity.Au < 0)
            {
                deliver = new DeliverAdjustmentEntity();
                deliver.DeliverAdjustmentID = Guid.NewGuid().ToString("n");
                deliver.DeliverAdjustmentNO = "JS" + DateTime.Now.ToString("yyMMddhhmmssffff");
                deliver.Goods = (int)GoodsType.Au;
                deliver.Direction = (int)OrderType.库存调整;
                deliver.Total = entity.Au;
                deliver.Account = entity.Account;
                deliver.LockPrice = 0;
                deliver.State = 0;
                deliver.AvailableTotal = 0;
                deliver.FromFlag = 1;
                deliver.OperationUserID = operationId;
                deliver.UserID = entity.UserId;
                listDeliver.Add(deliver);
            }
            if (entity.Ag < 0)
            {
                deliver = new DeliverAdjustmentEntity();
                deliver.DeliverAdjustmentID = Guid.NewGuid().ToString("n");
                deliver.DeliverAdjustmentNO = "JS" + DateTime.Now.ToString("yyMMddhhmmssffff");
                deliver.Goods = (int)GoodsType.Ag;
                deliver.Direction = (int)OrderType.库存调整;
                deliver.Total = entity.Ag;
                deliver.Account = entity.Account;
                deliver.LockPrice = 0;
                deliver.State = 0;
                deliver.AvailableTotal = 0;
                deliver.FromFlag = 1;
                deliver.OperationUserID = operationId;
                deliver.UserID = entity.UserId;
                listDeliver.Add(deliver);
            }
            if (entity.Pd < 0)
            {
                deliver = new DeliverAdjustmentEntity();
                deliver.DeliverAdjustmentID = Guid.NewGuid().ToString("n");
                deliver.DeliverAdjustmentNO = "JS" + DateTime.Now.ToString("yyMMddhhmmssffff");
                deliver.Goods = (int)GoodsType.Pd;
                deliver.Direction = (int)OrderType.库存调整;
                deliver.Total = entity.Pd;
                deliver.Account = entity.Account;
                deliver.LockPrice = 0;
                deliver.State = 0;
                deliver.AvailableTotal = 0;
                deliver.FromFlag = 1;
                deliver.OperationUserID = operationId;
                deliver.UserID = entity.UserId;
                listDeliver.Add(deliver);
            }
            if (entity.Pt < 0)
            {
                deliver = new DeliverAdjustmentEntity();
                deliver.DeliverAdjustmentID = Guid.NewGuid().ToString("n");
                deliver.DeliverAdjustmentNO = "JS" + DateTime.Now.ToString("yyMMddhhmmssffff");
                deliver.Goods = (int)GoodsType.Pt;
                deliver.Direction = (int)OrderType.库存调整;
                deliver.Total = entity.Pt;
                deliver.Account = entity.Account;
                deliver.LockPrice = 0;
                deliver.State = 0;
                deliver.AvailableTotal = 0;
                deliver.FromFlag = 1;
                deliver.OperationUserID = operationId;
                deliver.UserID = entity.UserId;
                listDeliver.Add(deliver);
            }

            UserLogEntity userLogEntity = new UserLogEntity();

            userLogEntity.Account = operationId;
            userLogEntity.DESC = string.Format(@"后台用户库存调整(减少):{0}库存,减少.Ag:{1},Au:{2},Pt:{3},Pd:{4};", entity.Account, entity.Au, entity.Ag, entity.Pt, entity.Pd);
            userLogEntity.UserType = (int)LogType.用户库存调整减少;
            YicelTransaction tran = new YicelTransaction();
            try
            {
                tran.BeginTransaction();
                //  CreateOrder(order, tran);//创建订单信息
                deliverList.ForEach(m => UpdateDeliver(m, entity, operationId, tran));//更新交割单信息
                listDeliver.ForEach(m => CreateDeliverAdjustment(m, tran));
                UpdateUserTotal(entity, stockEntity, tran);//更新用户库存数量
                CreateLog(userLogEntity, tran);
                tran.Commit();
                return true;
            }
            catch (Exception ex)
            {
                ManagerLog.WriteErr(ex + ":" + userLogEntity.DESC);
                tran.Rollback();
                return false;
            }
        }
        /// <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="orderNO"></param>
 /// <param name="userId">用户ID</param>
 /// <param name="state"></param>
 /// <returns></returns>
 public static bool UpdateOrderState(string orderNO, string userId, int state)
 {
     UserLogEntity userLogEntity = new UserLogEntity();
     userLogEntity.OperTime = DateTime.Now.ToString();
     // userLogEntity.UserID = userid;
     userLogEntity.DESC = string.Format(@"更新回购订单状态:用户{0},订单号:{1};", userId, orderNO);
     userLogEntity.UserType = (int)LogType.订单修改;
     YicelTransaction tran = new YicelTransaction();
     SqlParameter[] parms = new SqlParameter[] {
     };
     string strSql = string.Format(@"update Order_BZJ set version={0},state={1} ,enddate='{2}' where OrderNo='{3}' and userid='{4}'", 2, state, DateTime.Now.ToString(), orderNO, userId);
     try
     {
         tran.BeginTransaction();
         DbHelper.ExecuteNonQuery(strSql, parms, tran.Transaction);
         CreateLog(userLogEntity, tran);
         tran.Commit();
         return true;
     }
     catch
     {
         tran.Rollback();
         return false;
     }
 }
        /// <summary>
        /// 更新订单状态为已提货或卖
        /// </summary>
        /// <param name="agentId"></param>
        /// <param name="order"></param>
        /// <param name="dataMember"></param>
        /// <param name="operationEntity"></param>
        /// <returns></returns>
        public static bool UpdateOrder(string agentId, OrderEntity order, List<UpdateDataMember> dataMember, OrderOperationEntity operationEntity)
        {
            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.AuPrice });
                            if (Convert.ToDecimal(m.value) > stockEntity.AuAmount)
                            {
                                updateList.Add(new UpdateDataMember { field = "PdQuantity", value = stockEntity.AuAmount });
                            }
                            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(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;
            YicelTransaction tran = new YicelTransaction();
            try
            {
                tran.BeginTransaction();
                UpdateColumns(entity.OrderId, updateList, tran);
                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);//创建金商库存
                CreateLog(userLogEntity, tran);
                tran.Commit();
                return true;
            }
            catch
            {
                tran.Rollback();
                return false;
            }
        }
 /// <summary>
 /// 更新回购订单状态并记录操作日志 
 /// </summary>
 /// <param name="agentId"></param>
 /// <param name="order"></param>
 /// <returns></returns>
 public static bool UpdateBuyBackOrder(string agentId, OrderEntity order)
 {
     UserLogEntity userLogEntity = new UserLogEntity();
     userLogEntity.OperTime = DateTime.Now.ToString();
     userLogEntity.Account = agentId;
     userLogEntity.DESC = string.Format(@"更新回购订单状态:金商{0},订单号:{1}订单ID:{2};", agentId, order.IDNo, order.OrderId);
     userLogEntity.UserType = (int)LogType.金商回购单状态修改;
     YicelTransaction tran = new YicelTransaction();
     SqlParameter[] parms = new SqlParameter[] {
     };
     string strSql = string.Format(@"update Order_BZJ set version={0},state={1} ,OperationDate=GETDATE(),ClerkID='{4}',AgentID='{4}' where OrderNo='{2}' and userid='{3}'", order.Version, order.State, order.OrderNo, order.UserId, agentId);
     try
     {
         tran.BeginTransaction();
         DbHelper.ExecuteNonQuery(strSql, parms, tran.Transaction);
         CreateLog(userLogEntity, tran);
         tran.Commit();
         return true;
     }
     catch
     {
         tran.Rollback();
         return false;
     }
 }
        /// <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;
            }
        }