using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Repository.User;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;

namespace Mall.Module.User
{
    public class RB_WeChatPublicAccountModule
    {
        /// <summary>
        /// 商户仓储层对象
        /// </summary>
        private readonly RB_WeChatPublicAccountRepository weChatPublicAccountRepository = new RB_WeChatPublicAccountRepository();

        /// <summary>
        /// 下单成功发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="OrderNo">订单编号</param>
        /// <param name="OrderCreate">下单时间</param>
        /// <param name="OrderPay">支付金额</param>
        /// <param name="GoodsName">商品</param>
        /// <returns></returns>
        public bool SendOrderSucceedMsg(int TenantId, int MallBaseId, string OrderNo, string OrderCreate, string CustomerName, string GoodsName)
        {
            var appletWeChatModel = weChatPublicAccountRepository.GetWeChatPublicAccountListRepository(new Model.Entity.User.RB_WeChatPublicAccount { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (appletWeChatModel == null || appletWeChatModel.ID == 0)
            {
                return false;
            }

            if (!AccessTokenContainer.CheckRegistered(appletWeChatModel.AppId))
            {
                AccessTokenContainer.RegisterAsync(appletWeChatModel.AppId, appletWeChatModel.Appsecret, "");
                System.Threading.Thread.Sleep(3000);
            }

            string access_token = "";
            try
            {
                access_token = AccessTokenContainer.GetAccessTokenResult(appletWeChatModel.AppId).access_token;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SendOrderSucceedMsg_1");
                try
                {
                    access_token = AccessTokenContainer.GetAccessTokenResult(appletWeChatModel.AppId).access_token;
                }
                catch (Exception exs)
                {
                    Common.Plugin.LogHelper.Write(exs, "SendOrderSucceedMsg_2");
                }
            }
            if (string.IsNullOrWhiteSpace(access_token))
            {
                return false;
            }
            string TemplateId = appletWeChatModel.OrderSuccessTpl;
            string linkUrl = "";
            var data = new
            {
                first = new
                {
                    value = "您收到了一条新的订单"
                },
                tradeDateTime = new
                {
                    value = OrderCreate
                },
                orderType = new
                {
                    value = "商品订单"
                },
                customerInfo = new
                {
                    value = CustomerName
                },
                orderItemName = new
                {
                    value = "订单信息"
                },
                orderItemData = new
                {
                    value = GoodsName
                },
                remark = new
                {
                    value = "订单号：" + OrderNo
                }
            };

            try
            {
                foreach (var item in appletWeChatModel.Openids.Split(","))
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        try
                        {
                            SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(access_token, item, TemplateId, linkUrl, data);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "SendOrderSucceedMsg_1");
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SendOrderSucceedMsg_2");
                return false;
            }
        }


        /// 下单取消发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="OrderNo">订单编号</param>
        /// <param name="CancelReason">取消原因</param>
        /// <param name="OrderMoney">订单金额</param>
        /// <param name="GoodsName">商品</param>
        /// <returns></returns>
        public bool SendOrderCancelMsg(int TenantId, int MallBaseId, string OrderNo, string OrderCreate, string OrderMoney)
        {
            var appletWeChatModel = weChatPublicAccountRepository.GetWeChatPublicAccountListRepository(new Model.Entity.User.RB_WeChatPublicAccount { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (appletWeChatModel == null || appletWeChatModel.ID == 0)
            {
                return false;
            }
            if (!AccessTokenContainer.CheckRegistered(appletWeChatModel.AppId))
            {
                AccessTokenContainer.RegisterAsync(appletWeChatModel.AppId, appletWeChatModel.Appsecret, "");
                System.Threading.Thread.Sleep(3000);
            }

            string access_token = "";
            try
            {
                access_token = AccessTokenContainer.GetAccessTokenResult(appletWeChatModel.AppId).access_token;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SendOrderCancelMsg_1");
                try
                {
                    access_token = AccessTokenContainer.GetAccessTokenResult(appletWeChatModel.AppId).access_token;
                }
                catch (Exception exs)
                {
                    Common.Plugin.LogHelper.Write(exs, "SendOrderCancelMsg_2");
                }
            }

            if (string.IsNullOrWhiteSpace(access_token))
            {
                return false;
            }
            string TemplateId = appletWeChatModel.OrderCancelTpl;
            string linkUrl = "";
            var data = new
            {
                first = new
                {
                    value = "您收到了一条新的订单取消"
                },
                keyword1 = new
                {
                    value = OrderNo
                },
                keyword2 = new
                {
                    value = OrderMoney
                },
                keyword3 = new
                {
                    value = OrderCreate
                },
                remark = new
                {
                    value = "请及时查看"
                }
            };

            try
            {
                foreach (var item in appletWeChatModel.Openids.Split(","))
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        try
                        {
                            SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(access_token, item, TemplateId, linkUrl, data);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "SendOrderCancelMsg_3");
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SendOrderCancelMsg_4");
                return false;
            }
        }

    }
}
