using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OfficeOpenXml.ConditionalFormatting;
using RFrameGenerate.DAL.SQLServer;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using System.Linq.Expressions;
using RFrameGenerate.BLL.Products;
using RFrameGenerate.Common;
using System.Data;
using System.Net;
using RFrameGenerate.DAL.Enums;
using RFramework.SQLQuery;
using RFrameGenerate.BLL.Logistics;
using RFrameGenerate.BLL.Marketing;
using RFrameGenerate.Model.PageModel;
using System.Data.SqlClient;
using RFrameGenerate.Common.Tools;
using RFrameGenerate.BLL.Recharge;
namespace RFrameGenerate.BLL
{
    public class OrderManage
    {
        /// <summary>
        /// 获取订单列表（分页）
        /// </summary>
        /// <param name="gridModel"></param>
        /// <returns></returns>
        public List<T_ST_OrderList> GetPageList(GridModel gridModel, Guid? merchantguid, string orderState, string memberName, string orderNo, string payNo, string reciever)
        {
            using (var query = Factory.CreateT_ST_OrderList())
            {
                Expression<Func<T_ST_OrderList, bool>> condition = m => m.MemberName.SqlLike(memberName) && m.OrderNo.SqlLike(orderNo) && m.TransactionID.SqlLike(payNo) && m.Reciever.SqlLike(reciever);
                if (merchantguid != null && merchantguid != Guid.Empty)
                {
                    condition = condition.AndAlso(m => m.MerchantGuid == merchantguid);
                }
                if (!string.IsNullOrEmpty(orderState) && orderState != "0")
                {
                    condition = condition.AndAlso(m => m.OrderState == int.Parse(orderState));
                }
                var istop = MerchantManage.IsTop();
                if (!istop)
                {
                    condition = condition.AndAlso(m => m.MerchantGuid == Common.CurrentManage.MerchantGuid);
                }
                else
                {
                    var guids = AgentAuditManage.GetAllSubordinateAgentByMerGuid(CurrentManage.MerchantGuid);
                    guids.Add(Common.CurrentManage.MerchantGuid);
                    condition = condition.AndAlso(m => m.MerchantGuid.SqlIn(guids.Select(c => c.ToString()).ToArray()));
                }

                return query.GetPageList(gridModel, condition, true, a => a.OrderTime, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
            }
        }
        /// <summary>
        /// 根据GUID获取订单
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public T_BAS_Orders GetEntity(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_Orders())
            {
                return query.GetDataByGuid(guid, false);
            }
        }

        public static List<T_BAS_OrderDetails> GetDetailList(Guid orderGuid)
        {
            using (var query = Factory.CreateT_BAS_OrderDetails())
            {
                return query.GetList(a => a.OrderGuid == orderGuid, isFilterMerchant: false);
            }
        }

        public static Result ChangePrice(Guid orderDetailGuid, decimal price)
        {
            return ChangePrice(orderDetailGuid, price, Common.CurrentManage.MerchantGuid);

            //修改订单明细价格、佣金
            decimal previousPrice = 0;
            Guid? distributorguid = null;
            Guid? superiorDistributorGuid = null;
            Guid? topDistributorGuid = null;
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                    var query_product = Factory.CreateT_BAS_Products(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    if (price < 0) return new Result(false, "价格必须大于0！");
                    var orderDetails = query_orderDetails.GetFirstData(a => a.OrderDetailGuid == orderDetailGuid);
                    if (orderDetails == null) return new Result(false, "找不到订单明细！");

                    if (orderDetails.Discount != null && price * orderDetails.Quantity.Value <= orderDetails.Discount.Value) return new Result(false, "修改价格不能小于等于优惠价格！");
                    if (orderDetails.IntegralMoney > 0 && price * orderDetails.Quantity.Value <= (orderDetails.IntegralMoney.Value + (orderDetails.Discount ?? 0))) return new Result(false, string.Format("修改后的总价{0}不能小于等于总优惠价格（{1}）！", (price * orderDetails.Quantity.Value).ToString("N02"), orderDetails.IntegralMoney.Value + (orderDetails.Discount ?? 0)));//

                    previousPrice = orderDetails.Price.Value;//之前的价格
                    var product = query_product.GetFirstData(a => a.ProductGuid == orderDetails.ProductGuid);
                    if (product == null) return new Result(false, "找不到该商品！");
                    var order = query_order.GetFirstData(a => a.OrderGuid == orderDetails.OrderGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid);
                    if (order == null) return new Result(false, "找不到该订单！");

                    if (order.OrderState != DictionaryConst.OrderState.Unpaid) return new Result(false, "订单状态已付款，不能改价！");
                    //修改后的详情总金额
                    orderDetails.Price = price;
                    var newAmount = price * orderDetails.Quantity.Value;
                    orderDetails.Amount = newAmount;

                    orderDetails.WXPayMoney = orderDetails.Amount - (orderDetails.Discount ?? 0);
                    orderDetails.WXPayMoney -= (orderDetails.IntegralMoney ?? 0);//

                    if (order.IsDistribute == true)
                    {
                        distributorguid = order.DistributionPropGuid;
                        superiorDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(order.DistributionPropGuid, order.OrderGuid);
                        topDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(superiorDistributorGuid, order.OrderGuid);

                        decimal first = orderDetails.FirstCommissionSet == null ? 0 : Math.Round(orderDetails.FirstCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);
                        decimal second = orderDetails.SecondCommissionSet == null ? 0 : Math.Round(orderDetails.SecondCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);
                        decimal third = orderDetails.ThirdCommissionSet == null ? 0 : Math.Round(orderDetails.ThirdCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);

                        if (distributorguid != null && distributorguid != Guid.Empty) orderDetails.FirstCommission = first;
                        if (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty) orderDetails.SecondCommission = second;
                        if (topDistributorGuid != null && topDistributorGuid != Guid.Empty) orderDetails.ThirdCommission = third;

                        orderDetails.TotalCommission = (orderDetails.FirstCommission == null ? 0 : orderDetails.FirstCommission.Value) + (orderDetails.SecondCommission == null ? 0 : orderDetails.SecondCommission.Value) + (orderDetails.ThirdCommission == null ? 0 : orderDetails.ThirdCommission);
                    }
                    orderDetails.EntityState = EntityStates.ToBeUpdated;
                    orderDetails.DiscountPrice = 1;

                    query_orderDetails.Update(orderDetails);


                    #region 修改订单表金额
                    var list_orderDetail = query_orderDetails.GetList(a => a.OrderGuid == orderDetails.OrderGuid);
                    var amount = list_orderDetail.Sum(a => a.Amount * (a.DiscountPrice == null || a.DiscountPrice == 0.0m ? 1 : a.DiscountPrice));

                    #region 补充订单积分相关重置（暂定） Bing 151225
                    if (order.PresentExp > 0)
                    {
                        var tempPresentExp = 0;
                        var ruleEntity = new T_INT_IntegralRules()
                        {
                            IntegralEnable = true,
                            ProductAmount = order.InProductAmount,
                            PresentExp = order.InPresentExp
                        };
                        IntegralRulesManage.GetIntegral(amount, ruleEntity, out tempPresentExp);
                        if (tempPresentExp > 0)
                        {
                            order.PresentExp = tempPresentExp;

                            //order.InProductAmount = integralEntity.ProductAmount;
                            //order.InPresentExp = integralEntity.PresentExp;
                            //order.InProportionIntegral = integralEntity.ProportionIntegral;
                        }
                    }
                    #endregion

                    var wxPaymoney = list_orderDetail.Sum(a => a.WXPayMoney) + (order.Freight ?? 0);
                    var totalFirstCommission = list_orderDetail.Sum(a => a.FirstCommission);
                    var totalSecondCommission = list_orderDetail.Sum(a => a.SecondCommission);
                    var totalThirdCommission = list_orderDetail.Sum(a => a.ThirdCommission);
                    var totalCommission = list_orderDetail.Sum(a => a.TotalCommission);

                    if (order.PresentExp > 0)
                    {  //补充包含积分处理
                        query_order.Update(a => new Object[] { a.TotalMoney == amount, a.WXPayMoney == wxPaymoney, a.PresentExp == order.PresentExp }, a => a.OrderGuid == orderDetails.OrderGuid);
                    }
                    else
                    {
                        query_order.Update(a => new Object[] { a.TotalMoney == amount, a.WXPayMoney == wxPaymoney }, a => a.OrderGuid == orderDetails.OrderGuid);
                    }

                    #endregion

                    #region 修改分销订单表佣金
                    query_distribute.Update(a => new Object[]{
                        a.FirstCommission==totalFirstCommission,
                        a.SecondCommission==totalSecondCommission,
                        a.ThirdCommission==totalThirdCommission,
                        a.TotalCommission==totalCommission
                    }, a => a.OrderGuid == order.OrderGuid);
                    #endregion

                    #region 消息模板
                    try
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var member = query_member.GetFirstData(a => a.MemberGuid == order.MemberGuid);
                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.订单改价通知, isFilterMerchant: false);
                        if (template != null && member != null)
                        {
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", string.Format("亲，您的订单{0}，卖家已经将价格由{1}元修改为{2}元，请您确认价格后支付。", order.OrderNo, previousPrice, price));
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("keyword1", order.OrderNo));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword2", orderDetails.ProductName));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword3", string.Format("{0:f}", order.OrderTime)));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword4", string.Format("{0}元", amount)));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword5", DictionaryConst.OrderState.GetText(order.OrderState)));
                            send.remark = new Wechat.Model.TempateKey("remark", "请您尽快支付！");
                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(member.MemberOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "Order/Index", send, CurrentManage.AppId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("SubmitOrder提交订单" + ex.Message + "   " + ex.StackTrace);
                    }
                    #endregion
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        /// <summary>
        /// 改价
        /// </summary>
        /// <param name="orderDetailGuid"></param>
        /// <param name="price"></param>
        /// <param name="merchantguid"></param>
        /// <returns></returns>
        public static Result ChangePrice(Guid orderDetailGuid, decimal price, Guid merchantguid)
        {
            //修改订单明细价格、佣金
            decimal previousPrice = 0;
            Guid? distributorguid = null;
            Guid? superiorDistributorGuid = null;
            Guid? topDistributorGuid = null;
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                    var query_product = Factory.CreateT_BAS_Products(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    if (price < 0) return new Result(false, "价格必须大于0！");
                    var orderDetails = query_orderDetails.GetFirstData(a => a.OrderDetailGuid == orderDetailGuid, isFilterMerchant: false);
                    if (orderDetails == null) return new Result(false, "找不到订单明细！");

                    if (orderDetails.Discount != null && price * orderDetails.Quantity.Value <= orderDetails.Discount.Value) return new Result(false, "修改价格不能小于等于优惠价格！");
                    if (orderDetails.IntegralMoney > 0 && price * orderDetails.Quantity.Value <= (orderDetails.IntegralMoney.Value + (orderDetails.Discount ?? 0))) return new Result(false, string.Format("修改后的总价{0}不能小于等于总优惠价格（{1}）！", (price * orderDetails.Quantity.Value).ToString("N02"), orderDetails.IntegralMoney.Value + (orderDetails.Discount ?? 0)));//

                    previousPrice = orderDetails.Price.Value;//之前的价格
                    var product = query_product.GetFirstData(a => a.ProductGuid == orderDetails.ProductGuid && a.MerchantGuid == merchantguid, isFilterMerchant: false);
                    if (product == null) return new Result(false, "找不到该商品！");

                    var order = query_order.GetFirstData(a => a.OrderGuid == orderDetails.OrderGuid && a.MerchantGuid == merchantguid, isFilterMerchant: false);
                    if (order == null) return new Result(false, "找不到该订单！");
                    if (order.MerchantPayWayGuid != null && order.MerchantPayWayGuid != Guid.Empty)
                        return new Result(false, "已经在微信下单，不能修改价格。请重新下单付款！");

                    if (order.OrderState != DictionaryConst.OrderState.Unpaid) return new Result(false, "订单状态已付款，不能改价！");
                    //修改后的详情总金额
                    orderDetails.Price = price;
                    var newAmount = price * orderDetails.Quantity.Value;
                    orderDetails.Amount = newAmount;

                    orderDetails.WXPayMoney = orderDetails.Amount - (orderDetails.Discount ?? 0);
                    orderDetails.WXPayMoney -= (orderDetails.IntegralMoney ?? 0);//

                    if (order.IsDistribute == true)
                    {
                        distributorguid = order.DistributionPropGuid;
                        superiorDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(merchantguid, order.DistributionPropGuid, order.OrderGuid);
                        topDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(merchantguid, superiorDistributorGuid, order.OrderGuid);

                        decimal first = orderDetails.FirstCommissionSet == null ? 0 : Math.Round(orderDetails.FirstCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);
                        decimal second = orderDetails.SecondCommissionSet == null ? 0 : Math.Round(orderDetails.SecondCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);
                        decimal third = orderDetails.ThirdCommissionSet == null ? 0 : Math.Round(orderDetails.ThirdCommissionSet.Value * (orderDetails.WXPayMoney == null ? 0 : orderDetails.WXPayMoney.Value), 2, MidpointRounding.AwayFromZero);

                        if (distributorguid != null && distributorguid != Guid.Empty) orderDetails.FirstCommission = first;
                        if (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty) orderDetails.SecondCommission = second;
                        if (topDistributorGuid != null && topDistributorGuid != Guid.Empty) orderDetails.ThirdCommission = third;

                        orderDetails.TotalCommission = (orderDetails.FirstCommission == null ? 0 : orderDetails.FirstCommission.Value) + (orderDetails.SecondCommission == null ? 0 : orderDetails.SecondCommission.Value) + (orderDetails.ThirdCommission == null ? 0 : orderDetails.ThirdCommission);
                    }
                    orderDetails.EntityState = EntityStates.ToBeUpdated;
                    orderDetails.DiscountPrice = 1;

                    query_orderDetails.Update(orderDetails, false);


                    #region 修改订单表金额
                    var list_orderDetail = query_orderDetails.GetList(a => a.OrderGuid == orderDetails.OrderGuid, isFilterMerchant: false);
                    var amount = list_orderDetail.Sum(a => a.Amount * (a.DiscountPrice == null || a.DiscountPrice == 0.0m ? 1 : a.DiscountPrice));

                    #region 补充订单积分相关重置（暂定） Bing 151225
                    if (order.PresentExp > 0)
                    {
                        var tempPresentExp = 0;
                        var ruleEntity = new T_INT_IntegralRules()
                        {
                            IntegralEnable = true,
                            ProductAmount = order.InProductAmount,
                            PresentExp = order.InPresentExp
                        };
                        IntegralRulesManage.GetIntegral(amount, ruleEntity, out tempPresentExp);
                        if (tempPresentExp > 0)
                        {
                            order.PresentExp = tempPresentExp;

                            //order.InProductAmount = integralEntity.ProductAmount;
                            //order.InPresentExp = integralEntity.PresentExp;
                            //order.InProportionIntegral = integralEntity.ProportionIntegral;
                        }
                    }
                    #endregion

                    var wxPaymoney = list_orderDetail.Sum(a => a.WXPayMoney) + (order.Freight ?? 0);
                    var totalFirstCommission = list_orderDetail.Sum(a => a.FirstCommission);
                    var totalSecondCommission = list_orderDetail.Sum(a => a.SecondCommission);
                    var totalThirdCommission = list_orderDetail.Sum(a => a.ThirdCommission);
                    var totalCommission = list_orderDetail.Sum(a => a.TotalCommission);

                    if (order.PresentExp > 0)
                    {  //补充包含积分处理//增加过滤 20160116 lij
                        query_order.Update(a => new Object[] { a.TotalMoney == amount, a.WXPayMoney == wxPaymoney, a.PresentExp == order.PresentExp }, a => a.OrderGuid == orderDetails.OrderGuid && a.MerchantGuid == merchantguid, isFilterMerchant: false);
                    }
                    else
                    {
                        query_order.Update(a => new Object[] { a.TotalMoney == amount, a.WXPayMoney == wxPaymoney }, a => a.OrderGuid == orderDetails.OrderGuid && a.MerchantGuid == merchantguid, isFilterMerchant: false);
                    }

                    #endregion

                    #region 修改分销订单表佣金
                    query_distribute.Update(a => new Object[]{
                        a.FirstCommission==totalFirstCommission,
                        a.SecondCommission==totalSecondCommission,
                        a.ThirdCommission==totalThirdCommission,
                        a.TotalCommission==totalCommission
                    }, a => a.OrderGuid == order.OrderGuid, isFilterMerchant: false);
                    #endregion

                    #region 消息模板
                    try
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var query_merchant = Factory.CreateT_BAS_Merchants(tran);
                        var queryWechant = Factory.CreateT_WX_WeChat(tran);
                        var member = query_member.GetFirstData(a => a.MemberGuid == order.MemberGuid && a.MerchantGuid == merchantguid, isFilterMerchant: false);
                        var merchant = query_merchant.GetFirstData(a => a.MerchantGuid == merchantguid, isFilterMerchant: false);
                        var weChant = queryWechant.GetFirstData(a => a.WeChatGuid == merchant.WeChatGuid, isFilterMerchant: false);

                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.订单改价通知, isFilterMerchant: false);
                        if (template != null && member != null)
                        {
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", string.Format("亲，您的订单{0}，卖家已经将价格由{1}元修改为{2}元，请您确认价格后支付。", order.OrderNo, previousPrice, price));
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("keyword1", order.OrderNo));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword2", orderDetails.ProductName));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword3", string.Format("{0:f}", order.OrderTime)));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword4", string.Format("{0}元", amount)));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword5", DictionaryConst.OrderState.GetText(order.OrderState)));
                            send.remark = new Wechat.Model.TempateKey("remark", "请您尽快支付！");
                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(member.MemberOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "Order/Index", send, weChant.appid);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("ChangePrice改价" + ex.Message + "   " + ex.StackTrace);
                    }
                    #endregion
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        public static decimal GetTotalMoney()
        {
            using (var query = Factory.CreateT_BAS_Orders())
            {
                var olist = query.GetList(c => (c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid && c.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid()) &&
                                               (c.OrderState == RFrameGenerate.BLL.DictionaryConst.OrderState.Completed || c.OrderState == RFrameGenerate.BLL.DictionaryConst.OrderState.WaitDelivery || c.OrderState == RFrameGenerate.BLL.DictionaryConst.OrderState.WaitReceipt));

                decimal num = olist.Sum(t => t.TotalMoney.Value);
                return num;
            }
        }

        public static T_BAS_Orders GetEntity(Guid guid, Guid merchantGuid)
        {
            using (var query = Factory.CreateT_BAS_Orders())
            {
                return query.GetFirstData(a => a.OrderGuid == guid && a.MerchantGuid == merchantGuid);
            }
        }

        /// <summary>
        /// 统计首页
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <returns></returns>
        public static List<PT_BAS_Orders_Select> GetStatCountByGuid()
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetStatCountByGuid(RFrameGenerate.Common.CurrentManage.MerchantGuid);
            }
        }
        /// <summary>
        /// 根据Guid更新物流GUID
        /// </summary>
        /// <param name="guid1"></param>
        /// <param name="guid2"></param>
        /// <returns></returns>
        public Result SaveLogistics(Guid entityGuid, Guid logisticsGuid)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Orders())
                {
                    var model = query.GetFirstData(a => a.OrderGuid == entityGuid);
                    if (model == null) return new Result(false, "找不到该订单！");

                    model.LogisticrGuid = logisticsGuid;

                    query.Update(model);

                    return new Result(true);
                }
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        #region 小周
        /// <summary>
        /// 当前会员待付款,待发货,待收货,退换货数据统计
        /// </summary>
        /// <param name="unpaid">待付款</param>
        /// <param name="waitDelivery">待发货</param>
        /// <param name="waitReceipt">待收货</param>
        /// <param name="refunding">退换货</param>
        public static Result GetStateQuantity(out int unpaid, out int waitDelivery, out int waitReceipt, out int refunding)
        {
            try
            {
                refunding = 0;
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateT_BAS_Orders(tran);
                    var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                    unpaid = query.GetCount(a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid() && a.OrderState == DictionaryConst.OrderState.Unpaid);
                    waitDelivery = query.GetCount(a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid() && a.OrderState == DictionaryConst.OrderState.WaitDelivery);
                    waitReceipt = query.GetCount(a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid() && a.OrderState == DictionaryConst.OrderState.WaitReceipt);

                    List<T_BAS_Orders> list = query.GetList(a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                    foreach (T_BAS_Orders item in list)
                    {
                        var list_orderDetail = query_orderDetail.GetList(a => a.OrderGuid == item.OrderGuid);
                        foreach (var subitem in list_orderDetail)
                        {
                            if (subitem.State == DictionaryConst.OrderDetailState.Refunding)
                            {
                                refunding += 1;
                                break;
                            }
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                unpaid = waitDelivery = waitReceipt = refunding = 0;
                return new Result(false, ex.Message);
            }
        }
        /// <summary>
        /// 获取所有订单
        /// </summary>
        /// <returns></returns>
        public static List<OrderList> GetOrderList()
        {
            List<OrderList> list = new List<OrderList>();
            List<PT_BAS_Orders_SelectAll> dblist;
            using (var query = Factory.CreateProcedure())
            {
                dblist = query.GetOrderList(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            }
            foreach (var m in dblist)
            {
                if (m.OrderNo == "16040800071014111210")
                {
                    int i = 0;
                    int a = i;
                }
                //分组
                var model = list.Where(a => a.OrderGuid == m.OrderGuid).FirstOrDefault();
                if (model == null)
                {

                    #region 求总金额
                    var totalMoney = m.TotalMoney;

                    if (m.Freight != null)//运费
                    {
                        totalMoney += m.Freight;
                    }

                    if (m.PrivilegelMoney != null)//优惠金额
                    {
                        totalMoney -= m.PrivilegelMoney;
                    }

                    // 添加积分-抵扣处理 Bing 151219
                    if (m.IntegralMoney > 0)//减积分金额
                    {
                        totalMoney -= m.IntegralMoney;
                        totalMoney = totalMoney <= 0 ? 0M : totalMoney;
                    }
                    #endregion

                    model = new OrderList()
                    {

                        MemberGuid = m.MemberGuid,
                        Details = new List<OrderDetails>() { },
                        OrderGuid = m.OrderGuid,
                        OrderInnerState = m.OrderInnerState,
                        OrderNo = m.OrderNo,
                        OrderState = m.OrderState,
                        OrderTime = m.OrderTime,
                        Amount = totalMoney,
                        Quantity = m.Quantity,
                        LogisticrGuid = m.LogisticrGuid,
                        IsComment = m.IsComment,
                        OrderDetailGuid = m.OrderDetailGuid,
                        DiscountPrice = m.DiscountPrice,

                    };
                    var dp = dblist.FirstOrDefault(v => v.OrderDetailGuid == m.OrderDetailGuid && v.OrderGuid == m.OrderGuid);

                    model.Details.Add(new OrderDetails() { GroupGuid = m.GroupGuid, Price = m.Price, ProductName = m.ProductName, DetailQuantity = m.DetailQuantity, Picture = m.Picture, State = m.State, DetailAmount = m.DetailAmount, SKU = m.SKU, DiscountPrice = (dp == null ? m.DiscountPrice : dp.DiscountPrice) });

                    list.Add(model);

                }
                else
                {
                    var dp = dblist.FirstOrDefault(v => v.OrderDetailGuid == m.OrderDetailGuid && v.OrderGuid == m.OrderGuid);

                    model.Details.Add(new OrderDetails() { GroupGuid = m.GroupGuid, Price = m.Price, ProductName = m.ProductName, DetailQuantity = m.DetailQuantity, Picture = m.Picture, State = m.State, DetailAmount = m.DetailAmount, SKU = m.SKU, DiscountPrice = (dp == null ? m.DiscountPrice : dp.DiscountPrice) });
                }
            }
            return list.OrderByDescending(a => a.OrderTime).ToList();
        }

        /// <summary>
        /// 获取所有退款中、已退款订单
        /// </summary>
        /// <returns></returns>
        public static List<OrderList> GetOrderList(int state)
        {
            List<OrderList> list = new List<OrderList>();
            List<PT_BAS_Orders_SelectAll> dblist;
            using (var query = Factory.CreateProcedure())
            {
                dblist = query.GetOrderList(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            }
            foreach (var m in dblist)
            {
                //分组
                var model = list.Where(a => a.OrderGuid == m.OrderGuid).FirstOrDefault();
                if (model == null)
                {
                    model = new OrderList()
                    {
                        MemberGuid = m.MemberGuid,
                        Details = new List<OrderDetails>() { },
                        OrderGuid = m.OrderGuid,
                        OrderInnerState = m.OrderInnerState,
                        OrderNo = m.OrderNo,
                        OrderState = m.OrderState,
                        OrderTime = m.OrderTime,
                        Amount = m.TotalMoney,
                        Quantity = m.Quantity,
                        LogisticrGuid = m.LogisticrGuid,
                        IsComment = m.IsComment

                    };
                    var dp = dblist.FirstOrDefault(v => v.OrderDetailGuid == m.OrderDetailGuid && v.OrderGuid == m.OrderGuid);

                    model.Details.Add(new OrderDetails() { GroupGuid = m.GroupGuid, Price = m.Price, ProductName = m.ProductName, DetailQuantity = m.DetailQuantity, Picture = m.Picture, State = m.State, DetailAmount = m.DetailAmount, DiscountPrice = (dp == null ? m.DiscountPrice : dp.DiscountPrice) });
                    if (m.State != state)
                    {
                        list.Add(model);
                    }
                }
                else
                {
                    var dp = dblist.FirstOrDefault(v => v.OrderDetailGuid == m.OrderDetailGuid && v.OrderGuid == m.OrderGuid);

                    model.Details.Add(new OrderDetails() { GroupGuid = m.GroupGuid, Price = m.Price, ProductName = m.ProductName, DetailQuantity = m.DetailQuantity, Picture = m.Picture, State = m.State, DetailAmount = m.DetailAmount, DiscountPrice = (dp == null ? m.DiscountPrice : dp.DiscountPrice) });
                }
            }
            return list.OrderByDescending(a => a.OrderTime).ToList();
        }


        /// <summary>
        /// 支付完成后处理订单状态
        /// </summary>
        /// <param name="orderNO">订单编号</param>
        /// <param name="total">金额(单位分)</param>
        /// <returns></returns>
        public static Result PaySuccess(string orderNO, string total, string appid, string openid, string transaction_id, bool isZeroBuy = false)
        {
            var lockitem = Common.LockManage.GetLock(orderNO);
            lock (lockitem)
            {
                try
                {
                    //未记录失败情况
                    decimal totalAmount = decimal.Parse(total) / 100;//实际支付
                    if (totalAmount <= 0 && isZeroBuy != true)
                        return new Result(false, "支付金额不能小于或等于0");

                    using (var tran = new SqlRTransaction())
                    {
                        var qeury = Factory.CreateProcedure(tran);
                        var query_detail = Factory.CreateT_BAS_OrderDetails(tran);

                        var order = qeury.GetOrderNO(orderNO);
                        if (order == null)
                            return new Result(false, "找不到订单" + orderNO);
                        var tempDetail = query_detail.GetFirstData(c => c.OrderGuid == order.OrderGuid, isFilterMerchant: false);
                        var tempProName = "购物";
                        if (tempDetail != null)
                        {
                            tempProName = tempDetail.ProductName;
                        }

                        var payMoneyState = OrderManage.OrderPayMoney(order);
                        if (!payMoneyState.State) return new Result(false, payMoneyState.Msg);

                        if ((payMoneyState.Price) != totalAmount)
                            return new Result(false, "支付金额不对");

                        var query_member = Factory.CreateT_BAS_Member(tran);
                        var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                        var queryInTrade = Factory.CreateT_INT_IntegralTrading(tran);

                        #region 积分尝试扣减验证 Bing 151224
                        var member = query_member.GetFirstData(a => a.MemberGuid == order.MemberGuid);
                        var tempIntegral = (member.Integral ?? 0);
                        if (order.IntegralTe > 0)
                        {
                            tempIntegral -= order.IntegralTe.Value;//必须，更新用
                            if (tempIntegral < 0)
                            {
                                return new Result(false, "用户积分扣减失败");
                            }
                        }
                        #endregion

                        //优惠券更新信息 add by Panwp 
                        if (order.PrivilegeGuid != null)
                        {
                            var query_coupon = Factory.CreateT_SA_ActivityDetail(tran);
                            query_coupon.Update(m => new object[] { m.State == DictionaryConst.CouponsState.Used, m.OrderGuid == order.OrderGuid }, v => v.ActivityDetailGuid == order.PrivilegeGuid, false);
                        }
                        //订单状态改变  add by Panwp
                        if (order.IsVirtual != null && order.IsVirtual.Value && order.NoDelivery != null && order.NoDelivery.Value)
                        {
                            var query_order = Factory.CreateT_BAS_Orders(tran);
                            query_order.Update(a => new Object[]{
                                a.DeliveryTime==DateTime.Now,
                                a.CompletedTime == DateTime.Now,
                                a.PayTime == DateTime.Now,
                                a.PayWay =="微信支付",
                                a.OrderInnerState==DictionaryConst.OrderInnerState.Completed,
                                a.OrderState == DictionaryConst.OrderState.Completed,
                                a.TransactionID == transaction_id
                            }, a => a.OrderNo == orderNO, false);

                            var query_dis = Factory.CreateT_BAS_Distribute(tran);
                            query_dis.Update(m => new object[] { m.CompletionDate == DateTime.Now }, v => v.OrderGuid == order.OrderGuid, false);

                            #region 补充 积分赠送处理（虚拟产品&无需发货&收货，直接完成）-暂不处理 Bing 151224
                            //if (order.PresentExp > 0)
                            //{
                            //    tempIntegral += order.PresentExp.Value; //

                            //    queryInTrade.Add(new T_INT_IntegralTrading()//
                            //    {
                            //        IntegralTradingGuid = Guid.NewGuid(),
                            //        MemberGuid = order.MemberGuid,
                            //        MerchantGuid = order.MerchantGuid,
                            //        TradeIntegral = order.PresentExp,
                            //        IntegralBalance = tempIntegral,
                            //        OrderGuid = order.OrderGuid,
                            //        TradeType = IntegralTradingConst.TradeType.PresentExpType,
                            //        TradeDate = DateTime.Now,
                            //        IntegralTo = IntegralTradingConst.IntegralToDir.Income
                            //    });
                            //}
                            #endregion


                        }
                        else
                        {
                            qeury.UpdateOrder(orderNO,
                               RFrameGenerate.BLL.DictionaryConst.OrderState.WaitDelivery,
                               RFrameGenerate.BLL.DictionaryConst.OrderInnerState.WaitDelivery,
                               DateTime.Now,
                                "微信支付", transaction_id);
                        }

                        #region 添加 积分使用数据处理 Bing 151221

                        // 消费处理
                        if (order.IntegralTe > 0)
                        {
                            queryInTrade.Add(new T_INT_IntegralTrading()
                            {
                                IntegralTradingGuid = Guid.NewGuid(),
                                MemberGuid = order.MemberGuid,
                                MerchantGuid = order.MerchantGuid,
                                TradeIntegral = order.IntegralTe,
                                IntegralBalance = tempIntegral,
                                OrderGuid = order.OrderGuid,
                                TradeType = IntegralTradingConst.TradeType.IntegralTeType,
                                TradeDate = DateTime.Now,
                                IntegralTo = IntegralTradingConst.IntegralToDir.Expend
                            });
                        }
                        // 赠送处理-暂不处理 Bing 151224

                        #endregion

                        if (member != null)
                        {
                            var expenseTotal = member.ExpenseTotal + order.WXPayMoney;
                            var growthValue = member.GrowthValue;
                            var balance = member.Balance;
                            var amount = member.Amount;
                            if (RFrameGenerate.BLL.Member.MemberLevelManage.UsingMemberLevel(member.MerchantGuid ?? Guid.Empty))
                            {
                                growthValue = (member.GrowthValue ?? 0.0m) + order.WXPayMoney;
                            }
                            if (transaction_id == "余额支付")
                            {
                                balance = balance - totalAmount;
                                amount = amount - totalAmount;

                                RechargeRecordManage.AddConsume(order.OrderNo, order.OrderGuid, member.MemberGuid, payMoneyState.Price, amount, balance, tempProName, member.Balance, tran);

                            }
                            query_member.Update(m => new object[] 
                        { 
                            m.Integral == tempIntegral, 
                            m.ExpenseTotal == expenseTotal, 
                            m.GrowthValue == growthValue,
                            m.Balance == balance,
                            m.Amount == amount
                        }, v => v.MemberGuid == member.MemberGuid);
                        }

                        var listDetail = qeury.GetOrderDetails(order.OrderGuid);
                        foreach (var v in listDetail)
                        {
                            var product = qeury.GetProduct(v.ProductGuid.Value);
                            if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockByPay)
                            {

                                //无规格
                                if (v.GroupGuid == null)
                                {
                                    //付款减库存,未并发处理
                                    decimal inventory = product.Inventory - v.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume + v.Quantity.Value;
                                    qeury.UpdateProduct(inventory, saleVolume, product.ProductGuid);
                                }//有规格
                                else
                                {
                                    //付款减库存,未并发处理
                                    decimal inventory = product.Inventory - v.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume + v.Quantity.Value;
                                    qeury.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = query_sku.GetList(a => a.ProductGuid == product.ProductGuid && a.ProductSKUGroupGuid == v.GroupGuid);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var item in listSKU)
                                        {
                                            item.Invenotory = item.Invenotory - v.Quantity;
                                            item.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        query_sku.UpdateList(listSKU);
                                    }

                                }
                            }

                        }

                        #region 模板消息
                        try
                        {
                            var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                            var querywechat = Factory.CreateT_WX_WeChat(tran);
                            var querymerch = Factory.CreateT_BAS_Merchants(tran);
                            //var wechat = querywechat.GetFirstData(a => a.appid == appid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            var merch = querymerch.GetFirstData(a => a.MerchantGuid == order.MerchantGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                            var merchGuid = HeadPay.GetPayMerchantGuid(merch.UserID);
                            var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.购买成功通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            if (template != null)
                            {
                                Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                send.first = new Wechat.Model.TempateKey("first", "您的订单已支付成功，我们开始为您打包商品，准备发货。");
                                send.keys = new List<Wechat.Model.TempateKey>();
                                send.keys.Add(new Wechat.Model.TempateKey("orderID", order.OrderNo));
                                send.keys.Add(new Wechat.Model.TempateKey("keyword1", "点击查看商品明细"));
                                send.keys.Add(new Wechat.Model.TempateKey("keyword2", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                send.keys.Add(new Wechat.Model.TempateKey("keyword3", DateTime.Now.ToString("yyyy-MM-dd")));
                                send.remark = new Wechat.Model.TempateKey("remark", "感谢您对本店的信赖与支持，期待您下次光临！");
                                weixinopen.WeiXinOpenRequest.SendMessageTemplate(openid, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "Order/Index", send, appid);
                            }

                            #region 分销商
                            template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新订单通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            if (template != null)
                            {
                                //分销商模板消息
                                if (order.IsDistribute == true)
                                {
                                    Wechat.Model.SendTempateKey send_distributor = new Wechat.Model.SendTempateKey();
                                    Wechat.Model.SendTempateKey send_supdistributor = new Wechat.Model.SendTempateKey();
                                    Wechat.Model.SendTempateKey send_topdistributor = new Wechat.Model.SendTempateKey();
                                    string OpenID = "";
                                    string supOpenID = "";
                                    string topOpenID = "";

                                    string keyword1 = MerchantManage.GetStoreTitleNotFilter(order.DistributionPropGuid.Value);
                                    string keyword2 = ProductsManage.GetProductsNotFilter(order.OrderGuid);

                                    var distributorGuidMember = DistributionManage.GetPropMemberNotFilter(order.DistributionPropGuid.Value);

                                    var queryDist = Factory.CreateT_BAS_Distribute(tran);
                                    var prop = queryDist.GetFirstData(a => a.OrderGuid == order.OrderGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                                    if (prop != null)
                                    {
                                        var superiorDistributorMember = DistributionManage.GetPropMemberNotFilter(prop.SuperiorDistributorGuid);
                                        var topDistributorMember = DistributionManage.GetPropMemberNotFilter(prop.TopDistributorGuid);
                                        int distributionLevel = 1;
                                        if (superiorDistributorMember != null)
                                        {
                                            distributionLevel++;
                                            if (topDistributorMember != null)
                                                distributionLevel++;
                                        }

                                        switch (distributionLevel)
                                        {

                                            case 1:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;
                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_distributor, appid);
                                                }
                                                break;
                                            case 2:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;

                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_distributor, appid);


                                                    if (superiorDistributorMember != null)
                                                    {
                                                        supOpenID = superiorDistributorMember.MemberOpenID;
                                                        send_supdistributor.first = new Wechat.Model.TempateKey("first", "您的下级分销商有一个新订单，赶紧去看看吧!");
                                                        send_supdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                        send_supdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");

                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(supOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_supdistributor, appid);
                                                    }
                                                }
                                                break;
                                            case 3:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;

                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_distributor, appid);


                                                    if (superiorDistributorMember != null)
                                                    {
                                                        supOpenID = superiorDistributorMember.MemberOpenID;
                                                        send_supdistributor.first = new Wechat.Model.TempateKey("first", "您的下级分销商有一个新订单，赶紧去看看吧!");
                                                        send_supdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                        send_supdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");

                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(supOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_supdistributor, appid);

                                                        if (topDistributorMember != null)
                                                        {
                                                            topOpenID = topDistributorMember.MemberOpenID;
                                                            send_topdistributor.first = new Wechat.Model.TempateKey("first", "您的下下级分销商有一个新订单，赶紧去看看吧!");
                                                            send_topdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "已付款"));
                                                            send_topdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(topOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "DistributionCenter/Index", send_topdistributor, appid);
                                                        }
                                                    }
                                                }

                                                break;
                                        }

                                    }
                                }
                            }
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            Wechat.LogManage.Log("支付完成提交订单出错:" + ex.Message);
                        }
                        #endregion
                    }
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    return new Result(false, ex.Message);
                }
                finally
                {

                    lockitem.IsUser = false;
                }
            }
        }

        /// <summary>
        /// 支付完成后处理订单状态
        /// </summary>
        /// <param name="orderNO">订单编号</param>
        /// <param name="total">金额(单位分)</param>
        /// <returns></returns>
        public static Result PayTest(string orderNO, string total, string appid)
        {
            try
            {
                //未记录失败情况
                decimal totalAmount = decimal.Parse(total) / 100;//实际支付
                if (totalAmount <= 0)
                    return new Result(false, "支付金额不能小于或等于0");

                using (var tran = new SqlRTransaction())
                {
                    var qeury = Factory.CreateProcedure(tran);
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryInTrade = Factory.CreateT_INT_IntegralTrading(tran);

                    var order = qeury.GetOrderNO(orderNO);
                    if (order == null)
                        return new Result(false, "找不到订单" + orderNO);
                    if (order.OrderState != RFrameGenerate.BLL.DictionaryConst.OrderState.Unpaid)
                        return new Result(false, "找不到订单" + orderNO);

                    var payMoneyState = OrderManage.OrderPayMoney(order);
                    if (!payMoneyState.State) return new Result(false, payMoneyState.Msg);

                    if ((payMoneyState.Price) != totalAmount)
                        return new Result(false, "支付金额不对");

                    //优惠券更新信息 add by Panwp 
                    if (order.PrivilegeGuid != null)
                    {
                        var query_coupon = Factory.CreateT_SA_ActivityDetail(tran);
                        query_coupon.Update(m => new object[] { m.State == DictionaryConst.CouponsState.Used, m.OrderGuid == order.OrderGuid }, v => v.ActivityDetailGuid == order.PrivilegeGuid);
                    }

                    //订单状态改变  add by Panwp
                    if (order.IsVirtual != null && order.IsVirtual.Value && order.NoDelivery != null && order.NoDelivery.Value)
                    {
                        qeury.UpdateOrder(orderNO,
                           RFrameGenerate.BLL.DictionaryConst.OrderState.Completed,
                           RFrameGenerate.BLL.DictionaryConst.OrderInnerState.Completed,
                           DateTime.Now,
                           "微信支付", "模拟下单");
                    }
                    else
                    {
                        qeury.UpdateOrder(orderNO,
                           RFrameGenerate.BLL.DictionaryConst.OrderState.WaitDelivery,
                           RFrameGenerate.BLL.DictionaryConst.OrderInnerState.WaitDelivery,
                           DateTime.Now,
                            "微信支付", "模拟下单");
                    }


                    //更新会员累计消费金额
                    var member = query_member.GetFirstData(a => a.MemberGuid == order.MemberGuid);


                    if (member != null)
                    {
                        var expenseTotal = member.ExpenseTotal + order.WXPayMoney;
                        decimal? growthValue = member.GrowthValue;
                        if (RFrameGenerate.BLL.Member.MemberLevelManage.UsingMemberLevel())
                        {
                            growthValue = (member.GrowthValue ?? 0.0m) + order.WXPayMoney;
                        }

                        query_member.Update(m => new object[] { m.ExpenseTotal == expenseTotal, m.GrowthValue == growthValue }, v => v.MemberGuid == member.MemberGuid);
                    }

                    var listDetail = qeury.GetOrderDetails(order.OrderGuid);
                    foreach (var v in listDetail)
                    {
                        var product = qeury.GetProduct(v.ProductGuid.Value);
                        if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockByPay)
                        {//付款减库存,未并发处理
                            if (v.GroupGuid != null)
                            {
                                decimal inventory = product.Inventory - v.Quantity.Value;
                                decimal saleVolume = product.SalesVolume + v.Quantity.Value;
                                qeury.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                var listSKU = querySKU.GetList(a => a.ProductGuid == v.ProductGuid && a.ProductSKUGroupGuid == v.GroupGuid);
                                if (listSKU != null && listSKU.Count > 0)
                                {
                                    foreach (var item in listSKU)
                                    {
                                        item.Invenotory = item.Invenotory - v.Quantity.Value;
                                        item.EntityState = EntityStates.ToBeUpdated;
                                    }
                                    querySKU.UpdateList(listSKU);
                                }
                            }
                            else
                            {
                                decimal inventory = product.Inventory - v.Quantity.Value;
                                decimal saleVolume = product.SalesVolume + v.Quantity.Value;
                                qeury.UpdateProduct(inventory, saleVolume, product.ProductGuid);
                            }
                        }

                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        //暂时屏蔽支付类型的关系
        //public static Result UpdatePayWay(string orderNO)
        //{
        //    try
        //    {
        //        using (var tran = new SqlRTransaction())
        //        {
        //            var qeury = Factory.CreateT_BAS_Orders(tran);
        //            var queryMerchantPay = Factory.CreateT_BAS_MerchantsPayWay(tran);
        //            var payway = queryMerchantPay.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
        //            if (payway == null)
        //                return new Result(false, "支付失败,商家未配置微信支付,请联系商家!");

        //            qeury.Update(a => new object[] { a.MerchantPayWayGuid == payway.MerchantPayWayGuid }, b => b.OrderNo == orderNO);
        //        }
        //        return new Result(true);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new Result(false, ex.Message);
        //    }
        //}

        public static Result UpdateState(Guid orderGuid, int state)//退款的状态暂时未处理,除了退款,其它状态都一样
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    tran.BeginTransaction();
                    var qeury = Factory.CreateT_BAS_Orders(tran);
                    var qeury_produre = Factory.CreateProcedure(tran);
                    var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryInTrade = Factory.CreateT_INT_IntegralTrading(tran);
                    var queryMember = Factory.CreateT_BAS_Member(tran);
                    Expression<Func<T_BAS_Orders, object[]>> valueExpression = null;
                    //取消订单更新商品库存
                    if (state == DictionaryConst.OrderState.BeCancel)
                    {
                        var listDetail = qeury_produre.GetOrderDetails(orderGuid);
                        foreach (var v in listDetail)
                        {
                            var product = qeury_produre.GetProduct(v.ProductGuid.Value);
                            if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockBySingle)
                            {//拍下减库存,未并发处理
                                if (v.GroupGuid != null)
                                {
                                    decimal inventory = product.Inventory + v.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - v.Quantity.Value;
                                    qeury_produre.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = querySKU.GetList(a => a.ProductGuid == v.ProductGuid && a.ProductSKUGroupGuid == v.GroupGuid);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var item in listSKU)
                                        {
                                            item.Invenotory = item.Invenotory + v.Quantity.Value;
                                            item.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        querySKU.UpdateList(listSKU);
                                    }
                                }
                                else
                                {
                                    decimal inventory = product.Inventory + v.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - v.Quantity.Value;
                                    qeury_produre.UpdateProduct(inventory, saleVolume, product.ProductGuid);
                                }
                            }

                        }
                    }
                    if (state != DictionaryConst.OrderState.Refunding && state != DictionaryConst.OrderState.Refunded)
                        valueExpression = a => new object[] { a.OrderState == state, a.OrderInnerState == state, a.CompletedTime == DateTime.Now };


                    if (qeury.IsExist(a => a.OrderGuid == orderGuid && a.IsDistribute == true) == true)
                    {
                        var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                        var entity = query_distribute.GetFirstData(a => a.OrderGuid == orderGuid);
                        entity.CompletionDate = DateTime.Now;
                        query_distribute.Update(entity);
                    }

                    qeury.Update(valueExpression, b => b.OrderGuid == orderGuid);

                    if (state == DictionaryConst.OrderState.Completed)
                    {
                        var queryDistOrder = Factory.CreateT_BAS_Distribute(tran);
                        queryDistOrder.Update(a => new object[] { a.CompletionDate == DateTime.Now }, b => b.OrderGuid == orderGuid);

                    }

                    tran.Commit();
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static List<T_BAS_OrderDetails> GetOrderList(Guid orderGuid)
        {
            using (var query = Factory.CreateT_BAS_OrderDetails())
            {
                return query.GetList(a => a.OrderGuid == orderGuid);
            }
        }

        public static Result DealProduct(ref List<OrderConfirm> list)
        {
            var products = ProductsManage.GetProductList(list);
            foreach (var p in list)
            {
                var product = products.Where(a => a.ProductGuid == p.id && a.IsPutaway == true).FirstOrDefault();
                if (product != null)
                {
                    if (product.IsStandards == true)
                    {
                        p.msg = p.name + "规格已更改,请删除该商品后重新加入购物车！";
                        if (p.groupGuid == null) return new Result(false, p.msg);
                        var listSKU = ProductSKUManage.GetSkuGroupList(p.groupGuid.Value);
                        if (listSKU == null || listSKU.Count == 0) return new Result(false, p.msg);
                        foreach (var item in listSKU)
                        {
                            if (p.id == item.ProductGuid)
                            {
                                p.weight = item.Weight;
                                if (p.price != item.Price)
                                {
                                    p.isprice = true;
                                    break;
                                }
                            }
                            if (p.quantity > item.Invenotory)
                            {
                                p.isinventory = true;
                                p.msg = p.name + "数量不能超过库存量！";
                                break;
                            }

                        }
                        if (p.isprice) return new Result(false, p.msg);

                        if (p.isprice) return new Result(false, p.msg);

                        if (product.Quota > 0 && p.quantity > product.Quota)
                        {//限购
                            p.isinventory = true;
                            p.msg = p.name + "限购" + product.Quota + "个";
                            return new Result(false, p.msg);
                        }
                    }
                    else
                    {
                        p.weight = product.Weight;

                        if (p.price != product.Price)
                        {
                            p.isprice = true;
                            p.msg = p.name + "价格已更改,请删除该商品后重新加入购物车！";
                            return new Result(false, p.msg);
                        }
                        if (p.quantity > product.Inventory)
                        {
                            p.isinventory = true;
                            p.msg = p.name + "数量不能超过库存量！";
                            return new Result(false, p.msg);
                        }

                        if (product.Quota > 0 && p.quantity > product.Quota)
                        {//限购
                            p.isinventory = true;
                            p.msg = p.name + "限购" + product.Quota + "个";
                            return new Result(false, p.msg);
                        }
                        p.isprice = false;
                        p.isinventory = false;

                        p.price = product.Price;
                        p.inventory = product.Inventory;

                    }
                    p.pic = product.ProductImage;
                    p.name = product.ProductName;
                }
                else
                {
                    p.isexpire = true;
                    p.msg = p.name + "已下架!";
                    return new Result(false, p.msg);
                }
            }
            return new Result(true);
        }
        /// <summary>
        /// 下订单
        /// </summary>
        /// <param name="addressGuid">收货地址guid</param>
        /// <param name="list">订单数量</param>
        public static Result SubmitOrder(Guid addressGuid, string remark, Guid? couponsGuid, bool isVirtual, bool hasIntegral, int? IntegralTe, decimal? integralMoney, int? PresentExp, List<OrderConfirm> list, out string orderNo)
        {
            orderNo = GetOrderNO();

            #region 虚拟产品判断
            if (!isVirtual && addressGuid == Guid.Empty)
                return new Result(false, "请先选择收货地址");
            if (isVirtual && list.Count > 1)
                return new Result(false, "虚拟商品不能购买多个不同商品！");
            #endregion

            #region 计算运费
            PriceResult freightState = null;
            if (isVirtual)
            {
                freightState = new PriceResult(true, 0.0m);
            }
            else
            {
                freightState = TemplatesManage.CalculationFreight(list, addressGuid);
            }

            if (!freightState.State)
            {
                return new Result(false, freightState.Msg);
            }
            #endregion

            #region 优惠券检查
            T_ST_MemberCoupons coupon = null;
            if (couponsGuid != null)
            {
                coupon = ActivityDetailManage.GetMemberCoupon(couponsGuid.Value);

                var couponState = ActivityDetailManage.CheckCoupon(coupon);

                if (!couponState.State) return new Result(false, couponState.Msg);
            }
            #endregion

            T_BAS_Products dproduct = null;
            //return new Result(false, "后台升级中,暂停购买!");
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();
                    var queryOrder = Factory.CreateT_BAS_Orders(tran);
                    var queryOrderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                    var queryProduct = Factory.CreateT_BAS_Products(tran);
                    var queryDistribute = Factory.CreateT_BAS_Distribute(tran);
                    var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryFlagshipOrder = Factory.CreateT_BAS_FlagshipOrders(tran);
                    var queryAgentProductDis = Factory.CreateT_BAS_AgentProductDiscountDetail(tran);
                    var queryMer = Factory.CreateT_BAS_MerchantsWithLite(tran);
                    var mer = queryMer.GetFirstData(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                    var strdistributePropGuid = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                    var mlist = DistributionManage.GetStoreInfo();
                    string orderSource = mlist.SotreTitle;


                    decimal freight = 0;//运费
                    var orderGuid = Guid.NewGuid();
                    var isDist = string.IsNullOrEmpty(strdistributePropGuid) == true ? false : true;
                    var totalMoney = list.Sum(a => a.price * a.discountPrice * a.quantity) + freight;

                    var address = Factory.CreateT_BAS_RecieverAddress(tran).GetFirstData(a => a.RecieverAddressGuid == addressGuid);
                    if (!isVirtual && address == null)
                        return new Result(false, "收货地址有错");
                    if (isVirtual)
                    {
                        dproduct = queryProduct.GetDataByGuid(list.First().id);

                        if (dproduct == null) return new Result(false, "不存在商品！");

                        if (dproduct.ProductClassify != 2) return new Result(false, "商品属性已改变，请删除商品后重新下单！");
                    }
                    else
                    {
                        //运费返佣处理 zhou 2016/4/9 只有一个商品才可以零元购
                        if (list.Count == 1)
                        {
                            dproduct = queryProduct.GetDataByGuid(list.First().id);
                        }
                    }

                    #region 分销佣金、分销商等级
                    Guid guid = Guid.NewGuid();
                    Guid? distributorGuid = string.IsNullOrEmpty(strdistributePropGuid) == true ? null : (Guid?)Guid.Parse(strdistributePropGuid);

                    #region 分销商在自己店买东西 佣金计算
                    //如果关闭了分销商购买获得一级佣金
                    if (CurrentManage.IsDistribution == true)
                    {
                        var DistributorRelations = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributorRelations);
                        if (DistributorRelations != null && DistributorRelations.ParameterValue.ToLower() != "true" && distributorGuid == CurrentUser.GetDistributionGuid())
                        {
                            var ordermodel = Factory.CreateT_BAS_DistributionProp(tran).GetFirstData(a => a.DistributionPropGuid == distributorGuid);
                            if (ordermodel != null && ordermodel.ParentDistributionPropGuid != null && ordermodel.ParentDistributionPropGuid != Guid.Empty)
                            {
                                orderSource = DistributionManage.GetHeadStore(ordermodel.ParentDistributionPropGuid.Value);
                                distributorGuid = ordermodel.ParentDistributionPropGuid;
                            }
                            else
                            {
                                orderSource = "总部";
                                distributorGuid = null;
                                isDist = false;
                            }
                        }
                    }
                    #endregion

                    Guid? superiorDistributorGuid = null;
                    Guid? topDistributorGuid = null;
                    int distributionLevel = 0;
                    decimal firstCommissionSet = 0;
                    decimal secondCommissionSet = 0;
                    decimal thirdCommissionSet = 0;
                    decimal temp1 = 0;
                    decimal temp2 = 0;
                    decimal temp3 = 0;
                    if (isDist == true)
                    {
                        superiorDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(distributorGuid, orderGuid);
                        topDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(superiorDistributorGuid, orderGuid);

                        if (superiorDistributorGuid == Guid.Empty)
                        {
                            superiorDistributorGuid = null;
                            Wechat.LogManage.Log("下单时,上级为空,distributorGuid:" + distributorGuid);
                        }
                        if (topDistributorGuid == Guid.Empty)
                        {
                            topDistributorGuid = null;
                            Wechat.LogManage.Log("下单时,上级为空,distributorGuid:" + distributorGuid + ",superiorDistributorGuid:" + superiorDistributorGuid);
                        }

                        if ((distributorGuid == null || distributorGuid == Guid.Empty) && (superiorDistributorGuid == null || superiorDistributorGuid == Guid.Empty) && (topDistributorGuid == null || topDistributorGuid == Guid.Empty))
                        {
                            distributionLevel = 0;
                        }
                        if ((distributorGuid != null && distributorGuid != Guid.Empty) && (superiorDistributorGuid == null || superiorDistributorGuid == Guid.Empty) && (topDistributorGuid == null || topDistributorGuid == Guid.Empty))
                        {
                            distributionLevel = 1;
                        }
                        if ((distributorGuid != null && distributorGuid != Guid.Empty) && (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty) && (topDistributorGuid == null || topDistributorGuid == Guid.Empty))
                        {
                            distributionLevel = 2;
                        }
                        if ((distributorGuid != null && distributorGuid != Guid.Empty) && (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty) && (topDistributorGuid != null && topDistributorGuid != Guid.Empty))
                        {
                            distributionLevel = 3;
                        }
                    }
                    #endregion

                    #region 订单
                    var order = new T_BAS_Orders()
                    {
                        OrderGuid = orderGuid,
                        MemberGuid = CurrentUser.GetCurrUserGuid(),
                        MerchantGuid = CurrentManage.MerchantGuid,
                        Quantity = list.Sum(a => a.quantity),
                        TotalMoney = totalMoney,//
                        Remark = remark,
                        RecieverAddressGuid = addressGuid,
                        RecieverAddressInfo = isVirtual ? "虚拟商品，无需地址" : string.Format("收货人:{0},手机:{1},{2}{3}{4}{5}", address.Reciever, address.Telephone, address.Province, address.City, address.Area, address.Address),
                        OrderNo = orderNo,
                        LogisticrGuid = null,
                        IsExtendReceiving = false,//是否延长收货
                        ExtendDay = 0,//延长天数
                        IsComment = false,
                        IsDistribute = isDist,//是否是分销订单
                        OrderInnerState = DictionaryConst.OrderInnerState.Unpaid,
                        OrderState = DictionaryConst.OrderState.Unpaid,
                        OrderSource = orderSource,//来源
                        OrderTime = DateTime.Now,
                        DistributionPropGuid = distributorGuid,
                        Freight = freightState.Price,
                        PrivilegelMoney = 0.0m,
                        //LogisticrGuid = null,//物流
                        //DeliveryTime = DateTime.Now,//发货时间
                        //IsExtendReceiving = false,//是否延长收货
                        //ExtendDay = 0,//延长天数
                        //PayNO = "",//支付单号
                        //PayTime = DateTime.Now,//支付时间
                        //PayWay = "",//支付方式
                        IsVirtual = isVirtual,
                        NoDelivery = (dproduct == null ? false : dproduct.NoDelivery == true ? true : false),
                        NoReceive = (dproduct == null ? false : dproduct.NoReceive == true ? true : false),
                    };
                    if (dproduct != null)
                    {
                        order.ProductClassify = dproduct.ProductClassify;
                        if (dproduct.ProductClassify == 3)//零元购返佣
                        {
                            if (distributorGuid != null && distributorGuid != Guid.Empty)
                            {
                                order.FreightFirstCom = dproduct.FirstCommission;
                            }
                            else
                            {
                                order.FreightFirstCom = 0;
                            }

                            if (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty)
                            {
                                order.FreightSecondCom = dproduct.SecondCommission;
                            }
                            else
                            {
                                order.FreightSecondCom = 0;
                            }

                            if (topDistributorGuid != null && topDistributorGuid != Guid.Empty)
                            {
                                order.FreightThirdCom = dproduct.ThirdCommission;
                            }
                            else
                            {
                                order.FreightThirdCom = 0;
                            }
                        }
                    }

                    if (isVirtual)
                    {
                        order.DeliveryTime = DateTime.Now;
                    }
                    //add by Panwp 2015-11-03 添加优惠券信息
                    order.WXPayMoney = (order.TotalMoney + order.Freight);
                    if (coupon != null)
                    {
                        order.PrivilegelMoney = coupon.Amount;
                        order.Privilege = DictionaryConst.PrivilegeType.Coupons;
                        order.PrivilegeGuid = coupon.ActivityDetailGuid;

                        order.WXPayMoney = order.WXPayMoney - coupon.Amount;
                    }

                    #endregion

                    #region 添加订单积分相关验证 Bing 151219

                    var integralEntity = IntegralRulesManage.GetIntegralRuleByMerchant(Common.CurrentManage.MerchantGuid, tran);

                    //赠送积分判断/验证/(无增加)
                    if (PresentExp > 0)
                    {
                        var reVal1 = IntegralRulesManage.ValidateIntegral(list.Sum(a => a.price * a.quantity), PresentExp, integralEntity);
                        if (!reVal1.State)
                        {
                            return reVal1;
                        }
                    }

                    //使用积分数据判断/验证(当前)
                    if (hasIntegral)
                    {
                        var _totalIntegral = IntegralRulesManage.GetMemberIntegral(CurrentUser.GetCurrUserGuid());
                        var reVal2 = IntegralRulesManage.ValidateIntegraltranData((order.TotalMoney).Value, _totalIntegral, IntegralTe.Value, integralMoney.Value, integralEntity);
                        if (!reVal2.State)
                        {
                            return reVal2;
                        }
                    }

                    #endregion

                    #region 添加订单积分相关赠送/使用数据 Bing 151219

                    if (PresentExp > 0)
                    {
                        order.PresentExp = PresentExp;

                        order.InProductAmount = integralEntity.ProductAmount;
                        order.InPresentExp = integralEntity.PresentExp;
                        order.InProportionIntegral = integralEntity.ProportionIntegral;
                    }
                    if (hasIntegral)
                    {
                        order.IntegralTe = IntegralTe;
                        order.IntegralMoney = integralMoney;

                        order.InProductAmount = integralEntity.ProductAmount;
                        order.InPresentExp = integralEntity.PresentExp;
                        order.InProportionIntegral = integralEntity.ProportionIntegral;

                        order.WXPayMoney -= integralMoney;
                        //order.WXPayMoney = order.WXPayMoney <= 0 ? 0.10M : order.WXPayMoney.Value;
                        if (order.WXPayMoney <= 0)
                        {
                            order.WXPayMoney = 0;
                            //return new Result(false, "非法操作，请重新下单");
                        }
                    }

                    #endregion

                    #region 添加代理商旗舰订单 Bing 160226

                    if ((!MerchantManage.IsTopTeByMer(order.MerchantGuid.Value)))
                    {
                        var agentRule = AgentRulesManage.GetUnifyFlagshipParaByMer(order.MerchantGuid.Value);
                        //if (!(agentRule.AgentComType == AgentRuleConst.AgentComType.无分红))
                        //{
                        queryFlagshipOrder.Add(new T_BAS_FlagshipOrders()
                        {
                            FlagshipOrdersGuid = Guid.NewGuid(),
                            OrderGuid = order.OrderGuid,
                            UserWeChatType = agentRule.UserWeChatType,
                            GoodsDeliveryType = agentRule.GoodsDeliveryType,
                            CommodityRefundAudit = agentRule.CommodityRefundAudit,
                            AgentComType = agentRule.AgentComType,
                            AgentComRatio = agentRule.AgentComRatio,
                        });
                        //}
                    }

                    #endregion

                    #region 订单明细
                    List<T_BAS_OrderDetails> listDetaList = new List<T_BAS_OrderDetails>();
                    foreach (var d in list)
                    {
                        var product = queryProduct.GetFirstData(a => a.ProductGuid == d.id && a.MerchantGuid == CurrentManage.MerchantGuid);
                        if (product != null && product.IsDefault != null)
                        {
                            if (product.IsDefault == false)
                            {
                                temp1 = product.FirstCommission == null ? 0 : product.FirstCommission.Value;
                                temp2 = product.SecondCommission == null ? 0 : product.SecondCommission.Value;
                                temp3 = product.ThirdCommission == null ? 0 : product.ThirdCommission.Value;
                            }
                            else
                            {
                                temp1 = (ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.FirstCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.FirstCommission))) / 100;
                                temp2 = (ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.SecondCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.SecondCommission))) / 100;
                                temp3 = (ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.ThirdCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(CurrentManage.MerchantGuid, ParameterName.CommissionMember.ThirdCommission))) / 100;
                            }

                            if (distributorGuid != null && distributorGuid != Guid.Empty)
                            {
                                firstCommissionSet = temp1;
                            }
                            else
                            {
                                firstCommissionSet = temp1 = 0;
                            }

                            if (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty)
                            {
                                secondCommissionSet = temp2;
                            }
                            else
                            {
                                secondCommissionSet = temp2 = 0;
                            }

                            if (topDistributorGuid != null && topDistributorGuid != Guid.Empty)
                            {
                                thirdCommissionSet = temp3;
                            }
                            else
                            {
                                thirdCommissionSet = temp3 = 0;
                            }
                        }
                        var groupGuid = d.groupGuid;
                        //补充代理折扣数据 Bing 160329
                        decimal? tempAgentDis = 100m;
                        decimal? tempAgentPrice = product.AgentPrice;
                        decimal price = 0m;
                        string sku = "";
                        if (mer != null && (!MerchantManage.IsMar()))
                        {
                            var agentDis = queryAgentProductDis.GetFirstData(c => c.ProductGuid == product.OriginalProductGuid && c.FlagshipGroupGuid == mer.FlagshipGroupGuid.Value && c.AgentProductDiscountGuid == mer.AgentProductDiscountGuid, true, isFilterMerchant: false);
                            if (agentDis != null)
                            {
                                tempAgentDis = (agentDis.Discount ?? 100M);

                            }
                        }
                        if (groupGuid != null)
                        {
                            //price = ProductSKUManage.GetPrice(groupGuid.Value);
                            var skuEn = querySKU.GetFirstData(c => c.ProductSKUGroupGuid == groupGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                            price = skuEn.Price;
                            tempAgentPrice = skuEn.AgentPrice;

                            sku = ProductSKUManage.GetSkuGroup(groupGuid.Value);
                        }
                        else
                        {
                            price = product.Price;
                        }
                        decimal firstCommission = Math.Round(d.quantity * price * d.discountPrice * firstCommissionSet, 2, MidpointRounding.AwayFromZero);
                        decimal secondCommission = Math.Round(d.quantity * price * d.discountPrice * secondCommissionSet, 2, MidpointRounding.AwayFromZero);
                        decimal thirdCommission = Math.Round(d.quantity * price * d.discountPrice * thirdCommissionSet, 2, MidpointRounding.AwayFromZero);
                        decimal totalCommission = firstCommission + secondCommission + thirdCommission;


                        T_BAS_OrderDetails orderDetail = new T_BAS_OrderDetails()
                        {
                            OrderDetailGuid = Guid.NewGuid(),
                            GroupGuid = d.groupGuid,
                            SKU = sku,
                            Amount = d.quantity * price,
                            Discount = 0,
                            DiscountPrice = d.discountPrice,
                            OrderGuid = order.OrderGuid,
                            DistributeGuid = guid,
                            FirstCommission = firstCommission,
                            SecondCommission = secondCommission,
                            ThirdCommission = thirdCommission,
                            TotalCommission = totalCommission,
                            FirstCommissionSet = temp1,
                            SecondCommissionSet = temp2,
                            ThirdCommissionSet = temp3,
                            Picture = d.pic,
                            Price = price,
                            ProductCategoryGuid = product.ProductCategoryGuid,
                            ProductCode = product.ProductCode,
                            ProductGuid = product.ProductGuid,
                            ProductName = product.ProductName,
                            Quantity = d.quantity,
                            SaleProp = "",
                            ProductProp = "",
                            AgentPrice = tempAgentPrice,
                            AgentDiscount = tempAgentDis,
                            State = DictionaryConst.OrderDetailState.Null,
                            EntityState = EntityStates.ToBeAdd,


                        };

                        if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockBySingle)
                        {//拍下减库存,未并发处理
                            //无规格
                            if (d.groupGuid == null)
                            {
                                var inventory = product.Inventory - d.quantity;
                                var saleVolume = product.SalesVolume + d.quantity;
                                queryProduct.Update(a => new object[] { a.Inventory == inventory, a.SalesVolume == saleVolume }, b => b.ProductGuid == product.ProductGuid);
                            }//有规格
                            else
                            {
                                var inventory = product.Inventory - d.quantity;
                                var saleVolume = product.SalesVolume + d.quantity;
                                queryProduct.Update(a => new object[] { a.Inventory == inventory, a.SalesVolume == saleVolume }, b => b.ProductGuid == product.ProductGuid);


                                var listSKU = querySKU.GetList(a => a.ProductGuid == product.ProductGuid && a.ProductSKUGroupGuid == d.groupGuid);
                                if (listSKU != null && listSKU.Count > 0)
                                {
                                    foreach (var item in listSKU)
                                    {
                                        orderDetail.ProductCode = item.Code;
                                        item.Invenotory = item.Invenotory - d.quantity;
                                        item.EntityState = EntityStates.ToBeUpdated;
                                    }
                                    querySKU.UpdateList(listSKU);
                                }
                            }
                        }
                        else
                        {
                            if (d.groupGuid != null)
                            {
                                var listSKU = querySKU.GetList(a => a.ProductGuid == product.ProductGuid && a.ProductSKUGroupGuid == d.groupGuid);
                                if (listSKU != null && listSKU.Count > 0)
                                {
                                    orderDetail.ProductCode = listSKU[0].Code;
                                }
                            }
                        }
                        listDetaList.Add(orderDetail);
                    }

                    #region 店铺预存额合法验证 Bing 160326
                    if (mer != null && mer.PaymentType == AgentProductDiscountConst.PaymentType.预存)
                    {
                        var currAgentAvailableBalance = AgentAccountManage.GetAgentAccount(Common.CurrentManage.MerchantGuid);
                        var currProMoney = listDetaList.Sum(a => a.AgentPrice * a.Quantity);
                        if (currProMoney > currAgentAvailableBalance)
                        {
                            return new Result(false, "店铺当前无法下单");//待定
                        }
                    }
                    #endregion


                    //add by panwp 20151127

                    var couponSum = order.PrivilegelMoney;
                    //int basePresentExp = 0;
                    decimal baseIntegralMoney = 0;
                    //int baseIntegralTe = 0;
                    var sum = listDetaList.Sum(m => m.Amount);

                    for (int i = 0; i < listDetaList.Count; i++)
                    {
                        var item = listDetaList[i];

                        item.WXPayMoney = item.Amount * item.DiscountPrice;

                        if (coupon != null)
                        {
                            if (i != list.Count - 1)
                            {
                                item.Discount = decimal.Round(((item.Amount / sum) * coupon.Amount).Value, 2);
                                couponSum -= item.Discount;
                            }
                            else
                            {
                                item.Discount = couponSum;
                            }
                            item.WXPayMoney = item.WXPayMoney - item.Discount;
                            //修改佣金
                            item.FirstCommission = Math.Round(item.WXPayMoney.Value * item.FirstCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.SecondCommission = Math.Round(item.WXPayMoney.Value * item.SecondCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.ThirdCommission = Math.Round(item.WXPayMoney.Value * item.ThirdCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.TotalCommission = item.FirstCommission + item.SecondCommission + item.ThirdCommission;
                        }

                        #region 添加详情积分赠送处理 Bing 151219- 暂不处理
                        if (PresentExp != 0)
                        {
                            //if (i != list.Count - 1)
                            //{
                            //    item.PresentExp = (int)(Math.Floor(((item.Amount / sum) * PresentExp).Value));
                            //    basePresentExp += item.PresentExp.Value;
                            //}
                            //else
                            //{
                            //    item.PresentExp = PresentExp.Value - basePresentExp;
                            //}


                            //if (list.Count > 1)
                            //{
                            //    IntegralRulesManage.GetIntegralChild(item.Amount, integralEntity, out itemIntegral);
                            //}
                            //else
                            //{
                            //    IntegralRulesManage.GetIntegral(item.Amount, integralEntity, out itemIntegral);
                            //}

                            //var itemIntegral = 0;
                            //IntegralRulesManage.GetIntegral(item.Amount, integralEntity, out itemIntegral);
                            //item.PresentExp = itemIntegral;

                        }
                        #endregion

                        #region 添加详情积分使用数据相关处理 Bing 151219
                        if (hasIntegral)
                        {
                            if (i != list.Count - 1)
                            {
                                item.IntegralMoney = ((item.Amount / sum) * integralMoney).Value;
                                item.IntegralMoney = item.IntegralMoney.ToString().LastIndexOf(".") != -1 && (item.IntegralMoney.ToString().Length - item.IntegralMoney.ToString().LastIndexOf(".") > 3) ? Convert.ToDecimal(item.IntegralMoney.ToString().Substring(0, item.IntegralMoney.ToString().LastIndexOf(".") + 3)) : item.IntegralMoney;
                                baseIntegralMoney += item.IntegralMoney.Value;
                            }
                            else
                            {
                                item.IntegralMoney = integralMoney.Value - baseIntegralMoney;
                            }
                            item.IntegralTe = (int)(item.IntegralMoney.Value * integralEntity.ProportionIntegral.Value);

                            //修正对应微信付款金额
                            item.WXPayMoney -= item.IntegralMoney;
                            //item.WXPayMoney = item.WXPayMoney <= 0 ? 0.10M : item.WXPayMoney.Value;
                            item.WXPayMoney = item.WXPayMoney <= 0 ? 0 : item.WXPayMoney.Value;//暂定
                            Wechat.LogManage.Log(string.Format("SubmitOrder_hasIntegral_WarnRecord:{0}|{1}", order.OrderGuid, item.OrderDetailGuid));

                            //修改对应佣金
                            item.FirstCommission = Math.Round(item.WXPayMoney.Value * item.FirstCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.SecondCommission = Math.Round(item.WXPayMoney.Value * item.SecondCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.ThirdCommission = Math.Round(item.WXPayMoney.Value * item.ThirdCommissionSet.Value, 2, MidpointRounding.AwayFromZero);
                            item.TotalCommission = item.FirstCommission + item.SecondCommission + item.ThirdCommission;

                        }
                        #endregion
                    }
                    #endregion

                    T_BAS_Distribute distribute = null;
                    bool isDistribute = (bool)order.IsDistribute;
                    queryOrder.Add(order);
                    queryOrderDetail.AddList(listDetaList);

                    #region 分销订单
                    if (isDistribute)
                    {
                        //

                        //订单结算后更细分销会员属性分销金额、分销佣金
                        if (order.IsDistribute == true)
                        {
                            distribute = new T_BAS_Distribute()
                            {
                                DistributeGuid = guid,
                                OrderGuid = order.OrderGuid,
                                DistributionPropGuid = order.DistributionPropGuid,
                                SuperiorDistributorGuid = superiorDistributorGuid,
                                TopDistributorGuid = topDistributorGuid,
                                DistributionLevel = distributionLevel,
                                FirstCommission = listDetaList.Sum(a => a.FirstCommission),
                                SecondCommission = listDetaList.Sum(a => a.SecondCommission),
                                ThirdCommission = listDetaList.Sum(a => a.ThirdCommission),
                                TotalCommission = listDetaList.Sum(a => a.TotalCommission),
                                IsSettlement = false,
                                MerchantGuid = order.MerchantGuid
                            };

                        }
                        queryDistribute.Add(distribute);
                    }
                    #endregion

                    #region 模板消息
                    try
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.订单提交成功, isFilterMerchant: false);
                        if (template != null)
                        {
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", "亲，您的订单已经提交成功，请及时付款，别错过哦。");
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("orderID", order.OrderNo));
                            send.keys.Add(new Wechat.Model.TempateKey("orderMoneySum", order.WXPayMoney.Value.ToString("0.00") + "元"));
                            send.remark = new Wechat.Model.TempateKey("remark", "如您在支付中遇到问题，请联系我们的客服，协助您处理！");
                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenIDManage.GetOpenID(), template.TemplateID, CurrentManage.CurrentDomainWx + "Order/Index", send, CurrentManage.AppId);

                            template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新订单通知, isFilterMerchant: false);
                            if (template != null)
                            {
                                //分销商模板消息
                                if (isDistribute)
                                {

                                    var template_distributor = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新订单通知, isFilterMerchant: false);
                                    if (template_distributor != null)
                                    {
                                        Wechat.Model.SendTempateKey send_distributor = new Wechat.Model.SendTempateKey();
                                        Wechat.Model.SendTempateKey send_supdistributor = new Wechat.Model.SendTempateKey();
                                        Wechat.Model.SendTempateKey send_topdistributor = new Wechat.Model.SendTempateKey();
                                        string OpenID = "";
                                        string supOpenID = "";
                                        string topOpenID = "";

                                        string keyword1 = MerchantManage.GetStoreTitle(distributorGuid.Value);
                                        string keyword2 = ProductsManage.GetProducts(orderGuid);

                                        var distributorGuidMember = DistributionManage.GetPropMember(distributorGuid);
                                        var superiorDistributorMember = DistributionManage.GetPropMember(superiorDistributorGuid);
                                        var topDistributorMember = DistributionManage.GetPropMember(topDistributorGuid);

                                        switch (distributionLevel)
                                        {

                                            case 1:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;
                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_distributor, CurrentManage.AppId);
                                                }
                                                break;
                                            case 2:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;

                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_distributor, CurrentManage.AppId);


                                                    if (superiorDistributorMember != null)
                                                    {
                                                        supOpenID = superiorDistributorMember.MemberOpenID;
                                                        send_supdistributor.first = new Wechat.Model.TempateKey("first", "您的下级分销商有一个新订单，赶紧去看看吧!");
                                                        send_supdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                        send_supdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");

                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(supOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_supdistributor, CurrentManage.AppId);
                                                    }
                                                }
                                                break;
                                            case 3:
                                                if (distributorGuidMember != null)
                                                {
                                                    OpenID = distributorGuidMember.MemberOpenID;

                                                    send_distributor.first = new Wechat.Model.TempateKey("first", "您的店铺有一个新订单，赶紧去看看吧!");
                                                    send_distributor.keys = new List<Wechat.Model.TempateKey>();
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                    send_distributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                    send_distributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_distributor, CurrentManage.AppId);


                                                    if (superiorDistributorMember != null)
                                                    {
                                                        supOpenID = superiorDistributorMember.MemberOpenID;
                                                        send_supdistributor.first = new Wechat.Model.TempateKey("first", "您的下级分销商有一个新订单，赶紧去看看吧!");
                                                        send_supdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                        send_supdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                        send_supdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");

                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(supOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_supdistributor, CurrentManage.AppId);

                                                        if (topDistributorMember != null)
                                                        {
                                                            topOpenID = topDistributorMember.MemberOpenID;
                                                            send_topdistributor.first = new Wechat.Model.TempateKey("first", "您的下下级分销商有一个新订单，赶紧去看看吧!");
                                                            send_topdistributor.keys = new List<Wechat.Model.TempateKey>();
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword1", keyword1));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword2", keyword2));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword3", order.OrderTime.ToString("yyyy/MM/dd HH:mm:ss")));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword4", order.WXPayMoney.Value.ToString("0.00") + "元"));
                                                            send_topdistributor.keys.Add(new Wechat.Model.TempateKey("keyword5", "未付款"));
                                                            send_topdistributor.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(topOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send_topdistributor, CurrentManage.AppId);
                                                        }
                                                    }
                                                }

                                                break;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("SubmitOrder提交订单" + ex.Message + "   " + ex.StackTrace);
                    }
                    #endregion

                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }

        public static string GetOrderNO()
        {
            int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
            DateTime dt = DateTime.Now;
            string strid = string.Format("{0:D4}", id);

            if (strid.Length > 4)
                throw new Exception("现在下单人数较多,请稍候再试.");

            string no = dt.ToString("yyMMdd#4ffff#3HH#2mm#1ss");//20
            no = no.Replace("#1", strid[strid.Length - 1].ToString());
            no = no.Replace("#2", strid[strid.Length - 2].ToString());
            no = no.Replace("#3", strid[strid.Length - 3].ToString());
            no = no.Replace("#4", strid[strid.Length - 4].ToString());
            System.Threading.Thread.Sleep(10);
            return no;
        }

        public static T_BAS_Orders GetOrderByNo(string orderNo)
        {
            using (var query = Factory.CreateT_BAS_Orders())
            {
                //return query.GetFirstData(a => a.OrderNo == orderNo,false,null,OrderMethods.Default,RFramework.SQLServer.Enums.LockType.Default,false);
                return query.GetFirstData(a => a.OrderNo == orderNo, isFilterMerchant: false);
            }
        }

        public static PT_BAS_PayWayByOrderNo GetPayWayByOrderNO(string orderNO)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetPayWayByOrderNO(orderNO);
            }
        }

        #endregion

        public static Result SaveRemark(Guid? entityGuid, string remark, Guid merchantGuid)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Orders())
                {
                    var model = query.GetFirstData(a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model == null) return new Result(false, "该数据不存在！");
                    model.Remark = remark;

                    query.Update(model, false);

                    return new Result(true);
                }
            }
            catch (Exception err)
            {

                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 付款
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public static Result Action_Paid(Guid entityGuid, Guid? merchantGuid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var curMerchantGuid = (merchantGuid == null || merchantGuid == Guid.Empty) ? Common.CurrentManage.MerchantGuid : merchantGuid;
                    var query = Factory.CreateProcedure(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == entityGuid && a.MerchantGuid == curMerchantGuid, isFilterMerchant: false);
                    if (model_order == null)
                        return new Result(false, "找不到该订单！");

                    if (model_order.IsVirtual != null && model_order.IsVirtual.Value && model_order.NoDelivery != null && model_order.NoDelivery.Value)
                    {
                        query_order.Update(a => new Object[]{
                                a.DeliveryTime==DateTime.Now,
                                a.CompletedTime == DateTime.Now,
                                a.PayTime == DateTime.Now,
                                a.PayWay =="其他支付",
                                a.OrderInnerState==DictionaryConst.OrderInnerState.Completed,
                                a.OrderState == DictionaryConst.OrderState.Completed,
                                a.TransactionID == "商家支付",
                            }, a => a.OrderGuid == model_order.OrderGuid);

                        var query_dis = Factory.CreateT_BAS_Distribute(tran);
                        query_dis.Update(m => new object[] { m.CompletionDate == DateTime.Now }, v => v.OrderGuid == model_order.OrderGuid);
                    }
                    else
                    {
                        query.UpdateOrder(model_order.OrderNo,
                            RFrameGenerate.BLL.DictionaryConst.OrderState.WaitDelivery,
                            RFrameGenerate.BLL.DictionaryConst.OrderInnerState.WaitDelivery,
                            DateTime.Now,
                             "其他支付", "商家支付");
                    }
                    var listDetail = query.GetOrderDetails(entityGuid);
                    foreach (var v in listDetail)
                    {
                        var product = query.GetProduct(v.ProductGuid.Value);
                        if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockByPay)
                        {//付款减库存,未并发处理
                            decimal inventory = product.Inventory - v.Quantity.Value;
                            decimal saleVolume = product.SalesVolume + v.Quantity.Value;
                            query.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                            var listSKU = querySKU.GetList(a => a.ProductGuid == v.ProductGuid && a.ProductSKUGroupGuid == v.GroupGuid && a.MerchantGuid == curMerchantGuid, isFilterMerchant: false);
                            if (listSKU != null && listSKU.Count > 0)
                            {
                                foreach (var item in listSKU)
                                {
                                    item.Invenotory = item.Invenotory - v.Quantity.Value;
                                    item.EntityState = EntityStates.ToBeUpdated;
                                    querySKU.Update(item, false);
                                }
                            }
                        }



                    }

                    try
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var querywechat = Factory.CreateT_WX_WeChat(tran);
                        var querymerch = Factory.CreateT_BAS_Merchants(tran);
                        var wechat = querywechat.GetFirstData(a => a.appid == Common.CurrentManage.AppId, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        var merch = querymerch.GetFirstData(a => a.WeChatGuid == wechat.WeChatGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        var merchGuid = HeadPay.GetPayMerchantGuid(merch.UserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.购买成功通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        if (template != null)
                        {
                            var member = MemberManage.GetMemberByOrderGuid(entityGuid);
                            string OpenID = member != null ? "" : member.MemberOpenID;
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", "您的订单已支付成功，我们开始为您打包商品，准备发货。");
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("orderID", model_order.OrderNo));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword1", "点击查看商品明细"));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword2", model_order.TotalMoney.Value.ToString("0.00") + "元"));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword3", DateTime.Now.ToString("yyyy-MM-dd")));
                            send.remark = new Wechat.Model.TempateKey("remark", "请耐心等候，谢谢！");

                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "Order/Index", send, Common.CurrentManage.AppId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("WeiXinSync提交订单出错:" + ex.Message);
                    }
                    return new Result(true);
                }

            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public static Result Action_OrderCancel(Guid? entityGuid, Guid merchantGuid)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Orders())
                {
                    var model = query.GetFirstData(a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model == null) return new Result(false, "该数据不存在！");
                    model.OrderInnerState = DictionaryConst.OrderInnerState.BeCancel;
                    model.OrderState = DictionaryConst.OrderState.BeCancel;
                    query.Update(model, false);

                    return new Result(true);
                }

            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 发货(待配送方式完成需修改)
        /// </summary>
        /// <param name="entityGuid">订单Guid</param>
        /// <param name="logisticsCompanyGuid">物流公司Guid</param>
        /// <param name="logisticsExpressNumber">快递单号</param>
        /// <returns></returns>
        public static Result Action_Delivery(Guid entityGuid, Guid logisticsCompanyGuid, string logisticsExpressNumber, Guid recieverAddressGuid, Guid merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var logisticrGuid = Guid.NewGuid();
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_logistics = Factory.CreateT_BAS_Logistics(tran);
                    var query_logisticsCompanys = Factory.CreateT_BAS_LogisticsCompanys(tran);
                    var query_recieverAddress = Factory.CreateT_BAS_RecieverAddress(tran);
                    var queryMember = Factory.CreateT_BAS_Member(tran);
                    var queryInTrade = Factory.CreateT_INT_IntegralTrading(tran);

                    var model_order = query_order.GetFirstData(a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model_order == null)
                        return new Result(false, "该数据不存在");
                    var model_logistics = query_logistics.GetFirstData(a => a.LogisticrGuid == model_order.LogisticrGuid, isFilterMerchant: false);
                    var model_logisticsCompany = query_logisticsCompanys.GetFirstData(a => a.LogisticsCompanyGuid == logisticsCompanyGuid, isFilterMerchant: false);
                    var entity = query_recieverAddress.GetDataByGuid(recieverAddressGuid, isFilterMerchant: false);

                    tran.BeginTransaction();



                    if (model_order.LogisticrGuid == null)
                    {
                        //新增
                        query_logistics.Add(new T_BAS_Logistics()
                        {
                            LogisticrGuid = logisticrGuid,
                            DeliveryMethodGuid = logisticsCompanyGuid,
                            Consignee = entity == null ? "" : entity.Reciever,
                            ExpressNumber = logisticsExpressNumber,
                            ExpressCompany = model_logisticsCompany.LogisticsCompanyName,
                            DeliveryMethod = model_logisticsCompany.LogisticsCompanyName,
                            ExpressDetail = null,
                            Arear = entity == null ? "" : entity.Area,
                            Address = entity == null ? "" : entity.Address,
                            Telephone = entity == null ? "" : entity.Telephone,
                            Zip = entity == null ? "" : entity.Zip,
                            DateTime = DateTime.Now,
                            SMerchantGuid = merchantGuid
                        });
                        if (model_order.IsVirtual != null && model_order.IsVirtual.Value && model_order.NoReceive != null && model_order.NoReceive.Value)
                        {
                            query_order.Update(a => new Object[]{
                                a.LogisticrGuid==logisticrGuid,
                                a.DeliveryTime==DateTime.Now,
                                a.CompletedTime == DateTime.Now,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.Completed,
                                a.OrderState == DictionaryConst.OrderState.Completed
                            }, a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);

                            var query_dis = Factory.CreateT_BAS_Distribute(tran);

                            query_dis.Update(m => new object[] { m.CompletionDate == DateTime.Now }, v => v.OrderGuid == entityGuid && v.MerchantGuid == merchantGuid, isFilterMerchant: false);

                            #region  赠送积分处理 Bing 151224 暂不处理
                            //if (model_order.PresentExp > 0)
                            //{
                            //    var member = queryMember.GetFirstData(c => c.MemberGuid == model_order.MemberGuid);
                            //    var tempIntegral = (member.Integral ?? 0) + model_order.PresentExp.Value;

                            //    queryMember.Update(c => new object[]
                            //{
                            //  c.Integral==tempIntegral,
                            //}, c => c.MemberGuid == model_order.MemberGuid);

                            //    queryInTrade.Add(new T_INT_IntegralTrading()
                            //    {
                            //        IntegralTradingGuid = Guid.NewGuid(),
                            //        MemberGuid = model_order.MemberGuid,
                            //        MerchantGuid = model_order.MerchantGuid,
                            //        TradeIntegral = model_order.PresentExp,
                            //        IntegralBalance = tempIntegral,
                            //        OrderGuid = model_order.OrderGuid,
                            //        TradeType = IntegralTradingConst.TradeType.PresentExpType,
                            //        TradeDate = DateTime.Now,
                            //        IntegralTo = IntegralTradingConst.IntegralToDir.Income
                            //    });

                            //}
                            #endregion

                        }
                        else
                        {
                            query_order.Update(a => new Object[]{
                                a.LogisticrGuid==logisticrGuid,
                                a.DeliveryTime==DateTime.Now,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.WaitReceipt,
                                a.OrderState == DictionaryConst.OrderState.WaitReceipt
                            }, a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                        }
                    }
                    else
                    {
                        //修改
                        //没有物流信息，有则更新物流信息
                        if (model_logistics == null)
                        {
                            query_logistics.Add(new T_BAS_Logistics()
                            {
                                LogisticrGuid = model_order.LogisticrGuid.Value,
                                DeliveryMethodGuid = logisticsCompanyGuid,
                                Consignee = entity == null ? "" : entity.Reciever,
                                ExpressNumber = logisticsExpressNumber,
                                ExpressCompany = model_logisticsCompany.LogisticsCompanyName,
                                DeliveryMethod = model_logisticsCompany.LogisticsCompanyName,
                                ExpressDetail = null,
                                Arear = entity == null ? "" : entity.Area,
                                Address = entity == null ? "" : entity.Address,
                                Telephone = entity == null ? "" : entity.Telephone,
                                Zip = entity == null ? "" : entity.Zip,
                                DateTime = DateTime.Now,
                                SMerchantGuid = merchantGuid
                            });
                            query_order.Update(a => new Object[]{
                                a.LogisticrGuid==model_order.LogisticrGuid.Value,
                                a.DeliveryTime==DateTime.Now,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.WaitReceipt,
                                a.OrderState == DictionaryConst.OrderState.WaitReceipt
                            }, a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                        }
                        else
                        {

                            query_logistics.Update(a => new Object[]{
                                    a.ExpressNumber == logisticsExpressNumber,
                                    a.ExpressCompany == model_logisticsCompany.LogisticsCompanyName
                                }, a => a.LogisticrGuid == model_logistics.LogisticrGuid, isFilterMerchant: false);
                            if (model_order.IsVirtual != null && model_order.IsVirtual.Value && model_order.NoReceive != null && model_order.NoReceive.Value)
                            {
                                query_order.Update(a => new Object[]{
                                a.LogisticrGuid==model_logistics.LogisticrGuid,
                                a.DeliveryTime==DateTime.Now,
                                a.CompletedTime == DateTime.Now,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.Completed,
                                a.OrderState == DictionaryConst.OrderState.Completed
                                }, a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);

                                var query_dis = Factory.CreateT_BAS_Distribute(tran);
                                query_dis.Update(m => new object[] { m.CompletionDate == DateTime.Now }, v => v.OrderGuid == entityGuid && v.MerchantGuid == merchantGuid, isFilterMerchant: false);

                                #region  赠送积分处理 Bing 151224 暂不处理
                                //    if (model_order.PresentExp > 0)
                                //    {
                                //        var member = queryMember.GetFirstData(c => c.MemberGuid == model_order.MemberGuid);
                                //        var tempIntegral = (member.Integral ?? 0) + model_order.PresentExp.Value;

                                //        queryMember.Update(c => new object[]
                                //{
                                //  c.Integral==tempIntegral,
                                //}, c => c.MemberGuid == model_order.MemberGuid);

                                //        queryInTrade.Add(new T_INT_IntegralTrading()
                                //        {
                                //            IntegralTradingGuid = Guid.NewGuid(),
                                //            MemberGuid = model_order.MemberGuid,
                                //            MerchantGuid = model_order.MerchantGuid,
                                //            TradeIntegral = model_order.PresentExp,
                                //            IntegralBalance = tempIntegral,
                                //            OrderGuid = model_order.OrderGuid,
                                //            TradeType = IntegralTradingConst.TradeType.PresentExpType,
                                //            TradeDate = DateTime.Now,
                                //            IntegralTo = IntegralTradingConst.IntegralToDir.Income
                                //        });

                                //    }
                                #endregion

                            }
                            else
                            {
                                query_order.Update(a => new Object[]{
                                a.LogisticrGuid==model_logistics.LogisticrGuid,
                                a.DeliveryTime==DateTime.Now,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.WaitReceipt,
                                a.OrderState == DictionaryConst.OrderState.WaitReceipt
                            }, a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                            }

                        }
                    }
                    #region 模板消息
                    try
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.订单发货通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        if (template != null)
                        {
                            var memeber = MemberManage.GetMemberByGuid(model_order.MemberGuid.Value);
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", "您的订单已发货，您可以通过“我的订单”中查询物流信息。");
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("keyword1", model_order.OrderNo));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword2", model_logisticsCompany.LogisticsCompanyName));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword3", logisticsExpressNumber));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword4", entity.Reciever + "  " + entity.City + entity.Area + entity.Address));
                            send.remark = new Wechat.Model.TempateKey("remark", "请耐心等候，谢谢！");

                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(memeber.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", CurrentManage.MerchantUserID)) + "Order/Index", send, Common.CurrentManage.AppId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("发货模板消息出错:" + ex.Message);
                    }
                    #endregion
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }
        }
        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public static Result Action_Receipt(Guid? entityGuid, Guid merchantGuid)
        {

            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query = Factory.CreateT_BAS_Orders(tran);
                    var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                    var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                    var model = query.GetFirstData(a => a.OrderGuid == entityGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model == null) return new Result(false, "该数据不存在！");
                    model.OrderInnerState = DictionaryConst.OrderInnerState.Completed;
                    model.OrderState = DictionaryConst.OrderState.Completed;
                    model.CompletedTime = DateTime.Now;
                    T_BAS_Distribute entity = null;
                    tran.BeginTransaction();
                    query.Update(model, false);
                    if (model.IsDistribute == true)
                    {
                        entity = query_distribute.GetFirstData(a => a.OrderGuid == model.OrderGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                        entity.CompletionDate = DateTime.Now;
                        query_distribute.Update(entity, false);
                    }
                    var list = query_orderDetails.GetList(a => a.OrderGuid == entityGuid, isFilterMerchant: false);
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            if (item.State == DictionaryConst.OrderDetailState.Refunding)
                            {
                                item.State = DictionaryConst.OrderDetailState.Null;
                                query_orderDetails.Update(item, isFilterMerchant: false);
                            }
                        }
                    }
                    tran.Commit();
                    return new Result(true);

                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }
        }
        public static Result Delivery(DataTable dt, ref StringBuilder sb)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_logistics = Factory.CreateT_BAS_Logistics(tran);
                    var query_recieverAddress = Factory.CreateT_BAS_RecieverAddress(tran);
                    var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                    var querywechat = Factory.CreateT_WX_WeChat(tran);
                    var querymerch = Factory.CreateT_BAS_Merchants(tran);
                    var queryOrderFlg = Factory.CreateT_BAS_FlagshipOrders(tran);
                    T_BAS_RecieverAddress model_recieverAddress = null;
                    foreach (DataRow row in dt.Rows)
                    {
                        var orderNo = row["订单号码"].ToString();
                        var model = query_order.GetFirstData(a => a.OrderNo == orderNo, isFilterMerchant: false);
                        if (model == null)
                        {
                            sb.Append("<p>");
                            sb.Append("订单号码：" + row["订单号码"].ToString());
                            sb.Append("该订单不存在！");
                            sb.Append("</p>");
                        }
                        else if (model.OrderInnerState != 2)
                        {
                            sb.Append("<p>");
                            sb.Append("订单号码：" + row["订单号码"].ToString());
                            sb.Append("发货失败！原因：该订单不是待发货状态！");
                            sb.Append("</p>");
                        }
                        else
                        {
                            //增加代理发货判断 Bing 160413
                            var orFlg = queryOrderFlg.GetFirstData(c => c.OrderGuid == model.OrderGuid, isFilterMerchant: false);
                            var isTop = MerchantManage.IsTopTe();
                            if (orFlg != null)
                            {
                                if ((!isTop) && orFlg.GoodsDeliveryType == AgentRuleConst.GoodsDeliveryType.总部)
                                {
                                    sb.Append("<p>");
                                    sb.Append("订单号码：" + row["订单号码"].ToString());
                                    sb.Append("发货失败！原因：该订单为总部发货！");
                                    sb.Append("</p>");
                                    return new Result(false);
                                }
                                if (isTop && orFlg.GoodsDeliveryType == AgentRuleConst.GoodsDeliveryType.代理商)
                                {
                                    sb.Append("<p>");
                                    sb.Append("订单号码：" + row["订单号码"].ToString());
                                    sb.Append("发货失败！原因：该订单为代理发货！");
                                    sb.Append("</p>");
                                    return new Result(false);
                                }

                            }


                            if (model.RecieverAddressGuid == null)
                            {
                                sb.Append("<p>");
                                sb.Append("订单号码：" + row["订单号码"].ToString());
                                sb.Append("发货失败！原因：该订单发货地址不存在！");
                                sb.Append("</p>");
                                return new Result(false);
                            }
                            model_recieverAddress = query_recieverAddress.GetDataByGuid(model.RecieverAddressGuid.Value, isFilterMerchant: false);
                            if (model_recieverAddress == null)
                            {
                                sb.Append("<p>");
                                sb.Append("订单号码：" + row["订单号码"].ToString());
                                sb.Append("发货失败！原因：该订单发货地址不存在！");
                                sb.Append("</p>");
                                return new Result(false);
                            }
                            var guid = Guid.NewGuid();
                            query_logistics.Add(new T_BAS_Logistics()
                            {
                                LogisticrGuid = guid,
                                DeliveryMethodGuid = guid,
                                Consignee = model_recieverAddress.Reciever,
                                ExpressNumber = row["运单号码"].ToString(),
                                ExpressCompany = row["物流公司"].ToString(),
                                DeliveryMethod = row["物流公司"].ToString(),
                                Arear = model_recieverAddress.Area,
                                Address = model_recieverAddress.Address,
                                Telephone = model_recieverAddress.Telephone,
                                Zip = model_recieverAddress.Zip,
                                DateTime = DateTime.Now,
                                SMerchantGuid = model.SMerchantGuid
                            });
                            query_order.Update(a => new Object[]
                            {
                                a.LogisticrGuid==guid,
                                a.OrderState==DictionaryConst.OrderState.WaitReceipt,
                                a.OrderInnerState==DictionaryConst.OrderInnerState.WaitReceipt
                            }, a => a.OrderNo == row["订单号码"].ToString(), isFilterMerchant: false);
                            sb.Append("<p>");
                            sb.Append("订单号码：" + row["订单号码"].ToString());
                            sb.Append("&nbsp;发货成功！");
                            sb.Append("</p>");
                        }
                        #region 模板消息
                        try
                        {
                            var wechat = querywechat.GetFirstData(a => a.appid == Common.CurrentManage.AppId, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            var merch = querymerch.GetFirstData(a => a.WeChatGuid == wechat.WeChatGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            var merchGuid = HeadPay.GetPayMerchantGuid(merch.UserID);
                            var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.订单发货通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            if (template != null)
                            {
                                string OpenID = MemberManage.GetMemberByOrderGuid(model.OrderGuid) == null ? "" : MemberManage.GetMemberByOrderGuid(model.OrderGuid).MemberOpenID;
                                Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                send.first = new Wechat.Model.TempateKey("first", "您的订单已发货，您可以通过“我的订单”中查询物流信息。");
                                send.keys = new List<Wechat.Model.TempateKey>();
                                send.keys.Add(new Wechat.Model.TempateKey("keyword1", row["物流公司"].ToString()));
                                send.keys.Add(new Wechat.Model.TempateKey("keyword2", row["运单号码"].ToString()));
                                if (model_recieverAddress != null)
                                {
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword3", model_recieverAddress.Reciever + "  " + model_recieverAddress.City + model_recieverAddress.Area + model_recieverAddress.Address));
                                }
                                send.remark = new Wechat.Model.TempateKey("remark", "请耐心等候，谢谢！");

                                weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", merch.UserID)) + "Order/Index", send, Common.CurrentManage.AppId);
                            }
                        }
                        catch (Exception ex)
                        {
                            Wechat.LogManage.Log("WeiXinSync提交订单出错:" + ex.Message);
                        }
                        #endregion
                    }
                    return new Result(true);
                }
                catch (Exception err)
                {
                    sb.Append("<p>");
                    sb.Append(err.Message);
                    sb.Append("</p>");
                    return new Result(false);
                }
            }


        }

        /// <summary>
        /// 获取订单付款金额
        /// </summary>
        public static PriceResult OrderPayMoney(T_BAS_Orders order)
        {
            if (order == null) return new PriceResult(false, "订单不能为空！");

            //if (order.TotalMoney == null || order.TotalMoney.Value <= 0) return new PriceResult(false, "总金额不能为空！");//zhou 2016/03/30 添加0元可支付

            var totalMoney = order.TotalMoney ?? 0;

            if (order.Freight != null)//运费
            {
                totalMoney += order.Freight.Value;
            }

            if (order.PrivilegelMoney != null)//优惠金额
            {
                totalMoney -= order.PrivilegelMoney.Value;
            }

            // 添加积分-抵扣处理 Bing 151219
            if (order.IntegralMoney > 0)//减积分金额
            {
                totalMoney -= order.IntegralMoney.Value;
                totalMoney = totalMoney <= 0 ? 0M : totalMoney;
            }

            //if (totalMoney <= 0) return new PriceResult(false, "总金额小于等于0元，不能支付！");//zhou 2016/03/30 添加0元可支付

            return new PriceResult(true, totalMoney);
        }
        private bool ValidateState(string state)
        {
            try
            {
                if (!string.IsNullOrEmpty(state) && state != "0")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 导出订单
        /// </summary>
        /// <param name="merchantguid"></param>
        /// <param name="orderState"></param>
        /// <param name="memberName"></param>
        /// <param name="orderNo"></param>
        /// <param name="payNo"></param>
        /// <param name="reciever"></param>
        public DataTable ExportOrdersByPrm(Guid merchantguid, string orderState, string memberName, string orderNo, string payNo, string reciever)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    orderState = orderState.Replace("'", "''");
                    memberName = memberName.Replace("'", "''");
                    orderNo = orderNo.Replace("'", "''");
                    payNo = payNo.Replace("'", "''");
                    reciever = reciever.Replace("'", "''");

                    StringBuilder strCondition = new StringBuilder();
                    strCondition.Append(string.Format(" where T_BAS_Orders.MerchantGuid='{0}'", merchantguid));
                    if (ValidateState(orderState))
                    {
                        strCondition.Append(string.Format(" and T_BAS_Orders.OrderState={0}", orderState));
                    }
                    if (!string.IsNullOrEmpty(memberName))
                    {
                        strCondition.Append(string.Format(" and T_BAS_Member.membername = '{0}'", memberName));
                    }
                    if (!string.IsNullOrEmpty(orderNo))
                    {
                        strCondition.Append(string.Format(" and T_BAS_Orders.orderNo = '{0}'", orderNo));
                    }
                    if (!string.IsNullOrEmpty(payNo))
                    {
                        strCondition.Append(string.Format(" and T_BAS_Orders.payNo like '%{0}%'", payNo));
                    }
                    if (!string.IsNullOrEmpty(reciever))
                    {
                        strCondition.Append(string.Format(" and T_BAS_RecieverAddress.Reciever like '%{0}%'", reciever));
                    }
                    SqlParameter[] prm = new SqlParameter[]
                    {
                         new SqlParameter("@strCondition",strCondition.ToString()){  }
                    };
                    DataTable dt = RFramework.SQLServer.SqlHelper.ExecuteDataTable("GetAllOrdersByPrm", CommandType.StoredProcedure, prm, tran);
                    return dt;
                }
                catch (Exception err)
                {
                    Wechat.LogManage.Log("导出订单出错，" + err.Message);
                    return null;
                }
            }
        }
    }
}