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.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.Extensions.Logging;
using PoJun.Util;
using PoJun.Util.Maps;
using Renci.SshNet.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// TC回调服务
	/// </summary>
	public class TCTransService : BaseService, ITCTransService
    {
        IPubUserInfoService _pubUserInfoService;
        IPubUserInfoRepository _pubUserInfoRepository;
        RedisHelperClient _redisHelper;
        IJWTService _jWTService;
        IPubSmsLogRepository _pubSmsLogRepository;
        IOutAptInfoRepository _outAptInfoRepository;
        IDicHosRepository _dicHosRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        IPatService _patService;
        IDicMapDeptDoctorRepository _dicMapDeptDoctorRepository;
        IDicMapDeptServRepository _dicMapDeptServRepository;
        IAptService _aptService;
        AppConfigurtaion _appConfigurtaion;
        IDicMapHosDeptRepository _dicMapHosDeptPhoneRepository;
        IZhuTongSMSService _zhuTongSMSService;
        ITCService _tcService;
        ILogger<TCTransService> _logger;
        IJpushService _jpushService;
        IPubMessageInfoRepository _pubMessageInfoRepository;
        IOutNoticeInfoRepository _outNoticeInfoRepository;
        IPubMessageService _pubMessageService;
        IVerifyCodeLogService _verifyCodeLogService;

        #region 初始化
        /// <summary>
        /// 
        /// </summary>
        public TCTransService(IPubUserInfoService pubUserInfoService, IPubUserInfoRepository pubUserInfoRepository, RedisHelperClient redisHelper, IJWTService jWTService, IPubSmsLogRepository pubSmsLogRepository, IOutAptInfoRepository outAptInfoRepository, IDicHosRepository dicHosRepository, IPubPatInfoRepository pubPatInfoRepository, IPatService patService, IDicMapDeptDoctorRepository dicMapDeptDoctorRepository, IDicMapDeptServRepository dicMapDeptServRepository, IAptService aptService, AppConfigurtaion appConfigurtaion, IDicMapHosDeptRepository dicMapHosDeptPhoneRepository, IZhuTongSMSService zhuTongSMSService, ITCService tcService, ILogger<TCTransService> logger, IJpushService jpushService, IPubMessageInfoRepository pubMessageInfoRepository, IOutNoticeInfoRepository outNoticeInfoRepository, IPubMessageService pubMessageService, IVerifyCodeLogService verifyCodeLogService)
        {
            _pubUserInfoService = pubUserInfoService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _redisHelper = redisHelper;
            _jWTService = jWTService;
            _pubSmsLogRepository = pubSmsLogRepository;
            _outAptInfoRepository = outAptInfoRepository;
            _dicHosRepository = dicHosRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _patService = patService;
            _dicMapDeptDoctorRepository = dicMapDeptDoctorRepository;
            _dicMapDeptServRepository = dicMapDeptServRepository;
            _aptService = aptService;
            _appConfigurtaion = appConfigurtaion;
            _dicMapHosDeptPhoneRepository = dicMapHosDeptPhoneRepository;
            _zhuTongSMSService = zhuTongSMSService;
            _tcService = tcService;
            _logger = logger;
            _jpushService = jpushService;
            _pubMessageInfoRepository = pubMessageInfoRepository;
            _outNoticeInfoRepository = outNoticeInfoRepository;
            _pubMessageService = pubMessageService;
            _verifyCodeLogService = verifyCodeLogService;
        }
        #endregion


        public void Confirm(Appointment aptInfo)
        {
            _logger.LogInformation("Confirm:" + aptInfo.ToJson());
            Pub_Sms_Log smsLog = new Pub_Sms_Log();
            string confirmInfo = aptInfo.ToJson() + "-------DEPT_CODE:[" + aptInfo.DeptId +
                    "],SERV_CODE[" + aptInfo.AptProj +
                    "],APT_TIME[" + aptInfo.AptDateTime +
                    "],USRN[" + aptInfo.AptUsrn +
                    "],DOCTOR_CODE[" + aptInfo.DocId +
                    "],EPISODE[" + aptInfo.EpisodeId +
                    "],HOS_CODE[" + aptInfo.HosId +
                    "],PAT_MRN[" + aptInfo.PatId +
                    "],REMARK[" + aptInfo.Remark + "]";
            smsLog.Request = confirmInfo;
            smsLog.Sms_Type = 21; //TC预约确认短信
            smsLog.Create_Time = DateTime.Now;
            smsLog.Id = _pubSmsLogRepository.InsertPubSmsLog(smsLog);

            try
            {
                //1.usrn+mrn匹配
                if (!string.IsNullOrEmpty(aptInfo.AptUsrn) && aptInfo.PatId != null)
                {
                    Out_Apt_Info outAptInfoPP = _outAptInfoRepository.FindByMrnUsrn(aptInfo.PatId, aptInfo.AptUsrn.Replace("\\F\\", "|"));
                    if (outAptInfoPP != null)
                    {
                        smsLog.Result = "预约已存在，无法提交预约！";
                        _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        return;
                    }
                }
                bool isSend = true;
                string hosCode = aptInfo.HosId.Substring(0, 3);
                Dic_Hos hos = _dicHosRepository.SelectByHisCode(hosCode);

                //region 若患者不存在则自动加入
                string mrn = aptInfo.PatId;
                Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectByMrn(mrn);
                if (patInfo == null)
                {
                    List<Pub_Pat_Info> list = _patService.GetHisPat(mrn, null, null);
                    if (list.Count() == 0)
                    {
                        smsLog.Result = "在HIS查不到病人信息，mrn" + mrn;
                        _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        return;
                    }
                    patInfo = list[0];
                }
                //endregion

                // 假设医生在一家诊所下只属于一个科室，否则需要修改规则
                string hisHosCode = aptInfo.HosId.Split('\\')[0];
                string hisDeptCode = aptInfo.DeptId;
                string hisDoctorCode = aptInfo.DocId;
                string hisServCode = aptInfo.AptProj;
                Dic_Map_Dept_Doctor mapDeptDoctor = _dicMapDeptDoctorRepository.FindByHisHosDeptDoctorCode(hisHosCode, hisDeptCode, hisDoctorCode, 0);

                Dic_Map_Dept_Serv mapDeptServ = null;
                if (mapDeptDoctor != null)
                {
                    mapDeptServ = _dicMapDeptServRepository.FindByHosDeptWithHisCode(mapDeptDoctor.Apt_Hos_Id, hisDeptCode, hisServCode);
                }


                if (mapDeptServ == null)
                {
                    // 若是查不到绑定的服务，则直接查code相同并且非绑定的服务，即特殊服务
                    mapDeptServ = _dicMapDeptServRepository.FindByHisServCode(hisServCode);
                }
                if (mapDeptServ == null)
                {
                    //还是无法查询到服务，则讲该服务加入，即未知服务
                    mapDeptServ = new Dic_Map_Dept_Serv();
                    mapDeptServ.His_Serv_Code = hisServCode;
                    mapDeptServ.Cn_Name = hisServCode;
                    mapDeptServ.En_Name = hisServCode;
                    mapDeptServ.Is_Deleted = false;
                    _dicMapDeptServRepository.InsertDicMapDeptServ(mapDeptServ);
                }

                isSend = mapDeptServ.Is_Send;
                if (!mapDeptServ.Is_Send)
                {
                    smsLog.Result = mapDeptServ.His_Serv_Code + "   SERVICE不需要发送短信";
                }

                Out_Apt_Info outAptInfo = new Out_Apt_Info();
                if (hos != null)
                {
                    outAptInfo.Hos_Id = hos.Id;
                }
                if (mapDeptDoctor != null)
                {
                    outAptInfo.Dept_ID = mapDeptDoctor.Apt_Dept_Id;
                    outAptInfo.Doc_Id = mapDeptDoctor.Apt_Doctor_Id;
                }

                outAptInfo.Apt_Proj = mapDeptServ.Id;
                outAptInfo.Episode_Id = aptInfo.EpisodeId;
                outAptInfo.Apt_Usrn = aptInfo.AptUsrn != null ? aptInfo.AptUsrn.Replace("\\F\\", "|") : null;
                outAptInfo.Pat_Id = patInfo.Id;
                outAptInfo.Source_Type = 2;//HIS
                outAptInfo.Remark = aptInfo.Remark;
                outAptInfo.Status = 0;//已确认
                outAptInfo.Inner_Status = 4;//已确认
                outAptInfo.Create_Time = DateTime.Now;


                string remark = aptInfo.Remark;

                int index = -1;
                if (!string.IsNullOrEmpty(remark))
                {
                    index = remark.IndexOf("#"); //预约同步时Remark和匹配码分割符
                }
                if (index >= 0)
                {
                    string matchCode = remark.Substring(index + 1);

                    if (!string.IsNullOrEmpty(matchCode))
                    {
                        //region 传入匹配码，需要把相对应的未录入的内部状态改为已确认
                        Out_Apt_Info _aptInfo = _outAptInfoRepository.SelectByMatchCode(matchCode);
                        if (_aptInfo != null && (2 & _aptInfo.Source_Type) == 0)
                        {
                            _aptInfo.Inner_Status = 4;
                            _outAptInfoRepository.UpdateOutAptInnerStatus(_aptInfo.Id, 4);
                        }
                        //endregion
                    }
                    outAptInfo.Match_Code = matchCode;

                }
                else
                {
                    outAptInfo.Match_Code = Guid.NewGuid().ToString().Substring(0, 8);
                }

                string timeStr = aptInfo.AptDateTime;
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                DateTime aptTime = DateTime.ParseExact(timeStr, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                //DateTime aptTime = Convert.ToDateTime(timeStr);
                outAptInfo.Apt_Time = aptTime;

                if (hisServCode != "CON67")
                {
                    _outAptInfoRepository.InsertOutAptInfo(outAptInfo);
                }

                if (isSend)
                    _pubMessageService.SendConfirmSms(hos, outAptInfo, patInfo, smsLog);
            }
            catch (System.Exception ee)
            {
                smsLog.Result = ee.Message;
            }
            finally
            {
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
        }



        public void Cancel(CancelReq req)
        {
            _logger.LogInformation(":Cancel:" + req.ToJson());
            Pub_Sms_Log smsLog = new Pub_Sms_Log();
            string _usrn = req.Usrn.Replace("\\F\\", "|");

            smsLog.Request = "患者ID[" + req.PatId + "],预约号源[" + _usrn + "],预约时间[" + req.AptDateTime + "],取消原因[" + req.ReasonforCancellation + "]";
            smsLog.Sms_Type = 22;//TC预约取消短信
            _pubSmsLogRepository.InsertPubSmsLog(smsLog);

            try
            {
                //Date aptTime = sdf.parse(aptDateTime.trim());//yyyyMMddHHmmss
                //string aptDate = Convert.ToDateTime(aptDateTime).ToString("yyyyMMddHHmmss");
                string aptDate = DateTime.ParseExact(req.AptDateTime, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture).ToString();
                Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectByMrn(req.PatId);
                if (patInfo == null)
                {
                    List<Pub_Pat_Info> list = _patService.GetHisPat(req.PatId, null, null);
                    if (list.Count() == 0)
                    {
                        smsLog.Result = "在HIS查不到病人信息，mrn" + req.PatId;
                        _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        return;
                    }
                    patInfo = list[0];
                }
                //把tc的字段转成我们自己的
                //Dic_Map_Dept_Doctor mapDeptDoctor = _dicMapDeptDoctorRepository.FindByHisHosDeptDoctorCode(req.HosId, req.DeptId, req.DocId, 0);
                //开始匹配预约
                //1.usrn+mrn匹配
                //Out_Apt_Info outAptInfo = _outAptInfoRepository.FindByCondition(req.PatId, _usrn, mapDeptDoctor.Apt_Dept_Id, mapDeptDoctor.Apt_Doctor_Id, mapDeptDoctor.Apt_Hos_Id, req.ProjId);
                Out_Apt_Info outAptInfo = _outAptInfoRepository.FindByMrnUsrn(req.PatId, _usrn);
                if (outAptInfo == null)
                {
                    //2.mrn+预约时间匹配
                    outAptInfo = _outAptInfoRepository.FindByMrnDate(req.PatId, aptDate);
                }
                if (outAptInfo != null)
                {
                    //如果已取消预约，不需要再次发送短信通知
                    if (outAptInfo.Status == 2)
                    {
                        smsLog.Request = "患者已取消预约";
                        _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        return;
                    }

                    bool isSend = true;
                    if (outAptInfo.Apt_Proj != 0)
                    {
                        Dic_Map_Dept_Serv mapDeptServ = _dicMapDeptServRepository.SelectByPrimaryKey(outAptInfo.Apt_Proj);
                        if (mapDeptServ != null)
                        {
                            isSend = mapDeptServ.Is_Send;
                        }
                        if (!mapDeptServ.Is_Send)
                        {
                            smsLog.Result = mapDeptServ.His_Serv_Code + "   SERVICE不需要发送短信";
                        }
                    }

                    outAptInfo.Inner_Status = 2; //取消
                    outAptInfo.Cancel_Remark = req.ReasonforCancellation;
                    if (outAptInfo.Source_Type == 2)//his
                    {
                        // 对于来自His的预约，处理状态也设置为取消
                        outAptInfo.Status = 2;//取消
                    }
                    Dic_Hos hos = _dicHosRepository.SelectByPrimaryKey(outAptInfo.Hos_Id);

                    if (isSend && req.ReasonforCancellation != "By Clinic")
                    {
                        _pubMessageService.SendCancelSms(hos, outAptInfo, patInfo, smsLog);
                    }
                    //短信发送成功修改状态
                    _outAptInfoRepository.UpdateOutAptInfo(outAptInfo);
                    smsLog.Result = "取消预约成功,修改后预约状态为：" + outAptInfo.Inner_Status + "！reasonforCancellation为By Clinic不需要发送短信";
                }
                else
                {
                    smsLog.Result = "平台没有对应的患者或预约，无需取消";
                    _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                }
            }
            catch (System.Exception throwable)
            {
                //throwable.printStackTrace();
                smsLog.Result = throwable.Message;
            }
            finally
            {
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
        }



        public List<Pub_Pat_Info> UpdatePatientInfo(string patId)
        {
            _logger.LogInformation(":UpdatePatientInfo:" + patId);
            var pat = _tcService.GetPatient(patId, "", "");

            List<Pub_Pat_Info> list = new List<Pub_Pat_Info>();

            foreach (var item in pat)
            {
                PatWithAge patInfo = new PatWithAge();
                patInfo.Pat_Source = 1;
                patInfo.Is_Deleted = false;
                patInfo.Birthday = item.PAPERDob + "";
                patInfo.Age = item.PAPERDob.GetAgeByBirth();
                patInfo.Email = item.PAPEREmail;
                patInfo.Last_Name = item.PAPERName;
                patInfo.First_Name = item.PAPERName2;
                patInfo.Gender = item.PAPERSex.ToLower().Contains("female") ? 0 : 1;
                patInfo.Is_Active = item.PAPMIActive == "Y";
                patInfo.Is_Dead = item.PAPERDeceased == "Y";
                patInfo.Pat_ID = item.PAPERRowId;
                patInfo.Pat_MRN = item.PAPMINo;
                patInfo.Nationality = item.PAPERNation;
                patInfo.Card_ID = item.PAPERID;

                if (patInfo.Card_ID.Length == 18 || patInfo.Card_ID.Length == 15)
                {
                    patInfo.Card_Type = 1;
                }
                else
                {
                    patInfo.Card_Type = 2;
                }

                string lastName = string.IsNullOrEmpty(item.PAPERName) ? "" : item.PAPERName.Trim();
                if (!string.IsNullOrEmpty(lastName) && !lastName.IsChinese())
                {
                    patInfo.Pat_Name = patInfo.First_Name + " " + lastName;
                }
                else
                {
                    patInfo.Pat_Name = lastName + patInfo.First_Name;
                }
                if (!string.IsNullOrEmpty(item.PAPERMobPhone))
                {
                    patInfo.Phone_NO = item.PAPERMobPhone.Trim();
                }

                _patService.SaveHisPat(patInfo);
                list.Add(patInfo);
            }

            return list;
        }

        /// <summary>
        ///INQUIRY_15MIN(1, "视屏预约开始前15分钟通知"),
        ///INQUIRY_10MIN(2, "视屏预约开始后10分钟通知"),
        ///INQUIRY_OPEN(3, "医生开启视屏"),
        ///NA_TREATMENT_EMAIL(4, "核酸检测报告发送到邮箱"),
        ///TC_CONFIRM(21, "TC预约提交"),
        ///TC_CANCEL(22, "TC预约取消"),
        ///TC_STATUS(23, "TC变更预约状态"),
        ///INTERNET_15MIN(31, "互联网医院预约开始前十五分钟通知");
        /// </summary>
        /// <param name="patId"></param>
        /// <param name="usrn"></param>
        /// <param name="aptDateTime"></param>
        /// <param name="tcStatus"></param>
        public void UpdateAptStatus(string patId, string usrn, string aptDateTime, string tcStatus)
        {
            _logger.LogInformation(":UpdateAptStatus:" + patId + "--" + usrn + "--" + aptDateTime + "--" + tcStatus);
            Pub_Sms_Log smsLog = new Pub_Sms_Log();
            string _usrn = usrn.Replace("\\F\\", "|");

            smsLog.Request = "患者ID[" + patId + "],预约号源[" + _usrn + "],预约时间[" + aptDateTime + "],状态变更[" + tcStatus + "]";
            smsLog.Sms_Type = 23;
            _pubSmsLogRepository.InsertPubSmsLog(smsLog);

            try
            {
                //string aptDate = Convert.ToDateTime(aptDateTime).ToString("yyyyMMddHHmmss");
                string aptDate = DateTime.ParseExact(aptDateTime, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture).ToString();
                Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectByMrn(patId);
                if (patInfo == null)
                {
                    List<Pub_Pat_Info> list = _patService.GetHisPat(patId, null, null);
                    if (list.Count == 0)
                    {
                        smsLog.Result = "在HIS查不到病人信息，mrn" + patId;
                        _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        return;
                    }
                    patInfo = list[0];
                }


                //开始匹配预约
                //1.usrn+mrn匹配
                Out_Apt_Info outAptInfo = _outAptInfoRepository.FindByMrnUsrn(patId, _usrn);
                if (outAptInfo == null)
                {
                    //2.mrn+预约时间匹配
                    outAptInfo = _outAptInfoRepository.FindByMrnDate(patId, aptDate);
                }
                if (outAptInfo != null)
                {            //code   desc  ppStatus
                    //cancelled("X", "取消", 2),
                    //booked("P", "已确认", 4),
                    //arrived("A", "来就诊了", 8),
                    //arrivedNotSeen("S", "来诊所但是因为各种原因没有看医生（没产生付款行为，但是来了）", 16),
                    //departed("D", "出院了，等同于arrived", 32),
                    //notShow("N", "爽约了", 64);
                    //变更状态
                    if (tcStatus == "A")
                    {
                        outAptInfo.Inner_Status = 8;
                    }
                    if (tcStatus == "S")
                    {
                        outAptInfo.Inner_Status = 16;
                    }
                    if (tcStatus == "P")
                    {
                        outAptInfo.Inner_Status = 4;
                    }
                    if (tcStatus == "X")
                    {
                        outAptInfo.Inner_Status = 2;
                    }
                    if (tcStatus == "D")
                    {
                        outAptInfo.Inner_Status = 32;
                    }
                    if (tcStatus == "N")
                    {
                        outAptInfo.Inner_Status = 64;
                    }

                    //成功修改状态
                    _outAptInfoRepository.UpdateOutAptInfo(outAptInfo);
                    smsLog.Result = "修改状态成功！,修改后状态为：" + outAptInfo.Inner_Status;
                }
                else
                {
                    smsLog.Result = "平台没有对应的患者或预约，无需操作";
                    _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                }
            }
            catch (System.Exception throwable)
            {
                //throwable.printStackTrace();
                smsLog.Result = throwable.Message;
            }
            finally
            {
                _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
            }
        }

        public string SignOffMsg(string patientId, string episodeNo)
        {
            _logger.LogInformation("接受SignOff成功！PatientId：" + patientId + ",EpisodeNo:" + episodeNo);
            string isOk = "0";
            Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectByMrn(patientId);
            if (patInfo != null)
            {
                if (patInfo.Last_Sign_Off != null)
                {
                    //获取今天的日期
                    string nowDay = DateTime.Now.ToString("yyyy-MM-dd");
                    //对比的时间
                    string day = Convert.ToDateTime(patInfo.Last_Sign_Off).ToString("yyyy-MM-dd");

                    if (day == nowDay)
                    {
                        isOk = "1";
                        return isOk;
                    }
                }

                //Pub_User_Info info = _pubUserInfoRepository.SelectByPatId(patInfo.Id);
                //if (info != null && info.APP_Language != null)
                //{
                //    //极光
                //    switch (info.APP_Language)
                //    {
                //        case 1:
                //            PushUserMessage(info.ID, episodeNo, 9, "检查报告", "您有一份新的检查报告可供查阅，点击查看!");
                //            _logger.LogInformation("发送通知成功！PatientId：" + patientId + ",EpisodeNo:" + episodeNo);
                //            isOk = "1";
                //            break;
                //        case 2:
                //            PushUserMessage(info.ID, episodeNo, 9, "inspection report ", "You have a new inspection report available for review, click to view! ");
                //            _logger.LogInformation("发送通知成功！PatientId：" + patientId + ",EpisodeNo:" + episodeNo);
                //            isOk = "1";
                //            break;
                //    }
                //    //短信
                //    if (info.APP_Language == 1)
                //    {
                //        _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "有新的检查/检验报告可以在曜影医疗APP zt81.cn/mZmM6 查看", 1);
                //    }
                //    else
                //    {
                //        _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "You have a new medical report available. Open APP zt81.cn/mZmM6 for detail", 2);
                //    }
                //    //发送微信模板消息
                //    List<Regcombos> reportInfoList = _tcService.GetClinicalInfo(episodeNo, 2);
                //    if (reportInfoList != null && reportInfoList.Count > 0 && info.Open_ID != null)
                //    {
                //        List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
                //        string url = "";
                //        string templateId = "V6scFBNxiwhnfQW0347544D0YtZ8gTmuhvahx9GSzKw";
                //        if (info.Language == 1)
                //        {
                //            dataObjectList.Add(new TemplateDataObject() { field = "first", value = "您有新的检查报告可供查阅", color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "keyword1", value = "详情请进入检查报告页面查看", color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "keyword2", value = reportInfoList.FirstOrDefault().CHECKDATE, color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "remark", value = "点击打开曜影医疗APP，查看报告", color = "#173177" });
                //            //dataObjectList.Add(new TemplateDataObject.Builder("first")
                //            //        .withValue("您有一份新的检查报告可供查阅").build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("keyword1")
                //            //        .withValue("详情请进入检查报告页面查看").build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("keyword2")
                //            //        .withValue(reportInfoList.get(0).getCheckDate()).build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("remark")
                //            //        .withValue("点击进入会员中心查看报告").build());
                //            url = "https://a.app.qq.com/o/simple.jsp?pkgname=com.ashermed.sino#opened";
                //        }
                //        else
                //        {
                //            dataObjectList.Add(new TemplateDataObject() { field = "first", value = "You have a new Medical Report available", color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "keyword1", value = "For details, please go to the Medical Report page", color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "keyword2", value = reportInfoList.FirstOrDefault().CHECKDATE, color = "#173177" });
                //            dataObjectList.Add(new TemplateDataObject() { field = "remark", value = "Tap to enter APP to view", color = "#173177" });
                //            //dataObjectList.Add(new TemplateDataObject.Builder("first")
                //            //        .withValue("You have a new Medical Report available").build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("keyword1")
                //            //        .withValue("For details, please go to the Medical Report page").build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("keyword2")
                //            //        .withValue(reportInfoList.get(0).getCheckDate()).build());
                //            //dataObjectList.Add(new TemplateDataObject.Builder("remark")
                //            //        .withValue("Tap to enter Customer Center to view").build());
                //            url = "https://a.app.qq.com/o/simple.jsp?pkgname=com.ashermed.sino#opened";//"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbd16212a70d55f55&redirect_uri=https%3A%2F%2Fwww.sinounitedhealth.com.cn%2Fpatientportal%2FHomesubscribe&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                //        }
                //        try
                //        {
                //            _logger.LogInformation("开始推送SignOff模板消息:" + info.Open_ID);
                //            _pubMessageService.SendTemplateMessage(info.Open_ID, templateId, url, dataObjectList);
                //            _logger.LogInformation("完成SignOff模板消息推送:" + info.Open_ID);
                //        }
                //        catch (System.Exception ex)
                //        {
                //            _logger.LogError("SignOff模板消息推送失败" + info.Open_ID);
                //        }
                //    }
                //}
                //修改最后发送时间
                patInfo.Last_Sign_Off = DateTime.Now;
                patInfo.Last_Sign_EpisodeNo = episodeNo;
                _pubPatInfoRepository.UpdatePubPatInfo(patInfo);
                _pubUserInfoRepository.UserSignOff(patInfo.Id);
                _pubPatInfoRepository.PatSignOff(patInfo.Id);
            }
            return isOk;
        }




        public void SendSignOffMsg(int patId)
        {
            Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(patId);
            //短信
            //Pub_User_Info info = _pubUserInfoRepository.SelectByPatId(patId);
            if (!string.IsNullOrEmpty(patInfo.Pat_Name) && patInfo.Pat_Name.IsChinese())
            {
                _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "有新的检查/检验报告可以在曜影医疗APP zt81.cn/mZmM6 查看", 1);
            }
            else
            {
                _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "You have a new medical report available. Open APP zt81.cn/mZmM6 for detail", 2);
            }
            var users = _pubPatInfoRepository.GetUsersByPatId(patId);
            foreach (var info in users)
            {
                if (info != null && info.APP_Language != null)
                {
                    //极光
                    switch (info.APP_Language)
                    {
                        case 1:
                            PushUserMessage(info.ID, patInfo.Last_Sign_EpisodeNo, 9, "检查报告", "您有一份新的检查报告可供查阅，点击查看!");
                            _logger.LogInformation("发送通知成功！PatientId：" + patInfo.Pat_MRN + ",EpisodeNo:" + patInfo.Last_Sign_EpisodeNo);
                            //isOk = "1";
                            break;
                        case 2:
                            PushUserMessage(info.ID, patInfo.Last_Sign_EpisodeNo, 9, "inspection report ", "You have a new inspection report available for review, click to view! ");
                            _logger.LogInformation("发送通知成功！PatientId：" + patInfo.Pat_MRN + ",EpisodeNo:" + patInfo.Last_Sign_EpisodeNo);
                            //isOk = "1";
                            break;
                    }

                    //发送微信模板消息
                    List<Regcombos> reportInfoList = _tcService.GetClinicalInfo(patInfo.Last_Sign_EpisodeNo, 2);
                    if (reportInfoList != null && reportInfoList.Count > 0 && info.Open_ID != null)
                    {
                        List<TemplateDataObject> dataObjectList = new List<TemplateDataObject>();
                        string url = "";
                        string templateId = "V6scFBNxiwhnfQW0347544D0YtZ8gTmuhvahx9GSzKw";
                        if (info.Language == 1)
                        {
                            dataObjectList.Add(new TemplateDataObject() { field = "first", value = "您有新的检查报告可供查阅", color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "keyword1", value = "详情请进入检查报告页面查看", color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "keyword2", value = reportInfoList.FirstOrDefault()?.CHECKDATE, color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "remark", value = "点击打开曜影医疗APP，查看报告", color = "#173177" });
                            url = "https://a.app.qq.com/o/simple.jsp?pkgname=com.ashermed.sino#opened";
                        }
                        else
                        {
                            dataObjectList.Add(new TemplateDataObject() { field = "first", value = "You have a new Medical Report available", color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "keyword1", value = "For details, please go to the Medical Report page", color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "keyword2", value = reportInfoList.FirstOrDefault().CHECKDATE, color = "#173177" });
                            dataObjectList.Add(new TemplateDataObject() { field = "remark", value = "Tap to enter APP to view", color = "#173177" });
                            url = "https://a.app.qq.com/o/simple.jsp?pkgname=com.ashermed.sino#opened";//"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbd16212a70d55f55&redirect_uri=https%3A%2F%2Fwww.sinounitedhealth.com.cn%2Fpatientportal%2FHomesubscribe&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                        }
                        try
                        {
                            _logger.LogInformation("开始推送SignOff模板消息:" + info.Open_ID);
                            _pubMessageService.SendTemplateMessage(info.Open_ID, templateId, url, dataObjectList);
                            //_logger.LogInformation("完成SignOff模板消息推送:" + info.Open_ID);
                        }
                        catch (System.Exception ex)
                        {
                            _logger.LogError("SignOff模板消息推送失败" + info.Open_ID);
                        }
                    }
                }
            }
        }

        public bool PushUserMessage(int userId, string Business, int jgPushType, string title, string content)
        {
            bool result = false;
            string[] pushKey = new string[1];
            string accptMd = "3";

            //获取用户信息
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1 && !string.IsNullOrEmpty(userInfo.Android_ID))
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_ID;
                    accptMd = "3";
                }
                if (userInfo.Key_Type == 2 && !string.IsNullOrEmpty(userInfo.IOS_ID))
                {
                    //IOS设备
                    pushKey[0] = userInfo.IOS_ID;
                    accptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    //获取用户消息未读数量
                    int unread = _pubMessageInfoRepository.SelectUserUnRead(userId);
                    var pushiResult = _jpushService.JiGuangPush(pushKey, title, content, jgPushType.ToString(), Business, unread.ToString(),
                            accptMd, 1);
                    if (pushiResult.StatusCode == HttpStatusCode.OK)
                    {
                        result = true;
                    }
                }
                // 添加系统消息
                _outNoticeInfoRepository.InsertOutNoticeInfo(new Out_Notice_Info() { Business = Business, Business_Type = jgPushType, Create_Time = DateTime.Now, Create_User = userId, Is_Read = false, Notice_Type = 1, States = 1, Text = content, User_Id = userId });
            }
            return result;
        }


        public int TestSignOff()
        {
            var todayStr = DateTime.Now.ToString("yyyy-MM-dd");
            //var times = new List<string>();
            //times.Add(todayStr);
            //times.Add(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
            var patList = _pubPatInfoRepository.GetSignOffPats(todayStr);
            if (patList != null && patList.Count > 0)
            {
                _logger.LogInformation("发送signoff总数:" + patList.Count);
                var mun = 0;
                foreach (var item in patList)
                {
                    mun++;
                    try
                    {
                        //_logger.LogInformation("发送signoff执行:" + patList.Count);
                        //var exsitAptId = _redisHelper.Get("SignOffSendMsg_" + item.Id + "_" + Convert.ToDateTime(item.Last_Sign_Off).ToString("yyyy-MM-dd"));
                        //if (string.IsNullOrEmpty(exsitAptId))
                        //{
                        _logger.LogInformation("SignOffSendMsgJob:SignOff短信发送患者:" + item.Pat_MRN + "  day:" + item.Last_Sign_Off);
                        //_redisHelper.StringSet("SignOffSendMsg_" + item.Id + "_" + Convert.ToDateTime(item.Last_Sign_Off).ToString("yyyy-MM-dd"), "1", TimeSpan.FromDays(3));
                        SendSignOffMsg(item.Id);
                        //}
                    }
                    catch (System.Exception ee)
                    {
                        _logger.LogError("发送报错:" + item.Pat_MRN + "  msg" + ee.Message);
                        continue;
                    }
                }
                _logger.LogInformation("发送signoff执行结束:" + mun);
            }
            return 1;
        }


    }
}
