using ASHermed.AdminInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.App.Model;
using ASHermed.SinoInterface.Api.ContractModel.Coupon.Entity;
using ASHermed.SinoInterface.Api.ContractModel.Coupon.Model;
using ASHermed.SinoInterface.Api.ContractModel.Payment.Model;
using ASHermed.SinoInterface.Api.ContractModel.Payment.Param;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Api.IService.OnlineAptInfo;
using ASHermed.SinoInterface.Api.IService.Payment;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Enum;
using ASHermed.SinoInterface.Enum.App;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.Tools;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PoJun.Util.Maps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ASHermed.SinoInterface.Api.ContractModel.SMTP;
using ASHermed.SinoInterface.IFramework.SMTP;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 订单
	/// </summary>
	public class OrderService : BaseService, IOrderService
    {
        AppConfigurtaion _appConfigurtaion;
        RedisHelperClient _redisHelper;
        IOnlineOrderRepository _onlineOrderRepository;
        IDicDoctorRepository _dicDoctorRepository;
        IOnlineRefundRepository _onlineRefundRepository;
        ILinKingService _linKingService;
        IOnlineAptInfoService _onlineAptInfoService;
        IPrescriptionInfoRepository _prescriptionInfoRepository;
        IOnlineAptInfoRepository _onlineAptInfoRepository;
        IPubCouponFlowService _pubCouponFlowService;
        ITencentService _tencentService;
        IPubPatInfoRepository _pubPatInfoRepository;
        ISysRepository _sysRepository;
        IJpushService _jpushService;
        IPubMapUserPatRepository _pubMapUserPatRepository;
        ITCService _tCService;
        IDicDeptRepository _dicDeptRepository;
        ILogger<OrderService> _logger;
        IZhuTongSMSService _zhuTongSMSService;
        IOnlineCouponPubUserRepository _onlineCouponPubUserRepository;
        IOnlineCouponlogsRepository _onlineCouponlogsRepository;
        IOnlineCouponRepository _onlineCouponRepository;
        IVerifyCodeLogService _verifyCodeLogService;
        IDicMapDeptDoctorRepository _dicMapDeptDoctorRepository;
        ICouponService _couponService;
        IPubMessageService _pubMessageService;
        IPubUserInfoRepository _pubUserInfoRepository;
        IPubInsuranceRepository _pubInsuranceRepository;
        IPubUserAddressRepository _pubUserAddressRepository;
        IOnlineBillRepository _onlineBillRepository;
        IOnlineBillDetailRepository _onlineBillDetailRepository;
        IOnlineOrderSourceRepository _onlineOrderSourceRepository;
        IEmailService _emailService;
        IJGPushService _jGPushService;
        IAuthorizationService _authorizationService;

        /// <summary>
        /// 订单
        /// </summary>
        public OrderService(AppConfigurtaion appConfigurtaion, RedisHelperClient redisHelper, IOnlineOrderRepository onlineOrderRepository, IDicDoctorRepository dicDoctorRepository, IOnlineRefundRepository onlineRefundRepository, ILinKingService linKingService, IOnlineAptInfoService onlineAptInfoService, IPrescriptionInfoRepository prescriptionInfoRepository, IOnlineAptInfoRepository onlineAptInfoRepository, IPubCouponFlowService pubCouponFlowService, ITencentService tencentService, IPubPatInfoRepository pubPatInfoRepository, ISysRepository sysRepository, IJpushService jpushService, IPubMapUserPatRepository pubMapUserPatRepository, ITCService tCService, IDicDeptRepository dicDeptRepository, ILogger<OrderService> logger, IZhuTongSMSService zhuTongSMSService, IOnlineCouponPubUserRepository onlineCouponPubUserRepository, IOnlineCouponlogsRepository onlineCouponlogsRepository, IOnlineCouponRepository onlineCouponRepository, IVerifyCodeLogService verifyCodeLogService, IDicMapDeptDoctorRepository dicMapDeptDoctorRepository, ICouponService couponService, IPubMessageService pubMessageService, IPubUserInfoRepository pubUserInfoRepository, IPubInsuranceRepository pubInsuranceRepository, IPubUserAddressRepository pubUserAddressRepository, IOnlineBillRepository onlineBillRepository, IOnlineBillDetailRepository onlineBillDetailRepository, IOnlineOrderSourceRepository onlineOrderSourceRepository, IEmailService emailService, IJGPushService jGPushService, IAuthorizationService authorizationService)
        {
            _appConfigurtaion = appConfigurtaion;
            _redisHelper = redisHelper;
            _onlineOrderRepository = onlineOrderRepository;
            _dicDoctorRepository = dicDoctorRepository;
            _onlineRefundRepository = onlineRefundRepository;
            _linKingService = linKingService;
            _onlineAptInfoService = onlineAptInfoService;
            _prescriptionInfoRepository = prescriptionInfoRepository;
            _onlineAptInfoRepository = onlineAptInfoRepository;
            _pubCouponFlowService = pubCouponFlowService;
            _tencentService = tencentService;
            _pubPatInfoRepository = pubPatInfoRepository;
            _sysRepository = sysRepository;
            _jpushService = jpushService;
            _pubMapUserPatRepository = pubMapUserPatRepository;
            _tCService = tCService;
            _logger = logger;
            _dicDeptRepository = dicDeptRepository;
            _zhuTongSMSService = zhuTongSMSService;
            _onlineCouponPubUserRepository = onlineCouponPubUserRepository;
            _onlineCouponlogsRepository = onlineCouponlogsRepository;
            _onlineCouponRepository = onlineCouponRepository;
            _verifyCodeLogService = verifyCodeLogService;
            _dicMapDeptDoctorRepository = dicMapDeptDoctorRepository;
            _couponService = couponService;
            _pubMessageService = pubMessageService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _pubInsuranceRepository = pubInsuranceRepository;
            _pubUserAddressRepository = pubUserAddressRepository;
            _onlineBillRepository = onlineBillRepository;
            _onlineBillDetailRepository = onlineBillDetailRepository;
            _onlineOrderSourceRepository = onlineOrderSourceRepository;
            _emailService = emailService;
            _jGPushService = jGPushService;
            _authorizationService = authorizationService;
        }

        public BaseResponse<ResOrder> CreateOrder(OrderModel model)
        {
            BaseResponse<ResOrder> res = new BaseResponse<ResOrder>();
            if (model.DocId == 0)
            {
                res.Code = 0;
                res.Msg = "医生数据缺失";
                return res;
            }
            if (model.AptId == 0)
            {
                res.Code = 0;
                res.Msg = "未找到预约单信息";
                return res;
            }
            var type = string.IsNullOrEmpty(GetBaseUserInfo().U_Id) ? "sino" : "cigna";
            //获取服务价格  有科室获取对应价格 一一对应
            decimal price = _couponService.GetOrderPrice(model.AptType, 0, model.DocId, model.Language, "", type);
            //if (model.AptType == 1)
            //{
            //    var aptList = _dicDoctorRepository.GetVideoDoctorByDept(0, model.DocId, model.Language, "");
            //    if (aptList != null)
            //    {
            //        price = aptList.FirstOrDefault().Price;
            //    }

            //}
            //if (model.AptType == 2)
            //{
            //    var aptList = _dicDoctorRepository.GetReVisitDoctorByDept(0, model.DocId, model.Language, "");
            //    if (aptList != null)
            //    {
            //        price = aptList.FirstOrDefault().Price;
            //    }
            //}


            Online_Order order = new Online_Order();
            order.AptId = model.AptId;
            order.AptPrice = price;
            order.AptTime = model.AptTime;
            order.AptType = model.AptType;
            order.IsEnglish = model.Language == 2;
            order.CreateTime = DateTime.Now;
            order.DocId = model.DocId;
            order.OrderNo = GetOrderNo("GH", order.PayPrice);
            order.PatId = model.PatId;
            order.Remark = model.Remark;
            order.PayWay = model.PayWay;

            decimal couponPrice = 0;
            // 获取优惠券
            if (model.IsUseCoupon)
            {
                var coupons = _onlineCouponPubUserRepository.GetUserCoupons(model.PatId);
                //前端选择的优惠券是否存在，不存在直接返回
                var writeoffcoupon = coupons.Where(w => model.CouponId.Split(',').ToList().Contains(w.Id.ToString())).ToList();
                if (writeoffcoupon.Count != model.CouponId.Split(',').ToList().Count)
                {
                    res.Code = 0;
                    res.Msg = "此优惠券已被使用或不存在";
                    return res;
                }
                var veri = VerificationCoupon(writeoffcoupon, out couponPrice, model, order);
                if (!veri)
                {
                    res.Code = 0;
                    res.Msg = "此优惠券已被使用或不存在";
                    return res;
                }
                order.CouponPrice = couponPrice;
            }
            order.IsUseCoupon = model.IsUseCoupon;
            order.PayPrice = price - couponPrice;
            if (order.PayPrice < 0)
            {
                order.PayPrice = 0;//不能为负数
                order.PayWay = "";

            }
            //判断保险
            order.IsInsuranceUser = model.IsInsuranceUser;
            if (order.IsInsuranceUser)
            {//保险用户直接待审核
                order.InsuranceId = model.InsuranceId;
                var insur = _pubInsuranceRepository.GetPubInsuranceById(model.InsuranceId);
                order.InsuranceStatus = model.InsuranceStatus;//这里的订单保险状态 不要了
                if (insur.InsuranceStatus == 2)
                {
                    order.OrderStatus = 12;
                }
                else
                {
                    order.OrderStatus = 9;
                }
                order.PayWay = model.PayWay;
                order.PayPrice = 0;
                order.PayTime = DateTime.Now;
                //修改预约单保险状态
                //_onlineAptInfoRepository.UpdateAptInnerStatus(order.AptId, 1);
            }
            else
            {
                order.InsuranceStatus = 0;
                order.OrderStatus = 1;
            }
            var ret = _onlineOrderRepository.CreateOrder(order);
            if (order.PayPrice == 0)
            {//付款为0直接生成已付款订单(保险订单例外)
                if (!order.IsInsuranceUser)
                {
                    _onlineOrderRepository.AppPerfPayInfoByNo(order.OrderNo, DateTime.Now.ToString(), "", "2");
                    _onlineAptInfoService.UpdateAptStatus(order.AptId, 1);//修改预约单状态
                }
                CreateIMInfo(order);//创建视频咨询IM群和加复诊开药好友,预约推联空
                var aptInfo = _onlineAptInfoRepository.GetAptInfo(order.AptId);
                //向TC推预约
                try
                {
                    var pat = _pubPatInfoRepository.SelectById(order.PatId);
                    var tcret = _tCService.CommitApt(aptInfo.DeptId + "", aptInfo.AptProj + "", aptInfo.AptUsrn, aptInfo.AptUsrn, pat.Pat_ID);
                    _logger.LogInformation("接口:CreateOrder:ret-" + tcret + " AptUsrn" + aptInfo.AptUsrn + "");
                    if (!tcret)
                    {
                        //取消订单
                        var result = CancelOrder(order.OrderNo, true);
                        if (result.Code == 1)
                        {
                            OrderRefund(new RefundInfo() { OrderNo = order.OrderNo, RefundReason = "系统预约TC失败" });
                        }
                    }

                }
                catch (System.Exception ee)
                {
                    _logger.LogError("错误接口:PerfPayInfoByNo:" + ee.Message + "  OrderNo:" + order.OrderNo + "");
                    _tCService.LockApt(aptInfo.AptUsrn, aptInfo.AptUsrn, "U");
                }
                //修改优惠券使用记录
                _onlineCouponlogsRepository.UpdateOnlineCouponLogStatus(order.OrderNo, (int)CouponUserLogEnum.Success);
            }
            if (ret > 0)
            {
                if (order.IsInsuranceUser)
                {
                    var mhelper = _sysRepository.GetSysHelpers("保险审核员")?.FirstOrDefault();
                    _verifyCodeLogService.SendCignaSMS(mhelper.Phone, "有一条新的保险预约待审核,请及时审核");

                    //互联网医院cigna渠道有订单，发送邮件至precert@sinounitedhealth.com；邮件内容：互联网医院有新的订单，请及时处理
                    if (order.IsInsuranceUser)
                    {
                        var emailSendInput = new EmailSendInput
                        {
                            To = new List<string>
                            {
                                "precert@sinounitedhealth.com",
                                //"chen910735347@163.com"//测试环境陈艳磊的邮箱
                            },
                            Subject = "互联网医院复诊开药有新的订单，请及时审核保险",
                            TextBody = "互联网医院复诊开药有新的订单，请及时审核保险",
                        };

                        _emailService.Send(emailSendInput);
                    }
                }
                res.Code = 1;
                res.Msg = "成功";
                res.Data = new ResOrder() { OrderNo = order.OrderNo, Price = order.PayPrice };
            }
            else
            {
                res.Code = 0;
                res.Msg = "插入失败";
            }
            return res;
        }

        public BaseResponse<ResOrder> CreateOrderForSource(int language)
        {
            BaseResponse<ResOrder> response = new BaseResponse<ResOrder>();
            Online_Order_Source order = new Online_Order_Source();
            order.AptPrice = 49;
            order.AptType = 1;
            order.CouponId = 1314;
            order.CreateTime = DateTime.Now;
            order.IsEnglish = language == 2;
            order.IsUseCoupon = false;
            order.OrderNo = GetOrderNo("So", order.PayPrice);
            order.OrderStatus = 1;
            order.PayPrice = 49;
            order.UserId = GetBaseUserInfo().ID;
            var ret = _onlineOrderSourceRepository.CreateOrder(order);
            if (ret > 0)
            {
                response.Code = 1;
                response.Data = new ResOrder { OrderNo = order.OrderNo, Price = order.PayPrice };
            }
            return response;
        }

        public BaseResponse<string> OverOrder(string orderNo)
        {
            BaseResponse<string> res = new BaseResponse<string>();
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);
            if (order == null)
            {
                res.Code = 0;
                res.Msg = "未找到订单";
                return res;
            }
            var rets = 0;
            if (order.IsInsuranceUser)
            {
                rets = _onlineOrderRepository.UpdateOrder(orderNo, 10);
            }
            else
            {
                rets = _onlineOrderRepository.UpdateOrder(orderNo, 4);
            }
            _onlineAptInfoService.UpdateAptStatus(order.AptId, 5);
            res.Code = 1;
            res.Msg = "完成就诊";
            return res;
        }

        private string GetOrderNo(string head, decimal pay)
        {
            //var key = "OrderId" + DateTime.Now.ToString("yyyy-MM-dd");
            //var index = _redisHelper.GetIndex(key);
            var payStr = FullOrder(Convert.ToInt32(pay).ToString());
            var orderNo = head + DateTime.Now.ToString("yyyyMMddHHmmssfff") + payStr + GetRandoms(9);
            return orderNo;
        }
        private string FullOrder(string index)
        {
            if (index.Length >= 4)
            {
                return index;
            }
            else
            {
                index = "0" + index;
                return FullOrder(index);
            }
        }

        private string GetRandoms(int leng)
        {
            Random random = new Random();
            var retStr = string.Empty;
            for (int i = 0; i < leng; i++)
            {
                retStr += random.Next(0, 9);
            }
            return retStr;
        }
        public string PerfPayInfoByNo(string biz)
        {
            var retStr = "fail";
            var biz1 = JsonConvert.DeserializeObject<Biz_Content1>(biz);
            BaseResponse res = new BaseResponse();

            if (biz1 == null || string.IsNullOrEmpty(biz1.Out_trade_no))
            {
                return retStr;
            }
            //var order = _onlineOrderRepository.GetOrderByNo(biz1.Out_trade_no);
            var order = _onlineOrderSourceRepository.GetOrderSource(biz1.Out_trade_no);
            if (order == null)
            {
                return retStr;
            }
            if (order.OrderStatus != 1)
            {
                return "success";
            }
            if (order.PayPrice != biz1.Total_amount)
            {
                return retStr;
            }
            if (biz1.Trade_status != "TRADE_SUCCESS")
            {
                return retStr;
            }

            //确认付款后修改订单状态
            var ret = _onlineOrderSourceRepository.PerfPayInfoByNo(biz1.Out_trade_no, biz1.Payment_type, biz1.Gmt_payment, biz1.Trade_no, "4");
            if (ret > 0)
            {
                //通知有赞

                retStr = "success";
            }

            return retStr;
        }

        public string AppPerfPayInfoByNo(string response)
        {
            var retStr = "fail";
            var biz1 = JsonConvert.DeserializeObject<Biz_Content1>(response);
            BaseResponse res = new BaseResponse();

            if (biz1 == null || string.IsNullOrEmpty(biz1.Out_trade_no))
            {
                return retStr;
            }
            var order = _onlineOrderRepository.GetOrderByNo(biz1.Out_trade_no);
            if (order == null)
            {
                return retStr;
            }
            if (order.OrderStatus != 1)
            {
                return "success";
            }
            if (order.PayPrice != biz1.Total_amount)
            {
                return retStr;
            }
            if (biz1.Trade_status != "TRADE_SUCCESS")
            {
                return retStr;
            }
            var aptInfo = _onlineAptInfoRepository.GetAptInfo(order.AptId);

            //确认付款后修改订单状态
            var ret = _onlineOrderRepository.AppPerfPayInfoByNo(biz1.Out_trade_no, biz1.Gmt_payment, biz1.Trade_no, "2");
            var pat = _pubPatInfoRepository.SelectById(order.PatId);
            if (ret > 0)
            {
                if (biz1.Out_trade_no.Contains("GH"))
                {

                    //修改预约单状态
                    _onlineAptInfoService.UpdateAptStatus(order.AptId, 1);
                    //TC锁号 移回预约
                    //_tCService.LockApt(aptInfo.AptUsrn, aptInfo.AptUsrn, "L");

                }
                if (biz1.Out_trade_no.Contains("CF"))
                {
                    //修改处方单状态
                    _prescriptionInfoRepository.UpdatePrescriptionStatus(order.AptId, 1);
                }
                if (order.AptType == 1 || order.AptType == 2)
                {
                    CreateIMInfo(order);
                }
                if (order.AptType == 3)
                {
                    _onlineOrderRepository.UpdateOrder(order.OrderNo, 3);
                    try
                    {
                        //List<int> id = new List<int>();
                        //id.Add(order.AptId);
                        //var Prescription = _prescriptionInfoRepository.GetPrescriptionForIds(id).FirstOrDefault();
                        //var homeAddress = Prescription.Receipt_Address.Split('|')[0];
                        //var homeAddressDetail = Prescription.Receipt_Address.Split('|')[1];
                        //_linKingService.IFConfirmPrescriptionOrder(new PrescriptionOrderReq
                        //{
                        //    AccessToken = "Sino",
                        //    OpenUserID = order.PatId.ToString(),
                        //    PatientId = pat.Pat_MRN,
                        //    PrescriptionID = Prescription.Prescription_No,
                        //    ReceivingName = pat.Pat_Name,
                        //    HomeAddress = homeAddress,
                        //    HomeAddressDetail = homeAddressDetail,
                        //    Tel = Prescription.Patient_Tel,
                        //    DeliveryManner = 0,
                        //    OutTradeNo = order.OrderNo,
                        //    TradeNo = biz1.Trade_no,
                        //    Amount = order.PayPrice
                        //});

                        //发送短信
                        var userList = _sysRepository.GetSysUserList();
                        //string yaoZhuPhone = "15857396623";
                        if (userList.Any())
                        {
                            var phone = userList.Where(x => x.RoleName == "药助")?.FirstOrDefault()?.Phone;
                            _zhuTongSMSService.SendSMS(phone, "您收到一笔新的药物支付成功订单，请及时安排发货", true);
                        }
                        var openHelperId = _pubUserInfoRepository.GetMHelper("药助");
                        if (!string.IsNullOrEmpty(openHelperId))
                        {
                            var PreOrder = _prescriptionInfoRepository.GetPrescriptionForIds(new List<int>() { order.AptId })?.FirstOrDefault();
                            if (PreOrder != null)
                            {
                                _pubMessageService.SendOnlineWxMsg(PreOrder.Appt_Number, openHelperId, "您有一笔待发货的处方订单", "请及时前往[互联网医院工作站]去处理");
                            }
                        }

                    }
                    catch (System.Exception e) { }
                }

                //向TC推预约
                if (order.AptType != 3)
                {
                    try
                    {

                        var tcret = _tCService.CommitApt(aptInfo.DeptId + "", aptInfo.AptProj + "", aptInfo.AptUsrn, aptInfo.AptUsrn, pat.Pat_ID);
                        _logger.LogInformation("接口:PerfPayInfoByNo:ret-" + tcret + " AptUsrn" + aptInfo.AptUsrn + "");
                        if (!tcret)
                        {
                            //退款+取消订单
                            //_tCService.LockApt(aptInfo.AptUsrn, aptInfo.AptUsrn, "U");
                            var result = CancelOrder(order.OrderNo, true);
                            if (result.Code == 1)
                            {
                                OrderRefund(new RefundInfo() { OrderNo = order.OrderNo, RefundReason = "系统预约TC失败" });
                            }
                        }

                    }
                    catch (System.Exception ee)
                    {
                        _logger.LogError("错误接口:PerfPayInfoByNo:" + ee.Message + "  OrderNo:" + order.OrderNo + "");
                        _tCService.LockApt(aptInfo.AptUsrn, aptInfo.AptUsrn, "U");
                    }
                }

                //修改优惠券使用记录
                _onlineCouponlogsRepository.UpdateOnlineCouponLogStatus(biz1.Out_trade_no, (int)CouponUserLogEnum.Success);

                retStr = "success";
            }

            return retStr;
        }

        public void CreateIMInfo(Online_Order order)
        {
            if (order.IsInsuranceUser == false)
            {
                var aptInfo = _onlineAptInfoRepository.GetAptInfo(order.AptId);
                var user = _pubUserInfoRepository.SelectById(aptInfo.ApplyUserId);
                var helper = _sysRepository.GetSysHelpers("医助")?.FirstOrDefault();
                if (order.AptType == 1)
                {//视频咨询
                 //建群

                    var docImInfo = _pubPatInfoRepository.GetImIdByDocId(order.DocId);
                    //var helper = _sysRepository.GetDefaultHelper();
                    var group = _pubPatInfoRepository.IsExistGroup(user.ID, order.PatId, order.DocId);
                    if (group == null)
                    {
                        if (string.IsNullOrEmpty(user.IM_ID))
                        {
                            var tenRes = _tencentService.GetUsersigByPat(user.ID);
                            user.IM_ID = tenRes.UserId;
                        }
                        //极光推送给患者
                        PushUserMessage(user, "30", "您有一条新的消息", "您已成功预约,请至我的预约查看", string.Format("OrderDetail?orderNo={0}", order.OrderNo));
                        var reb = _tencentService.CreateTencentGroup(order.DocId + "-" + order.PatId, docImInfo.IMID, user.IM_ID, order.AptId, helper.ImId);
                        if (reb.ActionStatus == "OK")
                        {
                            _pubPatInfoRepository.InsertGroupInfo(reb.GroupId, user.ID, order.PatId, order.DocId, helper.Id, order.OrderNo);
                            SendGroupMessage(reb.GroupId, helper.ImId, order);
                        }

                    }
                    else
                    {
                        //更新群绑定的orderNo
                        group.OrderNo = order.OrderNo;
                        _pubPatInfoRepository.UpdateGroupOrder(group);
                        //多对多修改全部群绑定的orderNo
                        //_pubPatInfoRepository.SynchroGroupOrder(order.PatId, order.DocId, order.OrderNo);
                        //之前的群 禁言了  现在解除
                        var reb = _tencentService.ForbiddenUser(group.GroupId, user.IM_ID, false);
                        if (reb.ActionStatus == "OK")
                        {
                            _pubPatInfoRepository.GroupForbiddenUser(group.GroupId, false);
                        }

                        //极光推送给患者
                        PushUserMessage(user, "30", "您有一条新的消息", "您已成功预约,请至我的预约查看", string.Format("OrderDetail?orderNo={0}", order.OrderNo));
                        SendGroupMessage(group.GroupId, helper.ImId, order);

                    }
                    _tencentService.AddMessage(order.PatId, user.ID, 4, order.DocId + "", "预约提醒", 0);
                }
                if (order.AptType == 2)
                {
                    try
                    {
                        var reb = _tencentService.FriendAdd(user.IM_ID, new List<string> { helper.ImId });
                        SendFriendMessage(helper.ImId, user.IM_ID, order.PatId, order.DocId, order.AptId, order.OrderNo);
                        _onlineAptInfoRepository.UpdatePubUserInfoIsRead(user.ID, true, order.AptType);
                    }
                    catch (System.Exception e)
                    { }
                }

                var userInfo = _pubUserInfoRepository.SelectByPhone("15618328631");//TODO 写死的东西  后面再说
                if (!string.IsNullOrEmpty(userInfo.Open_ID) && order.IsInsuranceUser == false)
                {
                    _logger.LogInformation("888:" + userInfo.Open_ID);
                    _pubMessageService.SendOnlineWxMsg(order.OrderNo, userInfo.Open_ID, "你收到一笔新的线上问诊订单，请及时处理", "前往[互联网医院工作站]处理", "");
                }
            }
            if (order.AptType == 1 || order.AptType == 2)
            {
                try
                {
                    //复诊开药订单推联空
                    AptOrderConfirm(new ReVisitComfirm { OrderNo = order.OrderNo });
                }
                catch (System.Exception e)
                { }
            }
        }

        private void SendGroupMessage(string groupId, string fromWho, Online_Order order)
        {
            var msg1 = new object();
            if (order.IsEnglish)
            {
                msg1 = new { messageType = "systomNotice", content = "Appointment booked. Tap to see order details", url = "OrderDetail?orderNo=" + order.OrderNo + "&hidden=1" };
            }
            else
            {
                msg1 = new { messageType = "systomNotice", content = "您已成功预约,点击查看订单详情", url = "OrderDetail?orderNo=" + order.OrderNo + "&hidden=1" };
            }
            _tencentService.SendCusMsgToGroup(groupId, fromWho, JsonConvert.SerializeObject(msg1));
            var dept = _dicDeptRepository.GetOnlineDeptByDoc(order.DocId);
            List<MaterialDept> needMaterialDepts = GetMaterialDepts();
            var needDept = needMaterialDepts.Find(p => p.DeptId == dept.DeptId);
            if (needDept != null)
            {//发自定义材料信息

                var msg2 = new { messageType = "addDate", url = "AddDataViews?patientId=" + order.PatId + "&doctorId=" + order.DocId + "&DepartmentId=" + needDept.DeptId + "&Department=" + needDept.NameEn + "&AptId=" + order.AptId };
                _tencentService.SendCusMsgToGroup(groupId, fromWho, JsonConvert.SerializeObject(msg2));
            }
            else
            {
                var msg2 = new { messageType = "addDate", url = "AddDataViews?patientId=" + order.PatId + "&doctorId=" + order.DocId + "&DepartmentId=" + dept.DeptId + "&Department=Family&AptId=" + order.AptId };
                _tencentService.SendCusMsgToGroup(groupId, fromWho, JsonConvert.SerializeObject(msg2));
            }
        }

        private void SendFriendMessage(string fromWho, string toWho, int patId, int docId, int aptId, string orderNo)
        {
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);
            var content = "您已成功预约,点击查看订单详情";
            var title = "支付成功";
            if (order.IsEnglish)
            {
                content = "Your order has been submitted. Tap to see details.";
                title = "Payment Success";
            }
            var msg = new { messageType = "cardNotice", title = title, content = content, url = "OrderDetail?orderNo=" + orderNo + "&hidden=1" };
            _tencentService.SendFriendMsg(fromWho, toWho, JsonConvert.SerializeObject(msg));
            var dept = _dicDeptRepository.GetOnlineDeptByDoc(docId);
            List<MaterialDept> needMaterialDepts = GetMaterialDepts();
            var needDept = needMaterialDepts.Find(p => p.DeptId == dept.DeptId);
            if (needDept != null)
            {//发自定义材料信息

                var fmsg = new { messageType = "addDate", url = "AddDataViews?patientId=" + patId + "&doctorId=" + docId + "&DepartmentId=" + needDept.DeptId + "&Department=" + needDept.NameEn + "&AptId=" + aptId };
                _tencentService.SendFriendMsg(fromWho, toWho, JsonConvert.SerializeObject(fmsg));
            }
            else
            {
                var fmsg = new { messageType = "addDate", url = "AddDataViews?patientId=" + patId + "&doctorId=" + docId + "&DepartmentId=" + dept.DeptId + "&Department=Family&AptId=" + aptId };
                _tencentService.SendFriendMsg(fromWho, toWho, JsonConvert.SerializeObject(fmsg));
            }

        }

        private List<MaterialDept> GetMaterialDepts()
        {
            List<MaterialDept> needMaterialDepts = new List<MaterialDept>();//全科/内科/皮肤科/精神科/儿科(这个应该有个地方需要配置TODO){ 17, 23, 1053, 1048, 1055 }
            needMaterialDepts.Add(new MaterialDept { DeptId = 17, NameEn = "Family" });
            needMaterialDepts.Add(new MaterialDept { DeptId = 23, NameEn = "Family" });
            needMaterialDepts.Add(new MaterialDept { DeptId = 1053, NameEn = "Dermatology" });
            needMaterialDepts.Add(new MaterialDept { DeptId = 1048, NameEn = "Psychiatry" });
            needMaterialDepts.Add(new MaterialDept { DeptId = 1055, NameEn = "Pediatrics" });
            return needMaterialDepts;
        }

        private string GetDeptEnName(int deptId)
        {
            var name = "Family";
            switch (deptId)
            {
                case 1053:
                    return "Dermatology";
                case 1048:
                    return "Psychiatry";
                case 1055:
                    return "Pediatrics";
                default:
                    return name;
            }
        }

        public bool PushUserMessage(Pub_User_Info user, string jgPushType, string title, string content, string url = "")
        {
            if (user == null)
            {
                return false;
            }
            var list = new List<string>();
            string accptMd = string.Empty;
            if (user.Key_Type == 1)
            {
                list.Add(user.Android_ID);
                accptMd = "3";
            }
            if (user.Key_Type == 2)
            {
                list.Add(user.IOS_ID);
                accptMd = "2";
            }
            if (list.Count > 0)
            {
                var res = _jpushService.JiGuangPush(list.ToArray(), title, content, jgPushType, user.ID.ToString(), "0", accptMd, 1, url);
                _logger.LogInformation("9988:设备号" + list[0] + "    userid:" + user.ID + "ret:" + res.StatusCode);
                return res.StatusCode == HttpStatusCode.OK;
            }
            return false;
        }

        //public List<Online_Order> GetAllOrder()
        //{
        //    var user = _pubMapUserPatRepository.SelectByPatId
        //    var order = _onlineOrderRepository.GetAllOrder();

        //}


        public PageListModel<OrderListModel> GetOrderList(OrderListReq req)
        {
            var pats = new List<int>();
            var user = GetBaseUserInfo();
            if (!string.IsNullOrEmpty(user.U_Id))
            {
                if (req.Pat == 0)
                {
                    pats = _pubPatInfoRepository.GetPatIdsByUserId(user.ID).Select(w => w.Id).ToList();
                }
                else
                {
                    pats.Add(req.Pat);
                }
                var ret = _onlineOrderRepository.GetOrderList(req, pats);
                ret.PageList = ret.PageList.FindAll(p => p.AptType != 3 && p.IsInsuranceUser == true);
                return ret;
            }
            else
            {
                List<Pub_Pat_Info> patList = _authorizationService.GetUserAuthPats(user.ID, (int)AuthType.ONLINEORDER);
                if (req.Pat == 0)
                {
                    pats = patList.Select(w => w.Id).ToList();
                }
                else
                {
                    if (!patList.Where(w => w.Id == req.Pat).Any())
                    { pats = new List<int>(); }
                    else
                    {
                        pats.Add(req.Pat);
                    }
                }
                var ret = _onlineOrderRepository.GetOrderList(req, pats);
                var presInfo = _prescriptionInfoRepository.GetPrescriptionForIds(ret.PageList.Select(w => w.AptId).ToList());
                try
                {
                    ret.PageList.ForEach(w =>
                    {
                        if (w.AptType == 3)
                        {
                            w.OrderNo = presInfo.Where(f => f.Id == w.AptId).FirstOrDefault()?.Appt_Number;
                        }
                    });
                    ret.PageList = ret.PageList.Where(w => !string.IsNullOrEmpty(w.OrderNo)).ToList();
                }
                catch (System.Exception e) { }
                return ret;
            }
        }

        public OrderDetailModel GetOrderDetail(string orderNo, int language)
        {
            var ret = _onlineOrderRepository.GetOrderDetail(orderNo, language);
            var helper = _sysRepository.GetSysHelpers("医助")?.FirstOrDefault();
            ret.HelperImId = helper.ImId;
            if (ret == null)
            {
                return null;
            }
            switch (ret.AptType)
            {
                case 1:
                    ret.Notice = _appConfigurtaion.AptType1;
                    break;
                case 2:
                    ret.Notice = _appConfigurtaion.AptType2;
                    break;
                case 3:
                    ret.Notice = _appConfigurtaion.AptType3;
                    ret.PrescriptionInfo = new ContractModel.App.Model.MyPrescriptionList();
                    var info = _prescriptionInfoRepository.GetPrescription(GetBaseUserInfo().ID, 0, ret.AptId).FirstOrDefault();
                    List<string> list = new List<string>();
                    list.Add(info.Prescription_No);
                    var de = _prescriptionInfoRepository.GetPrescriptionDrug(list).ToList();
                    ret.PrescriptionInfo = info.MapTo<MyPrescriptionDetail>();
                    ret.PrescriptionInfo.Detail = de.Where(f => f.Prescripton_No == ret.PrescriptionInfo.Prescription_No).ToList();
                    break;
                default:
                    ret.Notice = _appConfigurtaion.AptType3;
                    break;
            }
            if (ret.OrderStatus == 6)
            {
                var refund = _onlineRefundRepository.GetRefundOrder("T" + ret.OrderNo);
                if (refund != null)
                {
                    ret.RefundPayTime = refund.RefundTime;
                    ret.RefundPayWay = ret.PayWay;
                }
            }
            if (ret.OrderStatus == 4)
            {
                var comment = _onlineOrderRepository.GetOrderComment(ret.OrderNo);
                if (comment != null)
                {
                    ret.CommentId = comment.Id;
                    ret.CommentInfo = comment;
                }
                else
                {
                    ret.CommentId = 0;
                }
            }
            //寻找互联网医生科室  (可优化)
            var videoList = _dicDoctorRepository.GetVideoDoctorByDept(0, ret.DocId, language, "");
            var revisitlist = _dicDoctorRepository.GetReVisitDoctorByDept(0, ret.DocId, language, "");
            if (videoList != null && videoList.Count > 0)
            {
                var video = videoList.FirstOrDefault();
                ret.DeptName = video.DeptName;
            }
            if (revisitlist != null && revisitlist.Count > 0)
            {
                var revisit = revisitlist.FirstOrDefault();
                ret.DeptName = revisit.DeptName;
            }

            //如果linking状态为进行中，预约状态为已确认，那么预约单状态改为就诊中
            if (ret.LinKingAptStatus == 8 && (ret.Status == 2 || ret.Status == 4))
            {
                ret.Status = 6;
            }
            if (ret.IsInsuranceUser)
            {
                ret.InsuranceInfo = _pubInsuranceRepository.GetPubInsuranceById(ret.InsuranceId);
            }
            return ret;
        }

        public string GetRefundNo(Online_Order order, string user)
        {
            var refundNo = "T" + order.OrderNo;
            Online_Refund refund = new Online_Refund();
            refund.OrderNo = order.OrderNo;
            refund.CreateTime = DateTime.Now;
            refund.Operator = user;
            refund.RefundFee = 0;
            refund.RefundNo = refundNo;
            var res = _onlineRefundRepository.CreateRefundOrder(refund);
            return refundNo;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderNo"></param>
        ///  /// <param name="isForce">强制退款</param>
        /// <returns></returns>
        public BaseResponse CancelOrder(string orderNo, bool isForce = false)
        {
            BaseResponse res = new BaseResponse();
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);
            if (order == null)
            {
                res.Code = 0;
                res.Msg = "未找到订单";
                return res;
            }
            if (!isForce)
            {
                if (order.OrderStatus != 1 && order.OrderStatus != 2 && order.OrderStatus != 3 && order.OrderStatus != 9 && order.OrderStatus != 10)
                {
                    res.Code = 0;
                    res.Msg = "该订单无法取消";
                    return res;
                }
                if ((order.OrderStatus == 2 || order.OrderStatus == 3) && order.AptTime < DateTime.Now.AddHours(24))
                {
                    res.Code = 0;
                    res.Msg = "24小时内的订单无法取消";
                    return res;
                }
            }

            var rets = _onlineOrderRepository.UpdateOrder(orderNo, 5);
            if (order.OrderNo.Contains("GH"))
            {
                //修改预约单状态
                _onlineAptInfoService.UpdateAptStatus(order.AptId, 3);
                if (order.AptType == 1 || order.AptType == 2)
                {
                    //通知联空修改预约单状态
                    _linKingService.IFUpdateReVisitStatus(new ContractModel.Payment.Param.UpdateReVisitReq() { AccessToken = "Sino", OutTradeNo = order.OrderNo, StatusDiv = 98 });
                }
                //挂号的 需要 解锁号源(解号)
                var usrn = _onlineAptInfoService.GetAptUsrn(order.AptId);
                if (order.OrderStatus == 1)
                {
                    var unlockUsrn = _tCService.LockApt(usrn, usrn, "U");
                    _logger.LogInformation("unlockUsrn:usrn " + usrn + "解锁返回: " + unlockUsrn);
                }
                else
                {
                    var tcret = _tCService.CancelAppt(usrn, usrn);
                    _logger.LogInformation("CancelAppt:usrn " + usrn + "取消返回: " + tcret);
                }

            }
            if (order.OrderNo.Contains("CF"))
            {
                //修改处方单状态
                _prescriptionInfoRepository.UpdatePrescriptionStatus(order.AptId, -1);
            }
            //修改完预付单后 付款账单需退款
            if (order.OrderStatus == 2 || order.OrderStatus == 3)
            {
                rets = _onlineOrderRepository.UpdateOrder(orderNo, 8);
            }

            //取消订单返回订单生成时的优惠券
            var couponlog = _onlineCouponlogsRepository.GetOnlineCouponLogListForOrderNo(orderNo);
            _onlineCouponPubUserRepository.UpdateCouponPubUserStatus(couponlog.Select(w => w.CouponPubUserId).ToList(), (int)CouponUserEnum.NotUsed);
            _onlineCouponlogsRepository.DeleteOnlineCouponLogListForOrderNo(orderNo);

            if (rets > 0)
            {
                res.Code = 1;
                res.Msg = "取消订单成功";
            }

            return res;
        }

        public BaseResponse CommentOrder(OrderCommentReq req)
        {
            BaseResponse res = new BaseResponse();
            req.CreateUser = GetBaseUserInfo().Nick_Name;
            req.UserId = GetBaseUserInfo().ID;
            var comment = _onlineOrderRepository.GetOrderComment(req.OrderNo);
            if (comment != null)
            {
                var inset = _onlineOrderRepository.UpdateComment(req);
                if (inset > 0)
                {
                    res.Code = 1;
                    res.Msg = "评价成功";
                }
            }
            else
            {
                var inset = _onlineOrderRepository.CommentOrder(req);
                if (inset > 0)
                {
                    res.Code = 1;
                    res.Msg = "评价成功";
                }
            }
            return res;
        }

        public BaseResponse InsuranceOrderSign(InsuranceOrderSignReq req)
        {
            BaseResponse res = new BaseResponse();
            var ret = _onlineOrderRepository.InsuranceOrderSign(req);//修改挂号订单状态为完成
            var prescription = _prescriptionInfoRepository.GetPrescriptionForId(req.OrderNo);
            if (prescription != null)
            {
                _onlineOrderRepository.UpdateCFOrder(prescription.Id, 11);//修改处方订单状态为完成
                var address = _pubUserAddressRepository.GetAddressForId(req.AddressId);
                if (address != null)
                {
                    _prescriptionInfoRepository.UpdateReceipt(prescription.Id, address.ReceiveName, address.ReceivePhone, address.Province + address.City + address.Area + "|" + address.Localization);
                    //new Pub_Deliver_Address() { Address = address.Address, OrderNo = req.OrderNo, ReceiveName = address.ReceiveName, ReceivePhone = address.ReceivePhone }
                }
                _prescriptionInfoRepository.UpdatePrescriptionStatus(prescription.Id, 1);
            }
            var mhelper = _sysRepository.GetSysHelpers("药助")?.FirstOrDefault();
            _verifyCodeLogService.SendCignaSMS(mhelper.Phone, "您收到一笔新的药物支付成功订单，请及时安排发货(保险客户)");
            if (ret > 0)
            {
                CreateBill(req.OrderNo);
                res.Code = 1;
                res.Msg = "签名成功";
            }
            return res;
        }

        public int CreateBill(string orderNo)
        {
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);

            var aptInfo = new Online_Apt_Info();
            if (orderNo.Contains("CF"))
            {
                aptInfo = new Online_Apt_Info { };
            }
            else
                aptInfo = _onlineAptInfoRepository.GetAptInfo(order.AptId);

            List<Online_Bill_Detail> billdetail = new List<Online_Bill_Detail>();
            Online_Bill bill = new Online_Bill();
            bill.BillNo = GetBillNo();
            if (order.IsInsuranceUser)
            {
                bill.AptType = 0;
                bill.BillPrice = order.AptPrice;
                bill.BillType = (int)BillTypeEnum.InsurBill;
                bill.ChannelCode = (int)BillChannelEnum.Cigna;
                bill.ChannelPayType = (int)BillPayEnum.CignaCover;
                bill.ConsultationFee = order.AptPrice;
            }
            else
            {
                bill.AptType = order.AptType;
                bill.BillPrice = order.PayPrice;
                bill.BillType = (int)BillTypeEnum.PayBill;
                bill.ChannelCode = (int)BillChannelEnum.Sino;
                bill.ChannelPayType = (int)BillPayEnum.PatientPay;
                if (order.AptType == 1 || order.AptType == 2)
                {
                    bill.ConsultationFee = order.PayPrice;
                }
                else
                {
                    bill.ConsultationFee = 0;
                }
                billdetail.Add(new Online_Bill_Detail
                {
                    CreateUser = "sys",
                    BillDetailType = (order.AptType == 1 || order.AptType == 2) ? 1 : 2,
                    BillDetailPrice = order.PayPrice,
                    BillNo = bill.BillNo,
                    BillPayType = 1,
                    CreateTime = DateTime.Now,
                    Remark = (order.AptType == 1 || order.AptType == 2) ? "诊费收取" : "药费收取"
                });
            }
            bill.BillCreateTime = DateTime.Now;
            bill.DeptId = aptInfo.DeptId;
            bill.DocId = aptInfo.DocId;
            if (order.AptType == 3 && !order.IsInsuranceUser)
            {
                bill.PrescriptionOrderNo = orderNo;
            }
            else
            {
                bill.OrderNo = order.OrderNo;
            }
            bill.PatId = order.PatId;
            var prescription = _prescriptionInfoRepository.GetPrescriptionForId(orderNo);
            if (prescription != null)
            {
                var prescriptionOrder = _onlineOrderRepository.GetOrderDetailForPrescriptionAptId(prescription.Id);
                bill.BillPrice += prescription.Total_Amount;
                bill.DrugCost = prescription.Total_Amount;
                bill.PrescriptionOrderNo = prescriptionOrder.OrderNo;
            }
            _onlineBillDetailRepository.InsertOnlineBillDetail(billdetail);
            return _onlineBillRepository.InsertOnlineBill(bill);
        }

        private string GetBillNo()
        {
            var billNo = "INV" + DateTime.Now.ToString("yyMMdd");
            var key = "BillId" + DateTime.Now.ToString("yyyy-MM-dd");
            var index = _redisHelper.GetIndex(key);
            billNo += FullBill(index);
            billNo += "-SUO";
            return billNo;
        }

        private string FullBill(string index)
        {
            if (index.Length >= 4)
            {
                return index;
            }
            else
            {
                index = "0" + index;
                return FullBill(index);
            }
        }

        public int UpdateOrderStatus(string orderNo, int status)
        {
            return _onlineOrderRepository.UpdateOrder(orderNo, status);
        }

        /// <summary>
        /// job使用
        /// </summary>
        /// <returns></returns>
        public List<string> GetCancelOrders()
        {
            return _onlineOrderRepository.GetCancelOrders();
        }

        public List<string> GetCancelOrderSource()
        {
            return _onlineOrderSourceRepository.GetCancelOrderSource();
        }

        public void UpdateOrderSourceStatus(string orderNo, int status)
        {
            _onlineOrderSourceRepository.UpdateOrderSourceStatus(orderNo, status, "", 0);
        }

        public string GetGroupOrderNo(string groupId)
        {
            return _onlineOrderRepository.GetGroupOrderNo(groupId);
        }


        //订单推联空
        public BaseResponse AptOrderConfirm(ReVisitComfirm info)
        {
            BaseResponse res = new BaseResponse();
            var order = _onlineOrderRepository.GetOrderByNo(info.OrderNo);
            if (order == null)
            {
                res.Code = 0;
                res.Msg = "参数错误:未找到对应订单";
                return res;
                //throw new BaseException("参数错误:未找到对应订单", DetailedStatusCode.Fail);
            }
            var pat = _pubPatInfoRepository.SelectById(order.PatId);
            if (pat == null)
            {
                res.Code = 0;
                res.Msg = "参数错误:未找到患者信息";
                return res;
                //throw new BaseException("参数错误:未找到患者信息", DetailedStatusCode.Fail);
            }
            if (string.IsNullOrEmpty(pat.Card_ID))
            {
                res.Code = 0;
                res.Msg = "参数错误:患者缺少证件信息";
                return res;
                //throw new BaseException("参数错误:患者缺少证件信息", DetailedStatusCode.Fail);
            }
            var atpInfo = _onlineAptInfoRepository.GetAptInfoById(order.AptId);
            //atpInfo.AptTime = DateTime.Parse(atpInfo.AptTime.ToString()).AddDays(-1);
            if (atpInfo == null)
            {
                res.Code = 0;
                res.Msg = "参数错误:未找到预约信息";
                return res;
            }
            ReVisitComfirmParam param = new ReVisitComfirmParam();
            param.AccessToken = "Sino";
            param.Amount = order.PayPrice.ToString();//需确认是否传钱
            param.CardNo = string.IsNullOrEmpty(pat.Clinic_Card) ? "" : pat.Clinic_Card;
            param.CardType = string.IsNullOrEmpty(pat.Clinic_CardType) ? "" : pat.Clinic_CardType;
            param.CertType = pat.Card_Type + "";
            param.DeptCode = atpInfo.DeptId + "";
            param.DeptName = "";
            param.Description = atpInfo.Description;
            //if (string.IsNullOrEmpty(pat.Pat_MRN))  TODO
            //{
            param.DiagnosisDetails = "{\"itemCode\":\"\",\"itemName\":\"\"}";
            //}
            param.DoctorId = atpInfo.DocCode;
            try
            {
                param.DoctorName = string.IsNullOrEmpty(atpInfo.DocName) ? "" : atpInfo.DocName.Split(' ')[0];
            }
            catch (System.Exception ex) { }
            //如果是护照，动态拼接身份证给联空
            if (pat.Card_Type != 1)
            {
                var d = DateTime.Parse(pat.Birthday).ToString("yyyyMMdd");
                pat.Card_ID = "430902" + d + "8017";
                _logger.LogInformation("修改前:" + pat.Birthday + "修改身份证为:" + pat.Card_ID);
            }
            param.IDCard = pat.Card_ID;
            param.Image = atpInfo.DescImage;
            param.OpenUserID = pat.Id + "";
            param.OutTradeNo = order.OrderNo;
            param.AptType = order.AptType;
            param.PatientID = string.IsNullOrEmpty(pat.Pat_MRN) ? "P0" : pat.Pat_MRN;
            param.PatientName = pat.Pat_Name;
            param.RegistDate = Convert.ToDateTime(atpInfo.AptTime).ToString("yyyy-MM-dd");
            param.RegistTime = Convert.ToDateTime(atpInfo.AptTime).ToString("HH:mm");
            param.ResourceID = GetRandoms(11);
            param.Tel = pat.Phone_NO;
            param.TradeNo = order.TradeNo;
            param.IsInsuranceUser = order.IsInsuranceUser;
            param.IsEnglish = order.IsEnglish;
            _logger.LogInformation("AptOrderConfirm Request:" + JsonConvert.SerializeObject(param));
            var reb = _linKingService.IFGetReVisitComfirmReservation(param);
            _logger.LogInformation("AptOrderConfirm Response:" + JsonConvert.SerializeObject(reb));
            if (reb.IsSuccess)
            {
                _pubPatInfoRepository.UpdatePatClinicCard(pat.Id, reb.CardNo, reb.CardType);
                res.Code = 1;
                res.Msg = "推送成功";
            }
            else
            {
                res.Code = 0;
                res.Msg = "推送失败";
            }
            return res;
        }

        public List<TreatedInfo> GetReadyApt(int language)
        {
            if (GetBaseUserInfo() == null)
            {
                return new List<TreatedInfo>();
            }
            var authpats = _authorizationService.GetUserAuthPats(GetBaseUserInfo().ID, 2);
            var myApt = _onlineAptInfoRepository.GetReadyApt(authpats.Select(w => w.Id).ToList(), GetBaseUserInfo().ID);
            //var docs = _dicDoctorRepository.GetAllOnlineDeptDocInfo();
            var docs = _dicDoctorRepository.GetAllDoctor();
            var depts = _dicDeptRepository.SelectByLanguage(language);
            if (myApt != null && myApt.Count > 0)
            {
                foreach (var item in myApt)
                {

                    //如果linking状态为进行中，预约状态为已确认，那么预约单状态改为就诊中
                    if (item.LinKingAptStatus == 8 && (item.Status == 2 || item.Status == 4))
                    {
                        item.Status = 6;
                    }

                    item.SeeDoctorTime = Convert.ToDateTime(item.SeeDoctorTime).ToString("yyyy-MM-dd HH:mm");
                    var doc = docs.Find(p => p.Id == item.DocId);
                    if (doc != null)
                    {
                        //item.DeptId = doc.DeptId;
                        item.DocName = language == 2 ? doc.EN_Name : doc.CN_Name;
                        item.DocImage = doc.List_Image;
                    }
                    var dept = depts.Find(p => p.Id == item.DeptId);
                    if (dept != null)
                    {
                        item.DeptName = dept.Name;
                    }
                    if (item.Status == 1)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 2)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 4)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 6)
                    {
                        item.StatusName = language == 2 ? "Doctor Await" : "就诊中";
                    }
                }
            }

            return myApt;
        }

        public List<TreatedInfo> GetCignaApt(int language)
        {
            var myApt = _onlineAptInfoRepository.GetCignaApt(GetBaseUserInfo().ID);
            var docs = _dicDoctorRepository.GetAllDoctor();
            var depts = _dicDeptRepository.SelectByLanguage(language);
            if (myApt != null && myApt.Count > 0)
            {
                foreach (var item in myApt)
                {

                    //如果linking状态为进行中，预约状态为已确认，那么预约单状态改为就诊中
                    if (item.LinKingAptStatus == 8 && (item.Status == 2 || item.Status == 4))
                    {
                        item.Status = 6;
                    }

                    item.SeeDoctorTime = Convert.ToDateTime(item.SeeDoctorTime).ToString("yyyy-MM-dd HH:mm");
                    var doc = docs.Find(p => p.Id == item.DocId);
                    if (doc != null)
                    {
                        //item.DeptId = doc.DeptId;
                        item.DocName = language == 2 ? doc.EN_Name : doc.CN_Name;
                        item.DocImage = doc.List_Image;
                    }
                    var dept = depts.Find(p => p.Id == item.DeptId);
                    if (dept != null)
                    {
                        item.DeptName = dept.Name;
                    }
                    if (item.Status == 1)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 2)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 4)
                    {
                        item.StatusName = language == 2 ? "To Start Soon" : "待就诊";
                    }
                    else if (item.Status == 6)
                    {
                        item.StatusName = language == 2 ? "Doctor Await" : "就诊中";
                    }
                }
            }

            return myApt;
        }


        public UserRedInfo GetMyRedPoint()
        {
            UserRedInfo red = new UserRedInfo();
            var user = GetBaseUserInfo();

            if (user == null)
            {
                return new UserRedInfo();
            }

            var needPayOrders = _onlineOrderRepository.GetOrderByStatus(user.ID, 1);
            if (needPayOrders != null && needPayOrders.Count > 0)
            {
                red.IsRedOrder = true;
            }
            var pats = _pubPatInfoRepository.GetUserPatHasSignOff(user.ID);
            if (pats != null && pats.Count > 0)
            {
                red.IsReportPre = true;
            }
            return red;
        }

        public int ReadMyPatReport(int patId)
        {
            return _pubPatInfoRepository.ReadMyPatReport(patId);
        }

        private bool VerificationCoupon(List<UserCouponView> writeoffcoupon, out decimal couponPrice, OrderModel ordermodel, Online_Order order)
        {
            //order.AptPrice = 300;

            couponPrice = 0;

            //除了叠加满减券，其他所有优惠券都只能使用一张优惠券
            if (writeoffcoupon.Where(w => w.Type != (int)CouponTypeEnum.Superposition).Any())
            {
                if (writeoffcoupon.Count() > 1)
                {
                    return false;
                }
            }
            if (writeoffcoupon.Where(w => w.Type == (int)CouponTypeEnum.Superposition).Any())
            {
                if (writeoffcoupon.Where(w => w.Type != (int)CouponTypeEnum.Superposition).Any())
                {
                    return false;
                }
            }

            foreach (var item in writeoffcoupon)
            {
                bool docpass = _couponService.VerificationCouponDoc(item.DocIds, item.DeptId, order.DocId.ToString(), order.AptType);
                ////判断当前优惠券使用医生是否正确
                //if (!string.IsNullOrEmpty(item.DocIds))
                //{
                //    if (!item.DocIds.Contains(order.DocId.ToString()))
                //    {
                //        docpass = false;
                //    }
                //    else
                //    {
                //        docpass = true;
                //    }
                //}
                ////对比科室
                //if (!string.IsNullOrEmpty(item.DeptId))
                //{
                //    List<int> IDs = new List<int>();
                //    item.DeptId.Split(',').ToList().ForEach(e =>
                //    {
                //        IDs.Add(int.Parse(e));
                //    });
                //    var doc = _dicMapDeptDoctorRepository.GetDocIdsForDeptIds(IDs);
                //    if (!doc.Contains(order.DocId))
                //    {
                //        docpass = false;
                //    }
                //    else
                //    {
                //        docpass = true;
                //    }
                //}
                if (!docpass)
                { return false; }


                //判断优惠券可使用的预约类型是否满足当前订单
                if (!item.AptType.Contains(order.AptType.ToString()))
                {
                    return false;
                }
                //判断优惠券使用时间是否满足
                if (!_couponService.VerificationCouponTime(item.CreateTime, item.EffectiveTime, item.EffectiveDateTime))
                {
                    return false;
                }

                var price = 0M;
                //核销优惠券
                switch (item.Type)
                {
                    case (int)CouponTypeEnum.NoThreshold:
                        price = item.Money;
                        break;
                    case (int)CouponTypeEnum.FullReduction:
                        if (order.AptPrice >= item.FullMoney)
                        {
                            price = item.Money;
                        }
                        else { return false; }
                        break;
                    case (int)CouponTypeEnum.Superposition:
                        if (order.AptPrice >= item.FullMoney)
                        {
                            price = item.Money;
                        }
                        else { return false; }
                        break;
                    case (int)CouponTypeEnum.Discount:
                        price = Math.Round(order.AptPrice * item.Money, 2);
                        break;
                    case (int)CouponTypeEnum.Free:
                        price = order.AptPrice;
                        break;
                }
                couponPrice += price;
                List<int> ids = new List<int>();
                ids.Add(item.Id);
                _onlineCouponPubUserRepository.UpdateCouponPubUserStatus(ids, (int)CouponUserEnum.Used);
                _onlineCouponlogsRepository.InsertOnlineCouponLog(new Online_Couponlogs
                {
                    CouponId = item.CouponId,
                    CouponMoney = item.Money,
                    CreateTime = DateTime.Now,
                    OrderNewMoney = order.AptPrice - couponPrice <= 0 ? 0.01M : order.AptPrice - couponPrice,
                    OrderNo = order.OrderNo,
                    OrderOldMoney = order.AptPrice,
                    PatId = order.PatId,
                    PubUserId = item.PubUserId,
                    Status = (int)CouponUserLogEnum.NewGeneration,
                    CouponPubUserId = item.Id,
                    IsDelete = false
                });

            }
            return true;
        }

        public BaseResponse<LcTradeRefundModel> OrderRefund(RefundInfo info)
        {
            BaseResponse<LcTradeRefundModel> res = new BaseResponse<LcTradeRefundModel>();
            var order = _onlineOrderRepository.GetOrderByNo(info.OrderNo);
            if (order == null)
            {
                throw new BaseException("参数错误:未找到对应订单", DetailedStatusCode.Fail);
            }
            var pat = _pubPatInfoRepository.SelectById(order.PatId);
            if (order.PayPrice == 0)
            {
                UpdateOrderStatus(info.OrderNo, 6);//订单退款成功
                //短信
                if (order.IsEnglish)
                {
                    _verifyCodeLogService.SendCusSms(pat.Phone_NO, "Your online consultation at " + Convert.ToDateTime(order.AptTime).ToString("HH:mm dd MM yyyy") + " has been cancelled. Any question please contact Customer Service in SinoUnited Health APP", 2);//xx:xx dd mmm yyyy
                }
                else
                {
                    _verifyCodeLogService.SendCusSms(pat.Phone_NO, "您" + Convert.ToDateTime(order.AptTime).ToString("MM月dd日 HH:mm") + "的线上问诊已取消，如有问题请在[曜影医疗App]内联系客服", 1);
                }
                res.Code = 1;
                res.Msg = "退款成功";
                return res;
            }
            //生成退单
            var refund = _onlineRefundRepository.GetRefundOrder("T" + order.OrderNo);
            if (refund != null && refund.RefundFee == order.PayPrice)
            {
                throw new BaseException("该订单无法退款", DetailedStatusCode.Fail);
            }

            LcTradeRefundParam param = new LcTradeRefundParam();
            param.Biz_Content = new Biz_Content2();
            //param.Biz_Content.Operator_id = info.UserId;
            if (refund == null)
            {
                param.Biz_Content.Out_request_no = GetRefundNo(order, info.UserId);//插入退款单号  返回退款单号
            }
            else
            {
                param.Biz_Content.Out_request_no = refund.RefundNo;
            }
            param.Biz_Content.Out_trade_no = order.OrderNo;
            //param.Biz_Content.Payment_type = order.PayWay;
            param.Biz_Content.Refund_amount = order.PayPrice;
            param.Biz_Content.Refund_reason = info.RefundReason;
            //param.Biz_Content.Terminal_id = info.TerminalId;
            param.Biz_Content.Trade_amount = order.PayPrice;
            param.Biz_Content.Trade_no = order.TradeNo;
            var response = _linKingService.LcTradeRefund(param);

            var helper = _sysRepository.GetSysHelpers("医助")?.FirstOrDefault();
            if (response != null && response.Code == "10000")
            {
                _onlineRefundRepository.PerfRefundOrder(param.Biz_Content.Out_request_no, response.Biz_Content);
                UpdateOrderStatus(info.OrderNo, 6);//订单退款成功
                //var user = _pubPatInfoRepository.GetUserByPatId(order.PatId);
                var apt = _onlineAptInfoRepository.GetAptInfo(order.AptId);
                var user = _pubUserInfoRepository.SelectById(apt.ApplyUserId);
                //极光推送//短信
                if (order.IsEnglish)
                {
                    PushUserMessage(user, "1", "New news", "Refund success：￥" + response.Biz_Content.Refund_fee);
                    //_jGPushService.PushMessageToUsers(order.PatId, "1", "New news", "Refund success：￥" + response.Biz_Content.Refund_fee);
                    _verifyCodeLogService.SendCusSms(pat.Phone_NO, "Your online consultation at " + Convert.ToDateTime(order.AptTime).ToString("HH:mm dd MM yyyy") + " has been cancelled. Any question please contact Customer Service in SinoUnited Health APP", 2);//xx:xx dd mmm yyyy
                }
                else
                {
                    PushUserMessage(user, "1", "您有一条新的消息", "退款成功：金额" + response.Biz_Content.Refund_fee + "元");
                    //_jGPushService.PushMessageToUsers(order.PatId, "1", "您有一条新的消息", "退款成功：金额" + response.Biz_Content.Refund_fee + "元");
                    _verifyCodeLogService.SendCusSms(pat.Phone_NO, "您" + Convert.ToDateTime(order.AptTime).ToString("MM月dd日 HH:mm") + "的线上问诊已取消，退款将在24小时内原路退还至您的账户，如有问题请在[曜影医疗App]内联系客服", 1);
                }//xx月xx日xx：xx
                //if (order.AptType == 1)//党锋改 我不知道为什么退款里会调这个  所以给注释了
                //{
                //    var group = _pubPatInfoRepository.IsExistGroup(order.PatId, order.DocId);
                //    SendGroupMessage(group.GroupId, helper.ImId, order);//TODO
                //}
                //if (order.AptType == 2)
                //{
                //    SendFriendMessage(helper.ImId, user.IM_ID, order.OrderNo);
                //}
                res.Code = 1;
                res.Msg = "退款成功";
                res.Data = response;
            }
            else
            {
                UpdateOrderStatus(info.OrderNo, 7);//订单退款失败
                _verifyCodeLogService.SendCusSms(helper.Phone, "有一笔问诊订单退款失败，请及时处理", 1);
                res.Code = 0;
                res.Msg = "退款异常";
            }
            return res;
        }

        public void RefundCase(Online_Order order)
        {

        }

        private void SendFriendMessage(string fromWho, string toWho, string orderNo)
        {
            var msg = new { messageType = "refundOrder", title = "预约取消", content = "您已成功预约,点击查看订单详情", url = "OrderDetail?orderNo=" + orderNo + "&hidden=1" };
            _tencentService.SendFriendMsg(fromWho, toWho, JsonConvert.SerializeObject(msg));
        }


        public int TestPush()
        {
            var users = _pubUserInfoRepository.GetAllUser();
            foreach (var item in users)
            {
                if (item.Language == 2)
                {
                    PushUserMessage(item, "1", "New news", "New version available, please update in app store.");

                }
                else
                {
                    PushUserMessage(item, "1", "您有一条新的消息", "有新的版本更新，请前往应用商店下载");
                }
            }
            return 1;
        }
    }
}
