using RFrameGenerate.BLL.Recharge;
using RFrameGenerate.Common;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.Model;
using RFrameGenerate.Model.PageModel;
using RFramework.SQLQuery.SQLExpands;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Wechat.Refunds;

using RFramework.SQLQuery;

namespace RFrameGenerate.BLL
{
    public class RefundApplysManage
    {
        /// <summary>
        /// 退款申请列表（分页）
        /// </summary>
        /// <param name="gridModel"></param>
        /// <returns></returns>
        public static List<T_BAS_RefundApplysWithLite> GetPageList(GridModel gridModel)
        {
            using (var query = Factory.CreateT_BAS_RefundApplysWithLite())
            {
                if (!MerchantManage.IsTopTe())
                {
                    return query.GetPageList(gridModel, null, true, b => b.ApplyDateTime, DAL.Enums.OrderMethods.DESC);
                }
                else
                {
                    var guids = AgentAuditManage.GetAllSubordinateAgentByMerGuid(CurrentManage.MerchantGuid);
                    if (guids == null || guids.Count == 0)
                    {
                        return query.GetPageList(gridModel, null, true, b => b.ApplyDateTime, DAL.Enums.OrderMethods.DESC);
                    }
                    else
                    {
                        guids.Add(Common.CurrentManage.MerchantGuid);
                        return query.GetPageList(gridModel, c => c.MerchantGuid.SqlIn(guids.Select(g => g.ToString()).ToArray()), true, b => b.ApplyDateTime, DAL.Enums.OrderMethods.DESC, isFilterMerchant: false);
                    }

                }
            }
        }
        /// <summary>
        /// 同意退款
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public static Result Action_Allow(Guid entityGuid, Guid? shipAddressGuid)
        {

            using (var tran = new SqlRTransaction())
            {

                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_ShipAddress = Factory.CreateT_BAS_ShipAddress(tran);
                var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                //if (model == null)
                //    return new Result(false, "没有该数据！");
                //if (model_order.PayTime == null)
                //    return new Result(false, "该订单尚未付款！");
                //if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_validity)) != 0 && DateTimeEx.DateDiff(model_order.PayTime.Value) > int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_validity)))
                //    return new Result(false, "不符合退款条件！");

                tran.BeginTransaction();
                try
                {
                    var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid, isFilterMerchant: false);
                    if (model == null)
                    {
                        return new Result(false, "找不到该退款订单！");
                    }
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid, isFilterMerchant: false);
                    if (model_order == null)
                    {
                        return new Result(false, "找不到该订单信息！");
                    }
                    if (shipAddressGuid == null)
                    {
                        return new Result(false, "请先设置商家发货地址！");
                    }
                    var model_shipAddress = query_ShipAddress.GetFirstData(a => a.ShipAddressGuid == shipAddressGuid);
                    if (model_shipAddress == null)
                    {
                        return new Result(false, "请先设置商家发货地址！");
                    }
                    //	退款单状态置为：等待买家发货
                    model.RefundAddress = model_shipAddress.Province + model_shipAddress.City + model_shipAddress.Area + model_shipAddress.AddressName;
                    model.Telephone = model_shipAddress.Telephone;
                    model.Recipients = model_shipAddress.ContantName;


                    model.State = DictionaryConst.RefundState.WaitDelivery;

                    // 该退款单关联的所有订单明细，状态置为：退款中
                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);

                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        query_orderDetails.Update(a => new Object[]
                        {
                            a.State==DictionaryConst.OrderDetailState.Refunding,

                        }, t => t.OrderDetailGuid == item.OrderDetailGuid && t.SMerchantGuid == model_order.MerchantGuid, isFilterMerchant: false);
                    }
                    //	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query.Update(model, isFilterMerchant: false);
                    query_order.Update(model_order, 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("reason", "同意退款"));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", model.RefundAmount.Value.ToString("0.00")));
                            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, CurrentManage.AppId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("同意退款发送模板消息出错:" + ex.Message);
                    }
                    #endregion

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

        }
        /// <summary>
        /// 拒绝退款
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <param name="refundRemark"></param>
        /// <returns></returns>
        public static Result Action_Refuse(Guid entityGuid, string refundRemark)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                tran.BeginTransaction();
                try
                {
                    var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid, isFilterMerchant: false);
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid, isFilterMerchant: false);
                    //	b)	退款单状态置为：已拒绝
                    model.RefundRemark = refundRemark;
                    model.State = DictionaryConst.RefundState.Rejected;

                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);
                    // c)	该退款单关联的所有订单明细，状态置为：正常
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        query_orderDetail.Update(a => new Object[]
                        {
                            a.State==DictionaryConst.OrderDetailState.Null
                        }, t => t.OrderDetailGuid == item.OrderDetailGuid, isFilterMerchant: false);
                    }
                    //d)	更新订单外部状态
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query.Update(model, isFilterMerchant: false);
                    query_order.Update(model_order, 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("reason", refundRemark));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", "0.00"));
                            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, 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>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static Result Action_Cancel(Guid entityGuid, string reason)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                tran.BeginTransaction();
                try
                {
                    var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid);
                    //	b)	退款单状态置为：取消退款
                    model.RefundRemark = reason;
                    model.State = DictionaryConst.RefundState.CancelRefund;

                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);
                    // c)	该退款单关联的所有订单明细，状态置为：正常
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        query_orderDetail.Update(a => new Object[]
                        {
                            a.State==DictionaryConst.OrderDetailState.Null
                        }, t => t.OrderDetailGuid == item.OrderDetailGuid);
                    }
                    //d)	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query.Update(model);
                    query_order.Update(model_order);

                    #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("reason", reason));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", "0.00"));
                            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, 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>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static Result Action_Cancel(Guid entityGuid, Guid merchantGuid, ref T_BAS_RefundApplys entity)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                tran.BeginTransaction();
                try
                {
                    var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid && a.MerchantGuid == merchantGuid);
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid);
                    if (model.State == DictionaryConst.RefundState.Solved || model.State == DictionaryConst.RefundState.CancelRefund || model.State == DictionaryConst.RefundState.Rejected)
                    {
                        return new Result(false, "该退款申请已处理，请重新打开页面查看最新状态！");
                    }
                    //	b)	退款单状态置为：取消退款
                    model.State = DictionaryConst.RefundState.CancelRefund;

                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);
                    // c)	该退款单关联的所有订单明细，状态置为：正常
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        query_orderDetail.Update(a => new Object[]
                        {
                            a.State==DictionaryConst.OrderDetailState.Null
                        }, t => t.OrderDetailGuid == item.OrderDetailGuid);
                    }
                    //d)	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    entity = model;
                    query.Update(model);
                    query_order.Update(model_order);
                    #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("reason", "您自己取消了"));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", "0.00"));
                            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, 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>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static Result Action_Cancel(Guid entityGuid, Guid merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                tran.BeginTransaction();
                try
                {
                    var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid && a.MerchantGuid == merchantGuid);
                    var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid);
                    if (model.State == DictionaryConst.RefundState.Solved || model.State == DictionaryConst.RefundState.CancelRefund || model.State == DictionaryConst.RefundState.Rejected)
                    {
                        return new Result(false, "该退款申请已处理，请重新打开页面查看最新状态！");
                    }
                    //	b)	退款单状态置为：取消退款
                    model.State = DictionaryConst.RefundState.CancelRefund;

                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);
                    // c)	该退款单关联的所有订单明细，状态置为：正常
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        query_orderDetail.Update(a => new Object[]
                        {
                            a.State==DictionaryConst.OrderDetailState.Null
                        }, t => t.OrderDetailGuid == item.OrderDetailGuid);
                    }
                    //d)	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query.Update(model);
                    query_order.Update(model_order);
                    #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("reason", "您自己取消了"));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", "0.00"));
                            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, 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>
        /// <param name="refundAddress"></param>
        /// <returns></returns>
        public static Result Action_UpdateAddr(Guid entityGuid, Guid shipAddressGuid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateT_BAS_RefundApplys(tran);
                    var query_ShipAddress = Factory.CreateT_BAS_ShipAddress(tran);
                    var shipAddress = query_ShipAddress.GetFirstData(a => a.ShipAddressGuid == shipAddressGuid);
                    query.Update(a => new Object[]
                    {
                        a.RefundAddress==shipAddress.AddressName,
                        a.Telephone==shipAddress.Telephone,
                        a.Recipients==shipAddress.ContantName
                    }, b => b.RefundApplyGuid == entityGuid && b.MerchantGuid == CurrentManage.MerchantGuid);
                }
                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_Confirm(Guid entityGuid)
        {
            //decimal firstCommission = 0;
            //decimal secondCommission = 0;
            //decimal thirdCommission = 0;
            decimal? curAmount = 0;
            using (var tran = new SqlRTransaction())
            {

                //if (!CheckMeet())
                //{
                //    return new Result(false, "不符合退款条件！");
                //}
                var query = Factory.CreateT_BAS_RefundApplys(tran);
                var query_commissions = Factory.CreateT_BAS_DistributionCommissions(tran);
                var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                var query_procedure = Factory.CreateProcedure(tran);
                var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                var model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid, isFilterMerchant: false);
                var model_order = query_order.GetFirstData(a => a.OrderGuid == model.OrderGuid, isFilterMerchant: false);
                var model_distribute = query_distribute.GetFirstData(a => a.OrderGuid == model.OrderGuid && a.MerchantGuid == model_order.MerchantGuid, isFilterMerchant: false);

                if (model == null)
                    return new Result(false, "没有该数据！");

                if (model_order == null)
                    return new Result(false, "没有该数据！");

                if (model_distribute != null && model_distribute.IsSettlement == true)
                    return new Result(false, "该订单已结算，不允许退款！");
                //if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_validity))!=0&&DateTimeEx.DateDiff(model_order.PayTime.Value)>int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_validity)))
                //    return new Result(false, "不符合退款条件！");
                tran.BeginTransaction();
                try
                {
                    //b)	退款单状态置为：已处理
                    model.State = DictionaryConst.RefundState.Solved;

                    //c)	该退款单关联的所有订单明细，状态置为：已退款
                    List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(entityGuid);
                    if (list.Count == 0)
                    {
                        tran.Rollback();
                        return new Result(false, "没有找到与该退款单对应的订单明细");
                    }
                    //更新订单表

                    curAmount = model_order.TotalMoney - model.RefundAmount;



                    //重新计算订单、分销订单、订单明细佣金
                    if (model_order.IsDistribute == true && model_distribute != null && model_distribute.IsSettlement == false)
                    {
                        ////分销佣金、分销商等级
                        //Guid? distributorGuid = model_order.DistributionPropGuid;
                        //Guid? superiorDistributorGuid = null;
                        //Guid? topDistributorGuid = null;


                        //superiorDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(distributorGuid, model_order.OrderGuid, 2, model_order.MerchantGuid);
                        //topDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(superiorDistributorGuid, model_order.OrderGuid, 3, model_order.MerchantGuid);

                        //if (distributorGuid != null && distributorGuid != Guid.Empty)
                        //{
                        //    firstCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.FirstCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.FirstCommission))) / 100;
                        //}
                        //if (superiorDistributorGuid != null && superiorDistributorGuid != Guid.Empty)
                        //{
                        //    secondCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.SecondCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.SecondCommission))) / 100;
                        //}
                        //if (topDistributorGuid != null && topDistributorGuid != Guid.Empty)
                        //{
                        //    thirdCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.ThirdCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.ThirdCommission))) / 100;
                        //}
                        ////更新分销订单表
                        //model_distribute.FirstCommission = curAmount * firstCommission;
                        //model_distribute.SecondCommission = curAmount * secondCommission;
                        //model_distribute.ThirdCommission = curAmount * thirdCommission;
                        //model_distribute.TotalCommission = curAmount * firstCommission + curAmount * secondCommission + curAmount * thirdCommission;
                        //修改佣金 zhou 2016/4/18
                        List<T_BAS_OrderDetails> listOrderDetail = query_orderDetails.GetList(a => a.OrderGuid == model_order.OrderGuid && a.State != DictionaryConst.OrderDetailState.Refunded, isFilterMerchant: false);
                        decimal firstCommission = 0;
                        decimal secondCommission = 0;
                        decimal thirdCommission = 0;
                        decimal totalCommission = 0;
                        foreach (var item in listOrderDetail)
                        {
                            var detail = list.Where(a => a.OrderDetailGuid == item.OrderDetailGuid).FirstOrDefault();
                            if (detail == null)//当前不计算佣金
                            {
                                firstCommission += item.FirstCommission.Value;
                                secondCommission += item.SecondCommission.Value;
                                thirdCommission += item.ThirdCommission.Value;
                                totalCommission += item.TotalCommission.Value;
                            }
                        }
                        query_distribute.Update(a => new object[] 
                            { 
                                a.FirstCommission == firstCommission,
                                a.SecondCommission == secondCommission, 
                                a.ThirdCommission == thirdCommission,
                                a.TotalCommission == totalCommission 
                            }, b => b.DistributeGuid == model_distribute.DistributeGuid, isFilterMerchant: false);
                    }

                    var totalIntegral = 0;//总积分

                    //更新商品库存、销量
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        var model_orderDetail = query_orderDetails.GetFirstData(a => a.OrderDetailGuid == item.OrderDetailGuid, isFilterMerchant: false);
                        model_orderDetail.FirstCommission = 0;
                        model_orderDetail.SecondCommission = 0;
                        model_orderDetail.ThirdCommission = 0;
                        model_orderDetail.TotalCommission = 0;
                        model_orderDetail.State = DictionaryConst.OrderDetailState.Refunded;
                        query_orderDetails.Update(model_orderDetail, isFilterMerchant: false);

                        totalIntegral += (model_orderDetail.IntegralTe ?? 0);

                        if (model.IsRefund == true)
                        {
                            var product = query_procedure.GetProduct(model_orderDetail.ProductGuid.Value);
                            if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockByPay)
                            {
                                //付款减库存,未并发处理
                                if (model_order.OrderInnerState == DictionaryConst.OrderInnerState.WaitDelivery || model_order.OrderInnerState == DictionaryConst.OrderInnerState.WaitReceipt || model_order.OrderInnerState == DictionaryConst.OrderInnerState.Completed)
                                {
                                    decimal inventory = product.Inventory + model_orderDetail.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - model_orderDetail.Quantity.Value;
                                    query_procedure.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = querySKU.GetList(a => a.ProductGuid == model_orderDetail.ProductGuid && a.ProductSKUGroupGuid == model_orderDetail.GroupGuid, isFilterMerchant: false);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var subItem in listSKU)
                                        {
                                            subItem.Invenotory = subItem.Invenotory + model_orderDetail.Quantity.Value;
                                            subItem.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        querySKU.UpdateList(listSKU);
                                    }
                                }
                            }
                            else
                            {
                                //拍下减库存,未并发处理
                                if (model_order.OrderInnerState != DictionaryConst.OrderInnerState.BeCancel)
                                {
                                    decimal inventory = product.Inventory + model_orderDetail.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - model_orderDetail.Quantity.Value;
                                    query_procedure.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = querySKU.GetList(a => a.ProductGuid == model_orderDetail.ProductGuid && a.ProductSKUGroupGuid == model_orderDetail.GroupGuid, isFilterMerchant: false);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var subItem in listSKU)
                                        {
                                            subItem.Invenotory = subItem.Invenotory + model_orderDetail.Quantity.Value;
                                            subItem.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        querySKU.UpdateList(listSKU);
                                    }
                                }
                            }
                        }
                    }
                    //  更新订单明细
                    //var list_orderDetail = query_orderDetails.GetList(a=>a.OrderGuid==model_order.OrderGuid);
                    //foreach (var item in list_orderDetail)
                    //{
                    //    item.FirstCommission = 0;
                    //    item.SecondCommission = 0;
                    //    item.ThirdCommission = 0;
                    //    item.TotalCommission = 0;
                    //    item.State = DictionaryConst.OrderDetailState.Refunded;
                    //    query_orderDetails.Update(item);
                    //}

                    //d)	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);

                    //e)	买家的账户余额=账户余额+退款金额
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    var model_member = query_member.GetFirstData(a => a.MemberGuid == model_order.MemberGuid, isFilterMerchant: false);
                    //model_member.Balance += model.RefundAmount == null ? 0 : model.RefundAmount.Value;
                    //model_member.ExpenseTotal -= model.RefundAmount == null ? 0 : model.RefundAmount.Value;

                    //zhou 2015/10/27
                    decimal balance = model_member.Balance + model.RefundAmount.Value;//退到可用余额
                    decimal amount = model_member.Amount + model.RefundAmount.Value;//总额也要加
                    decimal expenseTotal = model_member.ExpenseTotal - model.RefundAmount.Value;//减累计消费
                    //add by Panwp 20151224
                    RechargeRecordManage.AddRefund(model_order.OrderNo, model_member.MemberGuid, model.RefundAmount.Value, model_member.Amount, model_member.Balance, model_order.MerchantGuid.Value);

                    if (RFrameGenerate.BLL.Member.MemberLevelManage.UsingMemberLevel())
                    {
                        model_member.GrowthValue = model_member.GrowthValue - model.RefundAmount.Value;
                    }
                    var growthValue = model_member.GrowthValue == null || model_member.GrowthValue < 0.0m ? 0.0m : model_member.GrowthValue;
                    #region 补充 退还用户积分处理 赠送暂不处理 Bing 151225

                    var tempIntegral = model_member.Integral;
                    if (totalIntegral > 0)
                    {
                        tempIntegral += totalIntegral;

                        query_InTrade.Add(new T_INT_IntegralTrading()
                        {
                            IntegralTradingGuid = Guid.NewGuid(),
                            MemberGuid = model_member.MemberGuid,
                            MerchantGuid = model_member.MerchantGuid,
                            TradeIntegral = totalIntegral,
                            IntegralBalance = tempIntegral,
                            OrderGuid = model_order.OrderGuid,
                            TradeType = IntegralTradingConst.TradeType.RefundType,
                            TradeDate = DateTime.Now,
                            IntegralTo = IntegralTradingConst.IntegralToDir.Income,
                            SMerchantGuid = model_order.MerchantGuid
                        });
                    }

                    #endregion


                    #region 补充 代理预存订单扣减处理  Bing 160325

                    //if (totalIntegral > 0)
                    //{
                    //    tempIntegral += totalIntegral;

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

                    #endregion

                    //添加会员账户记录 Bing 160423 
                    MemberAccountManage.AddMemberAccount(model_member.MemberGuid, MemberAccountConst.TradingType.消费_退款, model.RefundApplyGuid, model.RefundAmount.Value, tran, model_member.Balance, model_member.MerchantGuid, "订单退款");

                    query_member.Update(a => new object[] 
                    { 
                        a.Balance==balance,
                        a.Amount==amount,
                        a.ExpenseTotal==expenseTotal,
                        a.GrowthValue == growthValue,
                        a.Integral==tempIntegral//新积分
                    }, b => b.MemberGuid == model_member.MemberGuid, isFilterMerchant: false);

                    query.Update(model, isFilterMerchant: false);
                    query_order.Update(model_order, isFilterMerchant: false);
                    //if (model_distribute != null)zhou 2016/4/18
                    //{
                    //    query_distribute.Update(model_distribute, isFilterMerchant: false);
                    //}

                    //if (model_member != null)//zhou 2015/10/27
                    //{
                    //    query_member.Update(model_member);
                    //}
                    #region 模板消息
                    try
                    {
                        #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("reason", "同意退款"));
                                send.keys.Add(new Wechat.Model.TempateKey("refund", model.RefundAmount.Value.ToString("0.00")));
                                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, CurrentManage.AppId);
                            }
                        }
                        catch (Exception ex)
                        {
                            Wechat.LogManage.Log("同意退款发送模板消息出错:" + ex.Message);
                        }
                        #endregion
                    }
                    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="refundApplyGuid">退款Guid</param>
        /// <returns></returns>
        public static Result RefundMoney(Guid refundApplyGuid)
        {
            #region 检查退款合法性

            T_BAS_RefundApplys applys = null;
            //检查是否可以退款
            var canState = CanRefund(refundApplyGuid, out applys);
            if (!canState.State) return new Result(false, canState.Msg);

            //之前订单按之前逻辑
            if (string.IsNullOrEmpty(applys.RefundOrderNo)) return Action_Confirm(refundApplyGuid);

            T_BAS_Orders model_order = null;
            T_BAS_Distribute model_distribute = null;
            using (var tran = new SqlRTransaction())
            {
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                var query_member = Factory.CreateT_BAS_Member(tran);
                var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);

                model_order = query_order.GetFirstData(a => a.OrderGuid == applys.OrderGuid, isFilterMerchant: false);
                model_distribute = query_distribute.GetFirstData(a => a.OrderGuid == applys.OrderGuid && a.MerchantGuid == model_order.MerchantGuid, isFilterMerchant: false);

                if (model_order == null)
                    return new Result(false, "没有该数据！");
                if (model_order.WXPayMoney == null)
                    return new Result(false, "付款金额为空，不能退款！");
                if (model_distribute != null && model_distribute.IsSettlement == true)
                    return new Result(false, "该订单已结算，不允许退款！");


            }
            List<T_BAS_RefundOrderDetails> list = RefundOrderDetailsManage.GetList(refundApplyGuid);
            if (list.Count <= 0)
            {
                return new Result(false, "没有找到与该退款单对应的订单明细");
            }

            if (model_order.TransactionID == "模拟支付" || model_order.TransactionID == "余额支付" || model_order.TransactionID == "商家支付") return Action_Confirm(refundApplyGuid);

            #endregion

            #region 调用接口退款

            //设置正在退款
            var preRefundStae = applys.State.Value;
            SetRefundState(refundApplyGuid, DictionaryConst.RefundState.Refunding);

            try
            {
                var pay = HeadPay.GetPayWayByOrderNO(applys.OrderNo);
                string key = pay.GetValue(DictionaryConst.PayWays.WeiXin.Key);
                string mch_id = pay.GetValue(DictionaryConst.PayWays.WeiXin.MChid);
                string appid = pay.GetValue(DictionaryConst.PayWays.WeiXin.AppID);
                string cer = pay.GetValue(DictionaryConst.PayWays.WeiXin.Cer);

                RefundRequest request = new RefundRequest();

                var state = request.RefundApply(new RefundApplyRequestModel()
                {
                    appid = appid,
                    key = key,
                    mch_id = mch_id,
                    op_user_id = mch_id,
                    out_refund_no = applys.RefundOrderNo,
                    out_trade_no = applys.OrderNo,
                    transaction_id = "",
                    refund_fee = (applys.RefundAmount.Value * 100).ToString("0"),
                    refund_fee_type = "CNY",
                    total_fee = (model_order.WXPayMoney.Value * 100).ToString("0"),
                    device_info = null,
                }, cer, mch_id);

                if (!state.VerifySign() || (!string.IsNullOrEmpty(state.result_code) && state.result_code.ToUpper() != "SUCCESS") || (!string.IsNullOrEmpty(state.return_code) && state.return_code.ToUpper() != "SUCCESS"))
                {
                    //调用失败，还原状态
                    SetRefundState(refundApplyGuid, preRefundStae);
                    Wechat.LogManage.Log(string.Format("调用退款接口失败:   Error Code : {0}   Msg：{1}", state.err_code, state.err_code_des));

                    return new Result(false, "调用退款接口失败:" + state.err_code_des);
                }
            }
            catch (Exception ex)
            {
                SetRefundState(refundApplyGuid, preRefundStae);
                Wechat.LogManage.Log("调用退款接口异常:  " + ex.Message);
                return new Result(false, ex.Message);
            }
            #endregion

            //decimal firstCommission = 0;
            //decimal secondCommission = 0;
            //decimal thirdCommission = 0;
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                try
                {
                    var query = Factory.CreateT_BAS_RefundApplys(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_orderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                    var query_procedure = Factory.CreateProcedure(tran);
                    var querySKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                    var query_distribute = Factory.CreateT_BAS_Distribute(tran);

                    var curAmount = (model_order.WXPayMoney - model_order.Freight ?? 0) - applys.RefundAmount;

                    //c)	退款单状态置为：已处理
                    query.Update(m => new object[] { m.State == DictionaryConst.RefundState.Solved }, v => v.RefundApplyGuid == refundApplyGuid, isFilterMerchant: false);

                    #region 重新计算订单、分销订单、订单明细佣金
                    if (model_order.IsDistribute == true && model_distribute != null && model_distribute.IsSettlement == false)
                    {
                        ////分销佣金、分销商等级
                        //Guid? distributorGuid = model_order.DistributionPropGuid;
                        //Guid? superiorDistributorGuid = null;
                        //Guid? topDistributorGuid = null;


                        //superiorDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(distributorGuid, model_order.OrderGuid, 2, model_order.MerchantGuid);
                        //topDistributorGuid = DistributionManage.GetSuperiorDistributorGuid(superiorDistributorGuid, model_order.OrderGuid, 3, model_order.MerchantGuid);

                        //if (distributorGuid != null)
                        //{
                        //    firstCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.FirstCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.FirstCommission))) / 100;
                        //}
                        //if (superiorDistributorGuid != null)
                        //{
                        //    secondCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.SecondCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.SecondCommission))) / 100;
                        //}
                        //if (topDistributorGuid != null)
                        //{
                        //    thirdCommission = (ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.ThirdCommission) == "" ? 0 : decimal.Parse(ParameterManage.GetParameters_Commission(model_order.MerchantGuid.Value, ParameterName.CommissionMember.ThirdCommission))) / 100;
                        //}
                        ////更新分销订单表
                        //model_distribute.FirstCommission = curAmount * firstCommission;
                        //model_distribute.SecondCommission = curAmount * secondCommission;
                        //model_distribute.ThirdCommission = curAmount * thirdCommission;
                        //model_distribute.TotalCommission = curAmount * firstCommission + curAmount * secondCommission + curAmount * thirdCommission;

                        //修改佣金 zhou 2016/4/18
                        List<T_BAS_OrderDetails> listOrderDetail = query_orderDetails.GetList(a => a.OrderGuid == model_order.OrderGuid && a.State != DictionaryConst.OrderDetailState.Refunded, isFilterMerchant: false);
                        decimal firstCommission = 0;
                        decimal secondCommission = 0;
                        decimal thirdCommission = 0;
                        decimal totalCommission = 0;
                        foreach (var item in listOrderDetail)
                        {
                            var detail = list.Where(a => a.OrderDetailGuid == item.OrderDetailGuid).FirstOrDefault();
                            if (detail == null)//当前不计算佣金
                            {
                                firstCommission += item.FirstCommission.Value;
                                secondCommission += item.SecondCommission.Value;
                                thirdCommission += item.ThirdCommission.Value;
                                totalCommission += item.TotalCommission.Value;
                            }
                        }
                        query_distribute.Update(a => new object[] 
                            { 
                                a.FirstCommission == firstCommission,
                                a.SecondCommission == secondCommission, 
                                a.ThirdCommission == thirdCommission,
                                a.TotalCommission == totalCommission 
                            }, b => b.DistributeGuid == model_distribute.DistributeGuid, isFilterMerchant: false);
                    }
                    #endregion
                    var totalIntegral = 0;//总积分
                    #region 更新商品库存、销量
                    foreach (T_BAS_RefundOrderDetails item in list)
                    {
                        var model_orderDetail = query_orderDetails.GetFirstData(a => a.OrderDetailGuid == item.OrderDetailGuid, isFilterMerchant: false);
                        model_orderDetail.FirstCommission = 0;
                        model_orderDetail.SecondCommission = 0;
                        model_orderDetail.ThirdCommission = 0;
                        model_orderDetail.TotalCommission = 0;
                        model_orderDetail.State = DictionaryConst.OrderDetailState.Refunded;
                        query_orderDetails.Update(model_orderDetail, isFilterMerchant: false);

                        totalIntegral += (model_orderDetail.IntegralTe ?? 0);

                        if (applys.IsRefund == true)
                        {
                            var product = query_procedure.GetProduct(model_orderDetail.ProductGuid.Value);
                            if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockByPay)
                            {
                                //付款减库存,未并发处理
                                if (model_order.OrderInnerState == DictionaryConst.OrderInnerState.WaitDelivery || model_order.OrderInnerState == DictionaryConst.OrderInnerState.WaitReceipt || model_order.OrderInnerState == DictionaryConst.OrderInnerState.Completed)
                                {
                                    decimal inventory = product.Inventory + model_orderDetail.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - model_orderDetail.Quantity.Value;
                                    query_procedure.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = querySKU.GetList(a => a.ProductGuid == model_orderDetail.ProductGuid && a.ProductSKUGroupGuid == model_orderDetail.GroupGuid, isFilterMerchant: false);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var subItem in listSKU)
                                        {
                                            subItem.Invenotory = subItem.Invenotory + model_orderDetail.Quantity.Value;
                                            subItem.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        querySKU.UpdateList(listSKU);
                                    }
                                }
                            }
                            else
                            {
                                //拍下减库存,未并发处理
                                if (model_order.OrderInnerState != DictionaryConst.OrderInnerState.BeCancel)
                                {
                                    decimal inventory = product.Inventory + model_orderDetail.Quantity.Value;
                                    decimal saleVolume = product.SalesVolume - model_orderDetail.Quantity.Value;
                                    query_procedure.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                    var listSKU = querySKU.GetList(a => a.ProductGuid == model_orderDetail.ProductGuid && a.ProductSKUGroupGuid == model_orderDetail.GroupGuid, isFilterMerchant: false);
                                    if (listSKU != null && listSKU.Count > 0)
                                    {
                                        foreach (var subItem in listSKU)
                                        {
                                            subItem.Invenotory = subItem.Invenotory + model_orderDetail.Quantity.Value;
                                            subItem.EntityState = EntityStates.ToBeUpdated;
                                        }
                                        querySKU.UpdateList(listSKU);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region d)	更新“订单外部状态”
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query_order.Update(m => new object[] { m.OrderState == model_order.OrderState }, v => v.OrderGuid == model_order.OrderGuid, isFilterMerchant: false);

                    //if (model_distribute != null)zhou 2016/4/18
                    //{
                    //    query_distribute.Update(model_distribute, isFilterMerchant: false);
                    //}
                    #endregion

                    #region e)更新会员信息
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    var model_member = query_member.GetFirstData(a => a.MemberGuid == model_order.MemberGuid, isFilterMerchant: false);
                    if (RFrameGenerate.BLL.Member.MemberLevelManage.UsingMemberLevel())
                    {
                        model_member.GrowthValue = model_member.GrowthValue - applys.RefundAmount.Value;//减成长值
                    }
                    var growthValue = model_member.GrowthValue == null || model_member.GrowthValue < 0.0m ? 0.0m : model_member.GrowthValue;

                    var expenseTotal = model_member.ExpenseTotal - applys.RefundAmount.Value;//减累计消费
                    expenseTotal = expenseTotal < 0.0m ? 0.0m : expenseTotal;

                    #region 补充 退还用户积分处理 赠送暂不处理 Bing 151225

                    var tempIntegral = model_member.Integral;
                    if (totalIntegral > 0)
                    {
                        tempIntegral += totalIntegral;

                        query_InTrade.Add(new T_INT_IntegralTrading()
                        {
                            IntegralTradingGuid = Guid.NewGuid(),
                            MemberGuid = model_member.MemberGuid,
                            MerchantGuid = model_member.MerchantGuid,
                            TradeIntegral = totalIntegral,
                            IntegralBalance = tempIntegral,
                            OrderGuid = model_order.OrderGuid,
                            TradeType = IntegralTradingConst.TradeType.RefundType,
                            TradeDate = DateTime.Now,
                            IntegralTo = IntegralTradingConst.IntegralToDir.Income,
                            SMerchantGuid = model_member.MerchantGuid
                        });
                    }

                    #endregion

                    ////添加会员账户记录 Bing 160423 去除
                    //MemberAccountManage.AddMemberAccount(model_member.MemberGuid, MemberAccountConst.TradingType.消费_退款, model_order.OrderGuid, applys.RefundAmount.Value, tran, null, model_member.MerchantGuid);

                    #region 补充 代理预存订单扣减处理 赠送暂不处理 Bing 160325

                    //if (totalIntegral > 0)
                    //{
                    //    tempIntegral += totalIntegral;

                    //    query_InTrade.Add(new T_INT_IntegralTrading()
                    //    {
                    //        IntegralTradingGuid = Guid.NewGuid(),
                    //        MemberGuid = model_member.MemberGuid,
                    //        MerchantGuid = model_member.MerchantGuid,
                    //        TradeIntegral = totalIntegral,
                    //        IntegralBalance = tempIntegral,
                    //        OrderGuid = model_order.OrderGuid,
                    //        TradeType = IntegralTradingConst.TradeType.RefundType,
                    //        TradeDate = DateTime.Now,
                    //        IntegralTo = IntegralTradingConst.IntegralToDir.Income,
                    //        SMerchantGuid = model_member.MerchantGuid,
                    //    });
                    //}

                    #endregion

                    query_member.Update(a => new object[] 
                    { 
                        a.ExpenseTotal==expenseTotal,
                        a.GrowthValue == growthValue,
                         a.Integral==tempIntegral//新积分
                    }, b => b.MemberGuid == model_member.MemberGuid, isFilterMerchant: false);


                    #endregion

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Wechat.LogManage.Log(string.Format("退款失败:  " + ex.Message));
                    return new Result(false, ex.Message);
                }
            }
            #region 模板消息
            try
            {
                #region 模板消息
                try
                {
                    T_BAS_Member memeber = null;
                    T_BAS_MessageTemplate template = null;
                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                    using (var querytemp = Factory.CreateT_BAS_MessageTemplate())
                    {
                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.退款通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        if (template != null)
                        {
                            memeber = MemberManage.GetMemberByGuid(model_order.MemberGuid.Value);
                            send.first = new Wechat.Model.TempateKey("first", "您的退款申请通过。");
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("reason", "同意退款"));
                            send.keys.Add(new Wechat.Model.TempateKey("refund", applys.RefundAmount.Value.ToString("0.00")));
                            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, CurrentManage.AppId);
                }
                catch (Exception ex)
                {
                    Wechat.LogManage.Log("同意退款发送模板消息出错:" + ex.Message);
                }
                #endregion
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("同意退款单出错:" + ex.Message);
            }
            #endregion

            return new Result(true);
        }

        private static Result CanRefund(Guid refundApplyGuid, out T_BAS_RefundApplys applys)
        {
            applys = null;
            if (refundApplyGuid == Guid.Empty) return new Result(false, "不存在退款信息！");

            using (var query = Factory.CreateT_BAS_RefundApplys())
            {
                applys = query.GetDataByGuid(refundApplyGuid, isFilterMerchant: false);
            }

            if (applys == null) return new Result(false, "不存在退款信息！");

            if (applys.State == null) return new Result(false, "申请退款状态错误！");

            if (applys.State != DictionaryConst.RefundState.Handling && applys.State != DictionaryConst.RefundState.Shipped) return new Result(false, "订单已经处理，请勿重复退款！");

            if (applys.RefundAmount == null) return new Result(false, "退款金额不能为空！");

            if (applys.RefundAmount.Value <= 0) return new Result(false, "退款金额不能小于等于0");

            return new Result(true);
        }

        private static bool SetRefundState(Guid refundApplyGuid, int state)
        {
            using (var query = Factory.CreateT_BAS_RefundApplys())
            {
                query.Update(m => new object[] { m.State == state }, v => v.RefundApplyGuid == refundApplyGuid, isFilterMerchant: false);
            }
            return true;
        }

        private static bool CheckMeet()
        {
            //验证是否符合退款条件
            if (string.IsNullOrEmpty(ParameterManage.GetParameterByName(ParameterName.Refund.OpenRefundService)))
                return false;
            if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.OpenRefundService)) == 0)
                return false;

            if (string.IsNullOrEmpty(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_paid)))
                return false;
            if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_paid)) == 0)
                return false;

            if (string.IsNullOrEmpty(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_delivery)))
                return false;
            if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_delivery)) == 0)
                return false;

            if (string.IsNullOrEmpty(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_completed)))
                return false;
            if (int.Parse(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_completed)) == 0)
                return false;

            if (string.IsNullOrEmpty(ParameterManage.GetParameterByName(ParameterName.Refund.RefundService_validity)))
                return false;

            return true;
        }

        public static int GetState(Guid orderGuid)
        {
            //a)	订单中处于非退款状态（“退款中”、“已退款”）的商品数≥1，则外部状态与内部状态一致；
            //b)	订单中所有商品处于退款状态（“退款中”、“已退款”），并且处于“退款中”的商品≥1，则外部状态置为“退款中”；
            //c)	订单中所有商品处于“已退款”状态，则外部状态置为“已退款”。
            using (var tran = new SqlRTransaction())
            {
                bool flag = false;
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                var model_order = query_order.GetFirstData(a => a.OrderGuid == orderGuid, isFilterMerchant: false);
                var list_orderDetail = query_orderDetail.GetList(a => a.OrderGuid == orderGuid, isFilterMerchant: false);

                foreach (var item in list_orderDetail)
                {
                    if (item.State == DictionaryConst.OrderDetailState.Null)
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    foreach (var item in list_orderDetail)
                    {
                        if (item.State == DictionaryConst.OrderDetailState.Refunding)
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (flag)
                    {
                        return DictionaryConst.OrderState.Refunding;
                    }
                    else
                    {
                        return DictionaryConst.OrderState.Refunded;
                    }
                }
                else
                {
                    return model_order.OrderInnerState.Value;
                }
            }
        }

        public static Result Action_GetRefundInfo(Guid entityGuid, ref T_BAS_RefundApplys model)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_RefundApplys())
                {
                    model = query.GetFirstData(a => a.RefundApplyGuid == entityGuid, isFilterMerchant: false);
                    if (model == null) return new Result(false, "该数据不存在或已删除！");
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="list"></param>
        /// <param name="orderDetailGuid"></param>
        /// <param name="orderGuid"></param>
        /// <param name="merchantGuid"></param>
        /// <returns></returns>
        public static Result AddRefundApply(List<RefundApplysInfo> list, Guid merchantGuid)
        {
            if (list == null || list.Count == 0)
                return new Result(false, "没有退款数据！");

            var orderGuid = list[0].OrderGuid;
            var orderDetailGuid = list[0].OrderDetailGuid;

            using (var sql = new SqlModel<T_BAS_RefundApplys, T_BAS_RefundOrderDetails>())
            {
                var refundList = sql.SqlSelect((a, b) => a.RefundApplyGuid)
                                    .SqlJionInner((a, b) => b).SqlOn((a, b) => a.RefundApplyGuid == b.RefundApplyGuid)
                                    .SqlWhere((a, b) => a.State != DictionaryConst.RefundState.CancelRefund && a.State != DictionaryConst.RefundState.Rejected &&
                                              a.MerchantGuid == CurrentManage.MerchantGuid && a.OrderGuid == orderGuid && b.OrderDetailGuid == orderDetailGuid)
                                    .ToList();


                if (refundList != null && refundList.Count > 0)
                    return new Result(false, "已提交申请，请不要重复提交申请！");
            }
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query = Factory.CreateT_BAS_RefundApplys(tran);
                    var query_details = Factory.CreateT_BAS_RefundOrderDetails(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_produre = Factory.CreateProcedure(tran);
                    var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                    var query_recieverAddress = Factory.CreateT_BAS_RecieverAddress(tran);
                    var model_order = query_order.GetDataByGuid(list[0].OrderGuid);
                    var query_member = Factory.CreateT_BAS_Member(tran);
                    if (model_order == null)
                        return new Result(false, "找不到该订单！");
                    var refundApplyGuid = Guid.NewGuid();
                    var model_recieverAddress = query_recieverAddress.GetFirstData(a => a.RecieverAddressGuid == model_order.RecieverAddressGuid);
                    tran.BeginTransaction();

                    foreach (RefundApplysInfo item in list)
                    {
                        var orderDetail = query_orderDetail.GetDataByGuid(item.OrderDetailGuid);

                        if (orderDetail == null) return new Result(false, "订单明细为空！");

                        if (item.RefundAmount > (orderDetail.WXPayMoney ?? orderDetail.Amount)) return new Result(false, "退款金额不能大于" + (orderDetail.WXPayMoney ?? orderDetail.Amount).Value.ToString("N02"));

                        query.Add(new T_BAS_RefundApplys()
                        {
                            RefundApplyGuid = refundApplyGuid,
                            MerchantGuid = merchantGuid,
                            OrderGuid = item.OrderGuid,
                            OrderNo = model_order.OrderNo,
                            RefundType = item.RefundType,
                            IsSignIn = item.IsSignIn == 0 ? false : true,
                            IsRefund = item.IsRefund == 0 ? false : true,
                            Recipients = model_recieverAddress == null ? "" : model_recieverAddress.Reciever,
                            Telephone = model_recieverAddress == null ? "" : model_recieverAddress.Telephone,
                            RefundAddress = model_recieverAddress == null ? "" : model_recieverAddress.Province + model_recieverAddress.City + model_recieverAddress.Area + model_recieverAddress.Address,
                            RefundWay = model_order.TransactionID == "模拟支付" || model_order.TransactionID == "余额支付" || model_order.TransactionID == "商家支付" ? DictionaryConst.RefundWay.MerberBalance : DictionaryConst.RefundWay.WeChatAccount,
                            RefundAmount = item.RefundAmount,
                            ApplyDateTime = DateTime.Now,
                            RefundRemark = item.RefundRemark,
                            State = DictionaryConst.RefundState.Handling,
                            Account = "",
                            SerialNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3),
                            RefundOrderNo = OrderManage.GetOrderNO()
                        });

                        //如果存在退款订单明细则删除否则新增
                        query_details.Delete(a => a.OrderDetailGuid == item.OrderDetailGuid);
                        query_details.Add(new T_BAS_RefundOrderDetails()
                        {
                            RefundOrderDetailsGuid = Guid.NewGuid(),
                            RefundApplyGuid = refundApplyGuid,
                            OrderDetailGuid = item.OrderDetailGuid
                        });

                        query_orderDetail.Update(a => new Object[] { 
                            a.State==DictionaryConst.OrderDetailState.Refunding
                        }, a => a.OrderDetailGuid == item.OrderDetailGuid);

                    }
                    //a)	订单中处于非退款状态（“退款中”、“已退款”）的商品数≥1，则外部状态与内部状态一致；
                    //b)	订单中所有商品处于退款状态（“退款中”、“已退款”），并且处于“退款中”的商品≥1，则外部状态置为“退款中”；
                    //c)	订单中所有商品处于“已退款”状态，则外部状态置为“已退款”。
                    model_order.OrderState = GetState(model_order.OrderGuid);
                    query_order.Update(model_order);
                    #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 == 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 list_refundOrderdetail = query_produre.GetRefundOrder(refundApplyGuid);
                            string OpenID = MemberManage.GetMemberByOrderGuid(model_order.OrderGuid) == null ? "" : MemberManage.GetMemberByOrderGuid(model_order.OrderGuid).MemberOpenID;
                            if (list_refundOrderdetail != null && list_refundOrderdetail.Count > 0)
                            {
                                foreach (PT_BAS_OrderDetails_Refund item in list_refundOrderdetail)
                                {

                                    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("orderProductPrice", item.RefundAmount.ToString("0.00")));
                                    send.keys.Add(new Wechat.Model.TempateKey("orderProductName", item.ProductName));
                                    send.keys.Add(new Wechat.Model.TempateKey("orderName", model_order.OrderNo));
                                    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("订单退款发送模板消息出错:" + ex.Message);
                    }
                    #endregion
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }
        }


        /// <summary>
        /// 退单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="orderGuid"></param>
        /// <param name="merchantGuid"></param>
        /// <returns></returns>
        /// 
        public static Result AddRefundApplyList(List<RefundApplysInfo> list, Guid orderGuid, Guid merchantGuid)
        {
            if (list == null || list.Count == 0)
                return new Result(false, "没有退款数据！");

            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query = Factory.CreateT_BAS_RefundApplys(tran);
                    var query_details = Factory.CreateT_BAS_RefundOrderDetails(tran);
                    var query_order = Factory.CreateT_BAS_Orders(tran);
                    var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                    var query_produre = Factory.CreateProcedure(tran);
                    var query_recieverAddress = Factory.CreateT_BAS_RecieverAddress(tran);
                    var model_order = query_order.GetDataByGuid(orderGuid);
                    if (model_order == null)
                        return new Result(false, "找不到该订单！");
                    var model_recieverAddress = query_recieverAddress.GetFirstData(a => a.RecieverAddressGuid == model_order.RecieverAddressGuid);

                    var refund = query.GetFirstData(m => m.OrderGuid == orderGuid && m.State != DictionaryConst.RefundState.CancelRefund && m.State != DictionaryConst.RefundState.Rejected);

                    if (refund != null) return new Result(false, "已提交申请，请不要重复申请！");

                    var refundApplyGuid = Guid.NewGuid();
                    tran.BeginTransaction();

                    foreach (var item in list)
                    {
                        decimal tempMoney = model_order.TotalMoney.Value + (model_order.Freight ?? 0) - (model_order.PrivilegelMoney ?? 0);
                        tempMoney -= (model_order.IntegralMoney ?? 0);

                        if (item.RefundAmount > tempMoney)
                        {
                            return new Result(false, "申请退款金额不能大于" + tempMoney);
                        }

                        query.Add(new T_BAS_RefundApplys()
                        {
                            RefundApplyGuid = refundApplyGuid,
                            MerchantGuid = merchantGuid,
                            OrderGuid = item.OrderGuid,
                            OrderNo = model_order.OrderNo,
                            RefundType = item.RefundType,
                            IsSignIn = item.IsSignIn == 0 ? false : true,
                            IsRefund = item.IsRefund == 0 ? false : true,
                            Recipients = model_recieverAddress == null ? "" : model_recieverAddress.Reciever,
                            Telephone = model_recieverAddress == null ? "" : model_recieverAddress.Telephone,
                            RefundAddress = model_recieverAddress == null ? "" : model_recieverAddress.Province + model_recieverAddress.City + model_recieverAddress.Area + model_recieverAddress.Address,
                            RefundWay = model_order.TransactionID == "模拟支付" || model_order.TransactionID == "余额支付" || model_order.TransactionID == "商家支付" ? DictionaryConst.RefundWay.MerberBalance : DictionaryConst.RefundWay.WeChatAccount,
                            RefundAmount = item.RefundAmount,
                            ApplyDateTime = DateTime.Now,
                            RefundRemark = item.RefundRemark,
                            State = DictionaryConst.RefundState.Handling,
                            Account = "",
                            SerialNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3),
                            RefundOrderNo = OrderManage.GetOrderNO()
                        });
                        List<T_BAS_OrderDetails> list_detail = query_orderDetail.GetList(a => a.OrderGuid == item.OrderGuid);
                        foreach (var subItem in list_detail)
                        {
                            //如果存在退款订单明细则删除否则新增
                            query_details.Delete(a => a.OrderDetailGuid == subItem.OrderDetailGuid);
                            query_details.Add(new T_BAS_RefundOrderDetails()
                            {
                                RefundOrderDetailsGuid = Guid.NewGuid(),
                                RefundApplyGuid = refundApplyGuid,
                                OrderDetailGuid = subItem.OrderDetailGuid
                            });
                            query_orderDetail.Update(a => new Object[] {
                                a.State==DictionaryConst.OrderDetailState.Refunding
                            }, a => a.OrderDetailGuid == subItem.OrderDetailGuid);
                        }
                        model_order.OrderState = DictionaryConst.OrderState.Refunding;
                        query_order.Update(model_order);
                    }
                    #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 == 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 list_refundOrderdetail = query_produre.GetRefundOrder(refundApplyGuid);
                            string OpenID = MemberManage.GetMemberByOrderGuid(model_order.OrderGuid) == null ? "" : MemberManage.GetMemberByOrderGuid(model_order.OrderGuid).MemberOpenID;
                            if (list_refundOrderdetail != null && list_refundOrderdetail.Count > 0)
                            {
                                foreach (PT_BAS_OrderDetails_Refund item in list_refundOrderdetail)
                                {

                                    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("orderProductPrice", item.RefundAmount.ToString("0.00")));
                                    send.keys.Add(new Wechat.Model.TempateKey("orderProductName", item.ProductName));
                                    send.keys.Add(new Wechat.Model.TempateKey("orderName", model_order.OrderNo));
                                    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("订单退单发送模板消息出错:" + ex.Message);
                    }
                    #endregion
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }
        }

        public static T_BAS_RefundApplys GetEntity(Guid? refundApplyGuid)
        {
            using (var query = Factory.CreateT_BAS_RefundApplys())
            {
                var model = query.GetFirstData(a => a.RefundApplyGuid == refundApplyGuid);
                return model;
            }
        }

        /// <summary>
        /// 重新提交（删除该退款记录）
        /// </summary>
        /// <param name="refundApplyGuid"></param>
        /// <param name="merchantGuid"></param>
        /// <returns></returns>
        public static Result ReSubmit(Guid refundApplyGuid, Guid merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query = Factory.CreateT_BAS_RefundApplys(tran);
                    var query_detail = Factory.CreateT_BAS_RefundOrderDetails(tran);
                    tran.BeginTransaction();
                    List<T_BAS_RefundOrderDetails> dataList = query_detail.GetList(a => a.RefundApplyGuid == refundApplyGuid);
                    if (dataList != null && dataList.Count > 0)
                    {
                        query_detail.DeleteList(dataList);
                    }
                    query.Delete(a => a.RefundApplyGuid == refundApplyGuid && a.MerchantGuid == merchantGuid);
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="refundApplyGuid"></param>
        /// <param name="express"></param>
        /// <param name="expressNumber"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static Result Submit(Guid refundApplyGuid, string express, string expressNumber, Guid guid)
        {
            using (var query = Factory.CreateT_BAS_RefundApplys())
            {
                try
                {
                    query.Update(a => new Object[] {
                        a.Express==express,
                        a.ExpressNo==expressNumber,
                        a.State==DictionaryConst.RefundState.Shipped
                    }, a => a.RefundApplyGuid == refundApplyGuid);

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



        public static T_BAS_RefundApplys GetEntityByOrderGuid(Guid orderGuid)
        {
            using (var query = Factory.CreateT_BAS_RefundApplys())
            {
                return query.GetFirstData(a => a.OrderGuid == orderGuid);
            }
        }
        /// <summary>
        /// 判断是否已结算
        /// </summary>
        /// <param name="distributeGuid"></param>
        /// <returns></returns>
        public static bool ApprovedRefund(Guid? distributeGuid)
        {

            using (var query = Factory.CreateT_BAS_Distribute())
            {
                if (distributeGuid == null)
                {
                    return true;
                }
                var model = query.GetFirstData(a => a.DistributeGuid == distributeGuid);
                if (model == null)
                {
                    return true;
                }
                else
                {
                    if (model.IsSettlement == true)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
        }
        /// <summary>
        /// 判断是否已结算
        /// </summary>
        /// <param name="distributeGuid"></param>
        /// <returns></returns>
        public static bool ApprovedRefundByOrder(Guid? orderGuid)
        {

            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Distribute(tran);
                var model = query.GetFirstData(a => a.OrderGuid == orderGuid);
                if (model == null)
                {
                    return true;
                }
                else
                {
                    if (model.IsSettlement == true)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
        }

    }
}
