using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RFrameGenerate.BLL
{
    public class MessageTemplateManage
    {

        public static List<T_BAS_MessageTemplate> LoadData(Model.GridModel gridModel)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                return query.GetPageList(gridModel, a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, false, b => b.TemplateNo);
            }
        }
        /// <summary>
        /// 根据ID获取名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetTypeByID(int id)
        {
            return TemplateType.GetTypeName(id);
        }
        /// <summary>
        /// 获取分类
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static Result GetList(ref List<TemplateType> list)
        {
            list = TemplateType.TemplateTypeList();
            return new Result(true);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public static Result DelTemplate(Guid entityGuid)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                try
                {
                    query.Delete(a => a.MessageTemplateGuid == entityGuid);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result SaveTemplate(T_BAS_MessageTemplate model)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                try
                {
                    var template = query.GetFirstData(a => a.MessageTemplateGuid == model.MessageTemplateGuid && a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    if (template != null)
                    {
                        query.Update(a => new object[]
                        {
                            a.Content==model.Content,
                            a.MessageType==model.MessageType,
                            a.Received==model.Received,
                            a.TemplateID==model.TemplateID,
                            a.TemplateNo==model.TemplateNo,
                            a.TemplateType==model.TemplateType,
                        }, b => b.MessageTemplateGuid == model.MessageTemplateGuid);
                    }
                    else
                    {
                        model.MerchantGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid;
                        query.Add(model);
                    }
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        public static Result GetTemplate(int typeID, ref T_BAS_MessageTemplate entity)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                try
                {
                    entity = query.GetFirstData(a => a.TemplateType == typeID && a.MerchantGuid == Common.CurrentManage.MerchantGuid);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        public static string GetTemplateID(string templayteType)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                var template = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid && a.TemplateType == int.Parse(templayteType));
                if (template == null)
                    return null;
                else
                    return template.TemplateID;
            }
        }

        public static T_BAS_MessageTemplate GetTemplateMessage(string templateNo)
        {
            using (var query = Factory.CreateT_BAS_MessageTemplate())
            {
                var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                return query.GetFirstData(m => m.TemplateNo == templateNo && m.MerchantGuid == merchGuid);
            }
        }
        /// <summary>
        /// 分销佣金模板消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="templateID"></param>
        /// <param name="openId"></param>
        /// <param name="orderNo"></param>
        /// <param name="firstCommission"></param>
        /// <param name="appid"></param>
        public static void SendMessage_Commission(string userId, string templateID, string openId, string orderNo, decimal firstCommission, string appid)
        {
            try
            {
                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", orderNo));
                send.keys.Add(new Wechat.Model.TempateKey("keyword1", firstCommission.ToString("f2")));
                send.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。");
                weixinopen.WeiXinOpenRequest.SendMessageTemplate(openId, templateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", userId)) + "DistributionCenter/Index", send, appid);
            }
            catch (Exception err)
            {
                Wechat.LogManage.Log("WeiXinSync分销佣金模板消息出错:" + err.Message);
            }
        }

        public static void ScanSendMessage(string openid, Guid merGuid, Guid didGuid, string appid)
        {
            try
            {
                var member = MemberManage.GetMemberByOpenID(openid, merGuid);
                if (member != null && member.DID == null)
                {
                    var did = DistributionManage.GetDistributeionProp(didGuid);
                    if (did != null)
                    {
                        var memberreferrer = MemberManage.GetMemberByGuid(did.MemberGuid.Value);
                        if (memberreferrer != null)
                        {
                            MessageTemplateManage.ScanSendMessage(member.MerchantGuid.Value, member.MemberNickName, DateTime.Now, did.DistributionName, memberreferrer.MemberOpenID, appid);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("邀请关注成功通知,发送模板消息失败:" + ex.Message);
            }
        }

        static void ScanSendMessage(Guid merGuid, string memberName, DateTime scan, string referrer, string openid, string appid)
        {
            using (var querytemp = Factory.CreateT_BAS_MessageTemplate())
            {
                var template = querytemp.GetFirstData(a => a.MerchantGuid == merGuid && 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("keyword1", memberName));
                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", scan.ToString("yyyy/MM/dd HH:mm:ss")));
                    send.keys.Add(new Wechat.Model.TempateKey("keyword3", referrer));
                    send.remark = new Wechat.Model.TempateKey("remark", "如有疑问，请联系我们的客服，协助您处理！");
                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(openid, template.TemplateID, CurrentManage.CurrentDomainWx + "Order/Index", send, appid);
                }
            }
        }
    }
}
