using Elasticsearch.Net;
using JiaZhiQuan.Common.ElasticSearch;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.Containers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using JiaZhiQuan.Common.Messaging;
using JiaZhiQuan.Common.Messaging.Models;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.Infrastructure.Repository;

namespace JiaZhiQuan.Common
{
    public static partial class RepositoryExtension
    {
        #region 寄售订单相关通知
        
        /// <summary>
        /// 寄售订单发货通知
        /// </summary>
        public static async Task MakePostOrderDeliverySuccessMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = "发货成功，请等待平台签收并鉴定。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单平台收货通知
        /// </summary>
        public static async Task MakePostOrderPlatformReceivedMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = "平台已收到您的寄售商品，正在火速安排鉴定。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            // TODO 公众号通知
        }
        
        /// <summary>
        /// 寄售订单平台鉴定通过，等待卖家上架通知，每24小时推送一次（TODO）
        /// </summary>
        public static async Task MakePostOrderWaitOnSaleMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = "您的寄售商品已通过鉴定，请尽快上架！超时未处理将退回商品。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单平台鉴定未通过，等待平台退货通知
        /// </summary>
        public static async Task MakePostOrderWaitReturnMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId, string reason)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您的寄售商品未通过鉴定，原因：{reason}。平台会尽快退回货物。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            // TODO 公众号通知
        }
        
        /// <summary>
        /// 寄售订单卖家取回商品（无偿），等待平台退货通知
        /// 寄售订单卖家取回商品 (有偿) ，等待平台退货通知
        /// 寄售订单卖家拒绝上架，等待平台退货通知
        /// 寄售订单卖家超时未上架，等待平台退货通知
        /// </summary>
        public static async Task MakePostOrderWaitReturnMessage2(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您主动取回了寄售商品，平台会尽快退回货物。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            // TODO 公众号通知
        }
        
        /// <summary>
        /// 寄售订单平台鉴定未通过，不退货，系统关闭订单通知
        /// </summary>
        public static async Task MakePostOrderRejectAndCloseMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId, string reason)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您的寄售商品未通过鉴定，且商品无法退回，原因：{reason}。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单商品上架通知
        /// </summary>
        public static async Task MakePostOrderOnSaleMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您的寄售商品已上架，正在火热出售中；适当降低售价会吸引更多买家。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单平台已退货，等待卖家签收
        /// </summary>
        public static async Task MakePostOrderReturnReceiveMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"平台退回了您的寄售商品，请留意物流进度并及时签收。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单卖家已签收退货，系统关闭订单通知
        /// </summary>
        public static async Task MakePostOrderAutoReceivedMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"退回的寄售商品已自动签收。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单销售订单关闭，重新上架中通知
        /// </summary>
        public static async Task MakePostOrderReOnSaleMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您的寄售商品因特殊原因交易失败，平台已重新上架该商品，并补偿额外的流量曝光，商品加速出售中。",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售订单关闭通知
        /// </summary>
        public static async Task MakePostOrderClosedMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId, string reason)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostOrder,
                Content = JsonConvert.SerializeObject(new UEPostOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"寄售已关闭；原因：{reason}",
                    ActionLink = $"app://ue/order/post/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        #endregion 寄售订单相关通知
        
        
        #region 寄售销售订单相关通知
        
        /// <summary>
        /// 寄售销售订单 买家已付款，等待平台发货
        /// </summary>
        public static async Task MakePostSaleOrderNeedDeliveryMessage(this DbRESTFulRepository repository, Producer producer, long saleOrderId, long orderId)
        {
            // TODO 公众号通知
            await Task.CompletedTask;
        }
        
        /// <summary>
        /// 寄售销售订单 买家超时未支付，系统关闭订单通知
        /// </summary>
        public static async Task MakePostSaleOrderPayExpireClosedMessage(this DbRESTFulRepository repository, Producer producer, long userId, long saleOrderId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostSaleOrder,
                Content = JsonConvert.SerializeObject(new UEPostSaleOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"因您超时未支付，订单已关闭。",
                    ActionLink = $"app://ue/order/postsale/detail?id={saleOrderId}&oid={orderId}",
                    OrderId = orderId,
                    SaleOrderId = saleOrderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售销售订单 平台已发货，等待买家签收
        /// </summary>
        public static async Task MakePostSaleOrderWaitBuyerReceiveMessage(this DbRESTFulRepository repository, Producer producer, long userId, long saleOrderId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostSaleOrder,
                Content = JsonConvert.SerializeObject(new UEPostSaleOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"平台已发货，请留意物流进度并及时签收。",
                    ActionLink = $"app://ue/order/postsale/detail?id={saleOrderId}&oid={orderId}",
                    OrderId = orderId,
                    SaleOrderId = saleOrderId,
                })
            });
        }
        
        /// <summary>
        /// 寄售销售订单 后台关闭订单
        /// </summary>
        public static async Task MakePostSaleOrderClosedMessage(this DbRESTFulRepository repository, Producer producer, long userId, long saleOrderId, long orderId, string reason, bool pointsUsed)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEPostSaleOrder,
                Content = JsonConvert.SerializeObject(new UEPostSaleOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"订单已关闭；原因：{reason}。货款稍后将全额退回至“原支付账户”。" + (pointsUsed ? "欧拉币已全额退回。" : ""),
                    ActionLink = $"app://ue/order/postsale/detail?id={saleOrderId}&oid={orderId}",
                    OrderId = orderId,
                    SaleOrderId = saleOrderId,
                })
            });
        }
        
        #endregion 寄售销售订单相关通知
        
        
        #region 挂售订单相关通知
        
        /// <summary>
        /// 挂售销售订单 买家已付款，选择快递收货，等待卖家发货
        /// </summary>
        public static async Task MakeHangSaleOrderWaitDeliveryMessage(this DbRESTFulRepository repository, Producer producer, long buyerId, long sellerId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerId,
                    Title = "订单通知",
                    Message = $"付款成功，卖家正在火速安排发货。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerId,
                    Title = "订单通知",
                    Message = $"您的挂售商品已有买家付款，买家选择快递收货，请尽快发货给买家！若因特殊原因无法发货，请联系平台客服。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 买家已付款，选择线下收货，等待买家取货
        /// </summary>
        public static async Task MakeHangSaleOrderWaitPickUpMessage(this DbRESTFulRepository repository, Producer producer, long buyerId, long sellerId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerId,
                    Title = "订单通知",
                    Message = $"付款成功，请在10天内前往门店取货，具体时间可与卖家商定。超时未取货将扣除您的取货保证金。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerId,
                    Title = "订单通知",
                    Message = $"您的挂售商品已有买家付款，买家将在10天内线下取货，请提前准备好商品，可与买家商定具体时间。请确保买家当面点击\"确认取货\"后，再取走商品！若因特殊原因无法提供商品，请联系平台客服。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 买家超时未支付，系统关闭订单
        /// </summary>
        public static async Task MakeHangSaleOrderPayExpireCloseMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"因您超时未支付，订单已关闭。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 卖家已发货，等待买家签收
        /// </summary>
        public static async Task MakeHangSaleOrderWaitReceiveMessage(this DbRESTFulRepository repository, Producer producer, long userId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = userId,
                    Title = "订单通知",
                    Message = $"您购买的商品已发货，请留意物流进度并及时签收。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 后台关闭订单
        /// </summary>
        public static async Task MakeHangSaleOrderPlatformClosedMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId, string reason)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerUserId,
                    Title = "订单通知",
                    Message = $"交易关闭，原因：{reason}。货款已全额退回至“原支付账户”。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"交易关闭，原因：{reason}。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 买家已取货，交易成功
        /// </summary>
        public static async Task MakeHangSaleOrderPickUpMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerUserId,
                    Title = "订单通知",
                    Message = $"您已取货，交易成功。取货保证金已全额退回至“原支付账户”。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"您的挂售商品交易成功，货款已打至“平台账户“。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }

        /// <summary>
        /// 挂售销售订单 买家拒绝取货，扣除保证金，交易关闭
        /// </summary>
        public static async Task MakeHangSaleOrderRefusePickUpClosedMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerUserId,
                    Title = "订单通知",
                    Message = $"您拒绝了取货，交易关闭。取货保证金已扣除，货款已全额退回至“原支付账户”。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"买家拒绝取货，交易关闭。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 买家超时未取货，扣除保证金，交易关闭
        /// </summary>
        public static async Task MakeHangSaleOrderExpirePickUpClosedMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerUserId,
                    Title = "订单通知",
                    Message = $"您超时未取货，交易关闭。取货保证金已扣除，货款已全额退回至“原支付账户”。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"买家超时未取货，交易关闭。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 后台关闭订单
        /// </summary>
        public static async Task MakeHangSaleOrderPlatformClosedMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId, bool returnBond, string reason)
        {
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = buyerUserId,
                    Title = "订单通知",
                    Message = returnBond ? $"交易关闭，原因：{reason}。货款与取货保证金稍后将全额退回至“原支付账户”。" : $"交易关闭，原因：{reason}。取货保证金已扣除，货款已全额退回至“原支付账户”。",
                    ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"交易关闭，原因：{reason}。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        /// <summary>
        /// 挂售销售订单 买家已签收，交易成功
        /// </summary>
        public static async Task MakeHangSaleOrderBuyerSignForMessage(this DbRESTFulRepository repository, Producer producer, long buyerUserId, long sellerUserId, long orderId, bool isAutoSignFor)
        {
            if (isAutoSignFor)
                await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
                {
                    Type = NotificationType.UEHangSaleOrder,
                    Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                    {
                        UserId = buyerUserId,
                        Title = "订单通知",
                        Message = $"您购买的商品已自动签收。",
                        ActionLink = $"app://ue/order/hangsale/detail?id={orderId}",
                        OrderId = orderId,
                    })
                });
            await producer.ProduceAsync(NotificationModel.GetMsgKey(), new NotificationModel
            {
                Type = NotificationType.UEHangSaleOrder,
                Content = JsonConvert.SerializeObject(new UEHangSaleOrderModel
                {
                    UserId = sellerUserId,
                    Title = "订单通知",
                    Message = $"您的挂售商品交易成功，货款已打至“平台账户“。",
                    ActionLink = $"app://ue/order/seller/hangsale/detail?id={orderId}",
                    OrderId = orderId,
                })
            });
        }
        
        #endregion 挂售订单相关通知
    }

}
