using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
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.Text;
using System.Threading.Tasks;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 预约
	/// </summary>
	public class PubMessageService : BaseService, IPubMessageService
    {
        AppConfigurtaion _appConfigurtaion;
        ILogger<PubMessageService> _logger;
        IDicHosRepository _dicHosRepository;
        IZhuTongSMSService _zhuTongSMSService;
        IPubUserInfoRepository _pubUserInfoRepository;
        IDicDoctorRepository _dicDoctorRepository;
        IDicDeptRepository _dicDeptRepository;
        ITencentOutService _tencentOutService;
        IDicMapHosPhoneRepository _dicMapHosPhoneRepository;
        IOnlineOrderRepository _onlineOrderRepository;
        IOnlineAptInfoRepository _onlineAptInfoRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        IOutAptInfoRepository _outAptInfoRepository;
        IPubSmsLogRepository _pubSmsLogRepository;
        IDicMapHosDeptRepository _dicMapHosDeptPhoneRepository;
        ITCService _tcService;
        IBaiduService _baiduService;
        /// <summary>
        /// 预约
        /// </summary>
        public PubMessageService(AppConfigurtaion appConfigurtaion, ILogger<PubMessageService> logger, IDicHosRepository dicHosRepository, IZhuTongSMSService zhuTongSMSService, IPubUserInfoRepository pubUserInfoRepository, IDicDoctorRepository dicDoctorRepository, IDicDeptRepository dicDeptRepository, ITencentOutService tencentOutService, IDicMapHosPhoneRepository dicMapHosPhoneRepository, IOnlineOrderRepository onlineOrderRepository, IOnlineAptInfoRepository onlineAptInfoRepository, IPubPatInfoRepository pubPatInfoRepository, IOutAptInfoRepository outAptInfoRepository, IPubSmsLogRepository pubSmsLogRepository, IDicMapHosDeptRepository dicMapHosDeptPhoneRepository, ITCService tcService, IBaiduService baiduService)
        {
            _appConfigurtaion = appConfigurtaion;
            _logger = logger;
            _dicHosRepository = dicHosRepository;
            _zhuTongSMSService = zhuTongSMSService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _dicDoctorRepository = dicDoctorRepository;
            _dicDeptRepository = dicDeptRepository;
            _tencentOutService = tencentOutService;
            _dicMapHosPhoneRepository = dicMapHosPhoneRepository;
            _onlineOrderRepository = onlineOrderRepository;
            _onlineAptInfoRepository = onlineAptInfoRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _outAptInfoRepository = outAptInfoRepository;
            _pubSmsLogRepository = pubSmsLogRepository;
            _dicMapHosDeptPhoneRepository = dicMapHosDeptPhoneRepository;
            _tcService = tcService;
            _baiduService = baiduService;
        }
        public string aptUserConfirmSmsTemplateEN = "【SinoUnited Health】Dear Mr./Ms. [name], you have an appointment at [date] Address: [addr]. ";
        public string aptUserConfirmSmsTemplateCN = "【曜影医疗】尊敬的 [name] 女士/先生，您 [date] 的预约已确认，地址：[addr]。";
        public string aptUserCancelSmsTemplateEN = "【SinoUnited Health】Dear Mr./Ms.[name], your appointment at [date]  [addr] has been cancelled.Any question please call 4001862116 or contact customer service Ying on WeChat “SinoUnited9“.";
        public string aptUserCancelSmsTemplateCN = "【曜影医疗】尊敬的 [name] 女士/先生，您于[date] 在[addr]的预约已取消。如有任何疑问请致电4001862116，或客服小影微信SinoUnited9 。";

        public void SendAptSmsMsg2User(int hosId, Pub_Pat_Info patInfo, int language, DateTime? aptTime)
        {
            Dic_Hos hos = _dicHosRepository.initLinq().Where(p => p.Id == hosId).Single();

            //var jObj = JsonConvert.DeserializeObject(appConfigurtaion.GetAptUserCommitSmsTemplate);
            //string lang = language+"";
            string addr;
            string aptTimeStr;
            string content = string.Empty;
            //判断病人名称是否英文
            if (!patInfo.Pat_Name.IsChinese())
            {
                //lang = "2";MMM/dd HH:mm
                addr = hos.EN_Addr;
                if (patInfo.Gender == 1)
                {
                    content = _appConfigurtaion.GetAptUserCommitSmsTemplateForENMan;
                }
                else
                {
                    content = _appConfigurtaion.GetAptUserCommitSmsTemplateForENFemale;
                }

                //SimpleDateFormat sdf = new SimpleDateFormat(jObj.getString(LanguageType.EN.getValue().toString()), Locale.ENGLISH);
                aptTimeStr = Convert.ToDateTime(aptTime).ToString("MM/dd HH:mm");
            }
            else
            {
                //lang = 1;MM月dd日 HH时mm分
                addr = hos.CN_Addr;
                if (patInfo.Gender == 1)
                {
                    content = _appConfigurtaion.GetAptUserCommitSmsTemplateForCNMan;
                }
                else
                {
                    content = _appConfigurtaion.GetAptUserCommitSmsTemplateForCNFemale;
                }
                //SimpleDateFormat sdf = new SimpleDateFormat(jObj.getString(LanguageType.CN.getValue().toString()));
                aptTimeStr = Convert.ToDateTime(aptTime).ToString("MM月dd日 HH时mm分");
            }
            //string content = jObj.getString(lang + patInfo.getGender());
            content = content.Replace("[name]", patInfo.Pat_Name).Replace("[date]", aptTimeStr).Replace("[addr]", addr);
            _zhuTongSMSService.SendSMS(patInfo.Phone_NO, content);
        }
        public void SendOnlineWxMsg(string orderNo, string toOpenId, string title, string remark, string url = "")
        {
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);
            if (order != null)
            {
                var aptInfo = _onlineAptInfoRepository.GetAptInfo(order.AptId);
                Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(aptInfo.ApplyUserId);

                string aptTime = aptInfo.AptTime != null ? Convert.ToDateTime(aptInfo.AptTime).ToString("yyyy/MM/dd HH:mm") : "";
                var pat = _pubPatInfoRepository.SelectById(order.PatId);
                var caseName = aptInfo.AptType == 1 ? "视频咨询" : "复诊/开药";
                if (userInfo.Language == 2)
                {
                    aptTime = aptInfo.AptTime != null ? Convert.ToDateTime(aptInfo.AptTime).ToString("dd/MM/yyyy HH:mm") : "";
                    caseName = aptInfo.AptType == 1 ? "Video Consultation" : "Prescription Refill";
                }
                List<TemplateDataObject> dataObjectList = GetOnlineTemplateDataObjects(pat.Pat_Name, pat.Phone_NO, aptTime, caseName, title, remark);
                SendTemplateMessage(toOpenId, _appConfigurtaion.GetWXOnlineTempId, url, dataObjectList);

            }
        }


        public void SendAptWxMsg2User(int hosId, int docId, int deptId, int userId, string name, string phone, DateTime? time)
        {
            if (userId == 0)
            {
                return;
            }
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            //SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            string aptTime = time != null ? Convert.ToDateTime(time).ToString("yyyy-MM-dd HH:mm:ss") : "";

            List<TemplateDataObject> dataObjectList = GetAptTemplateDataObjects(name, phone, aptTime, userInfo.Language == 2);

            Dic_Doctor doctor = null;
            if (docId != 0)
            {
                doctor = _dicDoctorRepository.SelectByPrimaryKey(docId);
            }

            Dic_Dept dept = null;
            if (deptId != 0)
            {
                dept = _dicDeptRepository.GetDeptById(deptId);
            }
            //${ profile.aptDetailPagePath}?HOS_ID =${ aptDetailHosId}
            //&APT_TIME =${ aptDetailAptTime}
            //&CN_DOCTOR_NAME =${ aptDetailCnDoctorName}
            //&CN_DEPT_NAME =${ aptDetailCnDeptName}
            //&DETAIL_IMAGE =${ aptDetailImage}
            StringBuilder strUrl = new StringBuilder();
            strUrl.Append(_appConfigurtaion.GetAptDetailPagePath);
            strUrl.Append("?HOS_ID=" + hosId);
            strUrl.Append("&APT_TIME=" + Common.UrlEncode(aptTime));
            strUrl.Append("&CN_DOCTOR_NAME=" + doctor == null ? "" : Common.UrlEncode(doctor.CN_Name));
            strUrl.Append("&CN_DEPT_NAME=" + dept == null ? "" : Common.UrlEncode(dept.CN_Name));
            strUrl.Append("&DETAIL_IMAGE=" + doctor == null ? "" : Common.UrlEncode(doctor.Detail_Image));

            //string url = appConfigurtaion.GetAptDetailPagePath + (aptDetailHosId, hosId + "")
            //.replace(aptDetailAptTime, URLEncoder.encode(aptTime, "UTF-8").replace("+", "%20"))
            //.replace(aptDetailCnDoctorName, (doctor == null ? "" : URLEncoder.encode(doctor.getCnName(), "UTF-8")))
            //.replace(aptDetailCnDeptName, (dept == null ? "" : URLEncoder.encode(dept.getCnName(), "UTF-8")))
            //.replace(aptDetailImage, (doctor == null ? "" : URLEncoder.encode(doctor.getDetailImage(), "UTF-8")));
            var userHelperInfo = _pubUserInfoRepository.SelectByPhone("15502125732");//给小影发
            SendTemplateMessage(userHelperInfo.Open_ID, _appConfigurtaion.GetWXAptTempId, strUrl.ToString(), dataObjectList);
        }
        public bool SendTemplateMessage(string openId, string templateId, string jumpUrl, List<TemplateDataObject> data)
        {
            string token = _tencentOutService.GetCgiAccessToken(_appConfigurtaion.GetAPPId, _appConfigurtaion.GetAPPSecret);
            var jsonObject = _tencentOutService.SendTemplateMessage(token, openId, templateId, jumpUrl, null, null, data);
            _logger.LogInformation("889:" + jsonObject.ToJson());
            int index = 3;
            while (jsonObject != null && jsonObject.errcode == 40001)
            {
                // token被意外更新时需要再次获取
                if (index > 0)
                {
                    index--;
                    token = _tencentOutService.ResetCgiAccessToken(_appConfigurtaion.GetAPPId, _appConfigurtaion.GetAPPSecret);
                    jsonObject = _tencentOutService.SendTemplateMessage(token, openId, templateId, jumpUrl, null, null, data);
                }
                else
                {
                    _logger.LogError("ResetCgiAccessToken获取微信授权失败");
                    return false;
                    //throw new AppointmenException("获取微信授权失败");
                }
            }
            return true;
        }

        private List<TemplateDataObject> GetAptTemplateDataObjects(string name, string phone, string time, bool isEn)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            string title = isEn ? _appConfigurtaion.GetWXEnAptTitle : _appConfigurtaion.GetWXAptTitle;
            //.Builder(appConfigurtaion.GetWXAptTitleCode).withValue(isEn ? wxEnAptTitle : wxAptTitle).build()
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTitleCode, value = title, color = "#173177" });
            //.Builder(wxAptNameCode).withValue(name).build()
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptNameCode, value = name, color = "#173177" });
            //.Builder(wxAptPhoneCode).withValue(phone).build()
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptPhoneCode, value = phone, color = "#173177" });
            //.Builder(wxAptTimeCode).withValue(time).build()
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTimeCode, value = time, color = "#173177" });
            //.Builder(wxAptRemarkCode).withValue(isEn ? wxEnAptRemark : wxAptRemark).build()
            string remark = isEn ? _appConfigurtaion.GetWXEnAptRemark : _appConfigurtaion.GetWXAptRemark;
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptRemarkCode, value = remark, color = "#173177" });
            return dataObjectList;
        }
        private List<TemplateDataObject> GetOnlineTemplateDataObjects(string name, string phone, string time, string caseName, string title, string remark)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTitleCode, value = title, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptNameCode, value = name + " " + phone, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptPhoneCode, value = time, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTimeCode, value = caseName, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptRemarkCode, value = remark, color = "#173177" });
            return dataObjectList;
        }
        private List<TemplateDataObject> GetTemplateDataObjects(string name, string time, string title, string remark)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTitleCode, value = title, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptNameCode, value = name, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptPhoneCode, value = time, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptRemarkCode, value = remark, color = "#173177" });
            return dataObjectList;
        }


        /// <summary>
        /// 儿科优惠券  特定的
        /// </summary>
        public void SendPediatricsWxMsg(string openid, string title, string docName, string aptTime, string remark, string url = "")
        {
            List<TemplateDataObject> dataObjectList = GetTemplateDataObjects(docName, aptTime, title, remark);
            SendTemplateMessage(openid, "dVdVnSNBI_T3_Per-dG_sXI6gA-NZclUhmCVrn9Y1yA", url, dataObjectList);
        }

        public void SendQuickAptSms2HosService(int hosId, string patName, string patPhone)
        {
            List<Dic_Map_Hos_Phone> hosPhoneList = _dicMapHosPhoneRepository.initLinq().Where(p => p.Hos_Id == hosId).Select().ToList();

            string content = _appConfigurtaion.GetCNQuickTemp.Replace("[patName]", patName).Replace("[patMobile]", patPhone);

            foreach (var mapHosPhone in hosPhoneList)
            {

                string phone = mapHosPhone.Mobile;
                string sign = "【" + _appConfigurtaion.GetZhuTongSMSCNSgin + "】";
                _zhuTongSMSService.SendSMS(phone, content + sign);
                _logger.LogInformation("SendQuickAptSms2HosService发送给：" + phone);
            }
        }
        public void SendAptWxMsg2Service(string name, string phone, DateTime? time)
        {
            //SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            string aptTime = time != null ? Convert.ToDateTime(time).ToString("yyyy-MM-dd HH:mm:ss") : "";
            List<TemplateDataObject> dataObjectList = GetAptServTemplateDataObjects(name, phone, aptTime);
            //Calendar now = Calendar.getInstance();
            //Calendar six = DateUtil.setTime(18, 0, 0);
            int dayOfWeek = Convert.ToInt32(DateTime.Now.DayOfWeek);
            string openidStr = _appConfigurtaion.GetWXServOpenIdWeekDay;
            if (dayOfWeek == 6 && DateTime.Now >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 18:00:00"))
            {
                // 周六6点之后
                openidStr = _appConfigurtaion.GetWXServOpenIdWeekEnd;
            }
            else if (dayOfWeek == 0 && DateTime.Now < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 18:00:00"))
            {
                // 周日6点之前
                openidStr = _appConfigurtaion.GetWXServOpenIdWeekEnd;
            }
            foreach (var openid in openidStr.Split(','))
            {
                SendTemplateMessage(openid, _appConfigurtaion.GetWXServAptTempId, null, dataObjectList);
            }

        }
        private List<TemplateDataObject> GetAptServTemplateDataObjects(string name, string phone, string time)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            //dataObjectList.Add(new TemplateDataObject.Builder(wxServAptTitleCode).withValue(wxServAptTitle).build());
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptTitleCode, value = _appConfigurtaion.GetWXServAptTitle, color = "#173177" });
            //dataObjectList.Add(new TemplateDataObject.Builder(wxServAptNameCode).withValue(name).build());
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptNameCode, value = name, color = "#173177" });
            //dataObjectList.Add(new TemplateDataObject.Builder(wxServAptPhoneCode).withValue(phone).build());
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptPhoneCode, value = phone, color = "#173177" });
            //dataObjectList.Add(new TemplateDataObject.Builder(wxServAptTimeCode).withValue(time).build());
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptTimeCode, value = time, color = "#173177" });
            //dataObjectList.Add(new TemplateDataObject.Builder(wxServAptRemarkCode).withValue(wxServAptRemark).build());
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptRemarkCode, value = "", color = "#173177" });//java为空
            return dataObjectList;
        }

        public void TestUrl()
        {
            _logger.LogInformation("LogInformation----------");
            _logger.LogError("LogError----------");
            _logger.LogWarning("LogWarning----------");
            _logger.LogDebug("LogDebug----------");
            _logger.LogTrace("LogTrace----------");
            //var address = _baiduService.GetShortUrl("https://sinoappointment.ashermed.com/PerfectInformation?type=update&patMrn=P0056965");
            //address = _baiduService.GetShortUrl("https://www.sinounitedhealth.com.cn/sinoview/PerfectInformation?type=update&patMrn=P0056966");
        }
        public bool SendConfirmSms(Dic_Hos hos, Out_Apt_Info oAInfo, Pub_Pat_Info patInfo, Pub_Sms_Log smsLog)
        {
            // 判断短信开关是否开启
            if (_appConfigurtaion.GetAptSmsOn != "true")
            {
                smsLog.Result = "短信开关没有打开,aptSmsOn=" + _appConfigurtaion.GetAptSmsOn;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                return true;
            }

            if (string.IsNullOrEmpty(patInfo.Phone_NO))
            {
                smsLog.Result = "发送TC短信失败，患者没有手机号，患者id：" + patInfo.Id + "预约id：" + oAInfo.Id;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                return true;
            }

            bool isSend = false;
            string content, carContent, addr;
            string deptAddrName = "";
            var address = _baiduService.GetShortUrl(_appConfigurtaion.GetSetViewDomain + "PerfectInformation?type=update&patMrn=" + patInfo.Pat_MRN);
            //判断病人名称是否英文  (之前patname 改成姓了)
            if (!patInfo.Pat_Name.IsChinese())
            {
                //发送英文短信
                addr = hos.EN_SMS_Addr;
                if (oAInfo.Dept_ID != 0)
                {
                    Dic_Map_Hos_Dept mapHosDept = _dicMapHosDeptPhoneRepository.SelectByHosIdDeptID(oAInfo.Hos_Id, oAInfo.Dept_ID, 0);
                    deptAddrName = mapHosDept != null && mapHosDept.En_Sms_Addr != null ? mapHosDept.En_Sms_Addr : "";
                }
                if (deptAddrName == null)
                {
                    deptAddrName = "";
                }
                content = aptUserConfirmSmsTemplateEN.Replace("[name]", patInfo.Pat_Name)
                        .Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("yyyy/MM/dd HH:mm"))
                        .Replace("[addr]", addr.Replace("[deptAddr]", deptAddrName));
                carContent = hos.EN_Parking_Info.Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("yyyy/MM/dd HH:mm"))
                        .Replace("[hos]", hos.EN_Abbreviated_Addr);
                if (string.IsNullOrEmpty(patInfo.Mrn))
                {
                    List<PAPerson> patList = _tcService.GetPatient(patInfo.Pat_MRN, "", "");
                    if (patList != null && patList.Count > 0)
                    {
                        if (string.IsNullOrEmpty(patList[0].MRN))
                        {
                            if (carContent.IndexOf("Any question") > 0)
                            {
                                carContent = carContent.Substring(0, carContent.IndexOf("Any question"));
                            }
                            carContent += "Please complete patient information before the first visit:" + address;
                        }
                    }
                }

            }
            else
            {
                //发送中文短信
                addr = hos.CN_SMS_Addr;
                if (oAInfo.Dept_ID != 0)
                {
                    Dic_Map_Hos_Dept mapHosDept = _dicMapHosDeptPhoneRepository.SelectByHosIdDeptID(oAInfo.Hos_Id, oAInfo.Dept_ID, 0);
                    deptAddrName = mapHosDept != null && mapHosDept.Cn_Sms_Addr != null ? mapHosDept.Cn_Sms_Addr : "";
                }
                if (deptAddrName == null)
                {
                    deptAddrName = "";
                }
                content = aptUserConfirmSmsTemplateCN.Replace("[name]", patInfo.Pat_Name)
                        .Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("yyyy年MM月dd日 HH:mm"))
                        .Replace("[addr]", addr.Replace("[deptAddr]", deptAddrName));
                carContent = hos.CN_Parking_Info.Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("yyyy年MM月dd日 HH:mm"))
                        .Replace("[hos]", hos.CN_Abbreviated_Addr);
                if (string.IsNullOrEmpty(patInfo.Mrn))
                {
                    List<PAPerson> patList = _tcService.GetPatient(patInfo.Pat_MRN, "", "");
                    if (patList != null && patList.Count > 0)
                    {
                        if (string.IsNullOrEmpty(patList[0].MRN))
                        {
                            if (carContent.IndexOf("如有疑问") > 0)
                            {
                                carContent = carContent.Substring(0, carContent.IndexOf("如有疑问"));
                            }
                            carContent += "就诊前请提前完善就诊人信息:" + address;
                        }
                    }
                }
            }

            //[hos] 停车信息: B3 H区8055-8060曜影医疗专用停车位，到达入口处请出示预约短信给保安即可。如有疑问请致电4001862116。下载曜影医疗APP实时查看预约信息。
            //[hos] Parking info: B3 Area H, 8055-8060, Reserve Parking For SinoUnited Health. Ask security for direction.Any question, please call 4001862116.Download SinoUnited Health APP, get  schedule info.
            content = content + carContent;
            try
            {
                bool result = _zhuTongSMSService.SendSMS(patInfo.Phone_NO, content)?.Code == 200;
                isSend = result;
                smsLog.Result = "发送TC确认预约短信成功，手机号：" + patInfo.Phone_NO;
                smsLog.Send_Time = DateTime.Now.ToString();
                smsLog.Sms_Content = content;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
            catch (System.Exception ex)
            {
                smsLog.Result = "发送TC确认预约短信失败，预约id：" + oAInfo.Id + "，手机号：" + patInfo.Phone_NO + ",错误信息：" + ex.Message;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
            return isSend;
        }

        public bool SendCancelSms(Dic_Hos hos, Out_Apt_Info oAInfo, Pub_Pat_Info patInfo, Pub_Sms_Log smsLog)
        {
            // 判断短信开关是否开启
            if (_appConfigurtaion.GetAptSmsOn != "true")
            {
                return true;
            }
            if (string.IsNullOrEmpty(patInfo.Phone_NO))
            {
                smsLog.Result = "发送TC取消短信失败，患者没有手机号，患者id：" + patInfo.Id + "预约id：" + oAInfo.Id;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                return true;
            }

            string content, addr;
            bool isSend = false;
            //判断病人名称是否英文
            if (!patInfo.Pat_Name.IsChinese())
            {
                //发送英文短信
                addr = hos.EN_SMS_Addr;
                content = aptUserCancelSmsTemplateEN.Replace("[name]", patInfo.Pat_Name)
                        .Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("MMM-d-yyyy HH:mm"))
                        .Replace("[addr]", addr);
            }
            else
            {
                //发送中文短信
                addr = hos.CN_SMS_Addr;
                content = aptUserCancelSmsTemplateCN.Replace("[name]", patInfo.Pat_Name)
                        .Replace("[date]", Convert.ToDateTime(oAInfo.Apt_Time).ToString("yyyy年MM月dd日 HH:mm"))
                        .Replace("[addr]", addr);
            }
            try
            {

                var sendResult = _zhuTongSMSService.SendSMS(patInfo.Phone_NO, content);

                if (patInfo.Phone_NO == "15921019118")
                {
                    _logger.LogInformation($"吴刚月：{patInfo.Phone_NO}-{content}-{sendResult.ToJson()}");
                }

                isSend = true;

                smsLog.Result = "发送TC取消预约短信成功，手机号：" + patInfo.Phone_NO;
                smsLog.Send_Time = DateTime.Now.ToString();
                smsLog.Sms_Content = content;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
            catch (System.Exception ex)
            {
                smsLog.Result = "发送TC取消预约短信失败，预约id：" + oAInfo.Id + "，手机号：" + patInfo.Phone_NO + ",错误信息：" + ex.Message;
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
            return isSend;
        }

        public void SendRewardIntegralWxMsg2User(UserDetail userDetail, int addedIntegral, DateTime? addedDate)
        {
            var wxRewardIntegralEnTitle = "Your points of inviting friends has been added to your account";
            var wxRewardIntegralCnTitle = "您好，您的邀请好友积分已到账";
            var wxRewardIntegralEnRemark = "Tap to view your points in Customer Center";
            var wxRewardIntegralCnRemark = "点击进入链接为邀请好友的老用户页面";
            bool isEn = userDetail.Language == 2;
            List<TemplateDataObject> data = GetRewardTemplateDataObjects(userDetail.totalIntegral, addedIntegral,
                            addedDate, userDetail.Language, isEn ? wxRewardIntegralEnTitle : wxRewardIntegralCnTitle,
                            isEn ? wxRewardIntegralEnRemark : wxRewardIntegralCnRemark);
            //享受儿科邀请奖励券的用户消息模板
            SendTemplateMessage(userDetail.OpenId, "VhAetabYEeac7M5AU8MfJQhmrzVm10i1BGWlow4S31E", "http://www.sinounitedhealth.com.cn/patientportal/switch", data);
        }

        private List<TemplateDataObject> GetRewardTemplateDataObjects(int totalIntegral, int addedIntegral, DateTime? addedDate, int language, string title, string remark)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            var wxRewardAddedIntegralEn = "${wxRewardIntegralPlaceHolder} points added";
            var wxRewardIntegralPlaceHolder = "#INTEGRAL#";
            var wxRewardAddedIntegralCn = "${wxRewardIntegralPlaceHolder}";
            var wxRewardTotalIntegralEn = "${wxRewardIntegralPlaceHolder} points available";
            var wxRewardTotalIntegralCn = "${wxRewardIntegralPlaceHolder}";
            bool isEn = language == 2;
            // 标题
            dataObjectList.Add(new TemplateDataObject() { field = "first", value = title, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject()
            {
                field = "keyword1",
                value = isEn ? wxRewardAddedIntegralEn.Replace(wxRewardIntegralPlaceHolder, "" + addedIntegral)
                        : wxRewardAddedIntegralCn.Replace(wxRewardIntegralPlaceHolder, "" + addedIntegral),
                color = "#173177"
            });


            // 奖励时间
            string date = Convert.ToDateTime(addedDate).ToString("yyyy-MM-dd"); ;
            if (isEn)
            {
                date = Convert.ToDateTime(addedDate).ToString("MMM-d-yyyy"); ;
            }
            dataObjectList.Add(new TemplateDataObject() { field = "keyword2", value = date, color = "#173177" });

            // 总积分
            dataObjectList.Add(new TemplateDataObject()
            {
                field = "keyword3",
                value = isEn ? wxRewardTotalIntegralEn.Replace(wxRewardIntegralPlaceHolder, "" + totalIntegral)
                            : wxRewardTotalIntegralCn.Replace(wxRewardIntegralPlaceHolder, "" + totalIntegral),
                color = "#173177"
            });
            //dataObjectList.add(new TemplateDataObject.Builder(wxRewardTotalIntegralCode)
            //        .withValue(isEn ? wxRewardTotalIntegralEn.replace(wxRewardIntegralPlaceHolder, "" + totalIntegral)
            //                : wxRewardTotalIntegralCn.replace(wxRewardIntegralPlaceHolder, "" + totalIntegral))
            //        .build());
            // remark
            //dataObjectList.add(new TemplateDataObject.Builder(wxRewardRemarkCode) .withValue(remark).build());
            dataObjectList.Add(new TemplateDataObject() { field = "remark", value = remark, color = "#173177" });
            return dataObjectList;
        }


        public void SendSmsCoupon300(string phone)
        {
            UserDetail userDetail = _pubUserInfoRepository.SelectDetailByPhone(phone);
            string content = "300元诊费抵用券已经加入您的账户，通过微信公众号打开“曜影医疗会员中心”，点击“我”→“我的卡券”查看。如有任何疑问请联系客服小影。【曜影医疗】";
            if (userDetail.Language == 2)
            {
                content = "￥300 voucher of consultation fee from SinoUnited Health has been added to your account. You can find it in our official WeChat → “Customer Center” → “Me” → “My Coupon”. Any question please contact customer service Ying.【SinoUnited Health】";
            }

            _zhuTongSMSService.SendSMS(phone, content);
        }

        public void SendVaccineAptWxMsg2User(int userId, string name, string phone)
        {
            if (userId == null)
            {
                return;
            }
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            if (string.IsNullOrEmpty(userInfo.Open_ID))
            {
                return;
            }
            List<TemplateDataObject> dataObjectList = GetVaccineAptTemplateDataObjects(name, phone, "N/A", 2 == userInfo.Language);

            SendTemplateMessage(userInfo.Open_ID, _appConfigurtaion.GetWXAptTempId, null, dataObjectList);
        }
        public void SendVaccineAptWxMsg2Service(string name, string phone)
        {
            string aptTime = "N/A";
            List<TemplateDataObject> dataObjectList = GetVaccineAptServTemplateDataObjects(name, phone, aptTime);
            string openidStr = _appConfigurtaion.GetWXServOpenIdWeekDay;

            foreach (var openid in openidStr.Split(','))
            {
                SendTemplateMessage(openid, _appConfigurtaion.GetWXServAptTempId, null, dataObjectList);
            }
        }

        private List<TemplateDataObject> GetVaccineAptTemplateDataObjects(string name, string phone, string time, bool isEn)
        {
            string wxEnVaccineAptRemark = "You have successfully queued up, please be patient. After the vaccine arrives, we will notify you in the order of appointment time.";
            string wxCnVaccineAptRemark = "您已排队成功，请耐心等待。疫苗到货后我们将会按照预约先后顺序进行通知。";
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            string title = isEn ? _appConfigurtaion.GetWXEnAptTitle : _appConfigurtaion.GetWXAptTitle;
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTitleCode, value = title, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptNameCode, value = name + " " + phone, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptPhoneCode, value = phone, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptTimeCode, value = time, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXAptRemarkCode, value = isEn ? wxEnVaccineAptRemark : wxCnVaccineAptRemark, color = "#173177" });
            return dataObjectList;
        }

        private List<TemplateDataObject> GetVaccineAptServTemplateDataObjects(string name, string phone, string time)
        {
            List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptTitleCode, value = "疫苗预约", color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptNameCode, value = name, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptPhoneCode, value = phone, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptTimeCode, value = time, color = "#173177" });
            dataObjectList.Add(new TemplateDataObject() { field = _appConfigurtaion.GetWXServAptRemarkCode, value = "", color = "#173177" });//java为空
            return dataObjectList;
        }
    }
}
