using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.App.Entity;
using ASHermed.SinoInterface.Api.ContractModel.App.Model;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using Newtonsoft.Json;
using PoJun.Util;
using PoJun.Util.Maps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using ASHermed.SinoInterface.Api.ContractModel.App.RequestForm;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using ASHermed.SinoInterface.IFramework;
using System.Net;
using ASHermed.SinoInterface.Api.IService.App;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Collections.Concurrent;
using ASHermed.SinoInterface.Enum;
using ASHermed.SinoInterface.Api.IRepository.Quest;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 预约
	/// </summary>
	public class AptService : BaseService, IAptService
    {
        AppConfigurtaion _appConfigurtaion;
        IOutAptInfoRepository _outAptInfoRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        IPubInsuranceRepository _pubInsuranceRepository;
        IPubMapUserPatRepository _pubMapUserPatRepository;
        ITCService _tcService;
        IDoctorService _doctorService;
        IDeptService _deptService;
        IOnlineOrderRepository _onlineOrderRepository;
        IPrescriptionInfoRepository _prescriptionInfoRepository;
        IDicDoctorRepository _dicDoctorRepository;
        IDicDeptRepository _dicDeptRepository;
        ISysRepository _sysRepository;
        IVerifyCodeLogService _verifyCodeLogService;
        RedisHelperClient _redisHelper;
        IOutDoctorAdviceRepository _outDoctorAdviceRepository;
        IPubUserAddressRepository _pubUserAddressRepository;
        HttpClient _httpClient;
        IDicHosRepository _dicHosRepository;
        IDicDiagnosisRepository _dicDiagnosisRepository;
        IOnlineAptInfoRepository _onlineAptInfoRepository;
        ITCPatInfoService _tCPatInfoService;
        ILogger<AptService> _logger;
        IPubUserInfoRepository _pubUserInfoRepository;
        IDicMapDeptServRepository _dicMapDeptServRepository;
        IPubMessageInfoRepository _pubMessageInfoRepository;
        IJpushService _jpushService;
        IOutNoticeInfoRepository _outNoticeInfoRepository;
        IDicMapHosDeptRepository _dicMapHosDeptRepository;
        IOutService _outService;
        IPubSmsLogRepository _pubSmsLogRepository;
        IPubMessageService _pubMessageService;
        IFileService _fileService;
        IFileRepository _fileRepository;
        IVaccineAptRepository _vaccineAptRepository;
        ISmsSurveyService _smsSurveyService;
        ISanFangRepository _sanFangRepository;
        IAuthorizationService _authorizationService;
        IJGPushService _jGPushService;
        IPubQuestDataRepository _pubQuestDataRepository;
        IDataRepository _dataRepository;
        /// <summary>
        /// 预约
        /// </summary>
        public AptService(AppConfigurtaion appConfigurtaion, IOutAptInfoRepository outAptInfoRepository, IPubPatInfoRepository pubPatInfoRepository, ITCService tcService, IDoctorService doctorService, IDeptService deptService, IPubInsuranceRepository pubInsuranceRepository, IPubMapUserPatRepository pubMapUserPatRepository, IOnlineOrderRepository onlineOrderRepository, IPrescriptionInfoRepository prescriptionInfoRepository, IDicDoctorRepository dicDoctorRepository, IDicDeptRepository dicDeptRepository, ISysRepository sysRepository, IVerifyCodeLogService verifyCodeLogService, RedisHelperClient redisHelper, IOutDoctorAdviceRepository outDoctorAdviceRepository, IPubUserAddressRepository pubUserAddressRepository, IHttpClientFactory httpClientFactory, IDicHosRepository dicHosRepository, IDicDiagnosisRepository dicDiagnosisRepository, IOnlineAptInfoRepository onlineAptInfoRepository, ITCPatInfoService tCPatInfoService, ILogger<AptService> logger, IPubUserInfoRepository pubUserInfoRepository, IDicMapDeptServRepository dicMapDeptServRepository, IPubMessageInfoRepository pubMessageInfoRepository, IJpushService jpushService, IOutNoticeInfoRepository outNoticeInfoRepository, IDicMapHosDeptRepository dicMapHosDeptRepository, IOutService outService, IPubSmsLogRepository pubSmsLogRepository, IPubMessageService pubMessageService, IFileService fileService, IFileRepository fileRepository, IVaccineAptRepository vaccineAptRepository, ISmsSurveyService smsSurveyService, ISanFangRepository sanFangRepository, IAuthorizationService authorizationService, IJGPushService jGPushService, IPubQuestDataRepository pubQuestDataRepository, IDataRepository dataRepository)
        {
            _appConfigurtaion = appConfigurtaion;
            _outAptInfoRepository = outAptInfoRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _tcService = tcService;
            _doctorService = doctorService;
            _deptService = deptService;
            _pubInsuranceRepository = pubInsuranceRepository;
            _pubMapUserPatRepository = pubMapUserPatRepository;
            _onlineOrderRepository = onlineOrderRepository;
            _prescriptionInfoRepository = prescriptionInfoRepository;
            _dicDoctorRepository = dicDoctorRepository;
            _dicDeptRepository = dicDeptRepository;
            _sysRepository = sysRepository;
            _verifyCodeLogService = verifyCodeLogService;
            _redisHelper = redisHelper;
            _outDoctorAdviceRepository = outDoctorAdviceRepository;
            _pubUserAddressRepository = pubUserAddressRepository;
            _httpClient = httpClientFactory.CreateClient(HttpClientConst.AdminBase_CLIENT_NAME);
            _dicHosRepository = dicHosRepository;
            _dicDiagnosisRepository = dicDiagnosisRepository;
            _onlineAptInfoRepository = onlineAptInfoRepository;
            _tCPatInfoService = tCPatInfoService;
            _logger = logger;
            _pubUserInfoRepository = pubUserInfoRepository;
            _dicMapDeptServRepository = dicMapDeptServRepository;
            _pubMessageInfoRepository = pubMessageInfoRepository;
            _jpushService = jpushService;
            _outNoticeInfoRepository = outNoticeInfoRepository;
            _dicMapHosDeptRepository = dicMapHosDeptRepository;
            _outService = outService;
            _pubSmsLogRepository = pubSmsLogRepository;
            _pubMessageService = pubMessageService;
            _fileService = fileService;
            _fileRepository = fileRepository;
            _vaccineAptRepository = vaccineAptRepository;
            _smsSurveyService = smsSurveyService;
            _sanFangRepository = sanFangRepository;
            _pubQuestDataRepository = pubQuestDataRepository;
            _authorizationService = authorizationService;
            _jGPushService = jGPushService;
            _dataRepository = dataRepository;
        }

        public Out_Apt_Info Commit(Out_Apt_Info outAptInfo, string hisPatId)
        {
            outAptInfo.Status = 0;//未录入 系统
            outAptInfo.Source_Type = 1;
            // 添加匹配码，便于确认
            outAptInfo.Match_Code = Common.CreateCode(16);
            outAptInfo.Inner_Status = 0;

            if (!string.IsNullOrEmpty(hisPatId) && !string.IsNullOrEmpty(outAptInfo.Apt_Usrn))
            {
                // 将进入TC的预约打上HIS来源标记，方便后续提醒短信的发送
                outAptInfo.Source_Type = outAptInfo.Source_Type | 2;
                //if (_appConfigurtaion.GetAptSwichOn == "true")
                //{
                List<SchedulingParam> list = _outAptInfoRepository.SelectDeptServDoctor(
                        outAptInfo.Hos_Id, outAptInfo.Dept_ID, outAptInfo.Doc_Id,
                        outAptInfo.Apt_Proj, 1, 0);
                SchedulingParam param = new SchedulingParam();
                if (list != null && list.Count > 0)
                {
                    param = list[0];

                    if (_tcService.LockApt(outAptInfo.Apt_Usrn, outAptInfo.Apt_Usrn, "L"))
                    {

                        try
                        {
                            var ret = _tcService.CommitApt(param.His_Dept_Id, param.His_Serv_Id, outAptInfo.Apt_Usrn, outAptInfo.Apt_Usrn, hisPatId);
                            if (ret)
                            {
                                outAptInfo.Status = 1;
                                outAptInfo.Inner_Status = 1;
                            }
                        }
                        catch (System.Exception ex)
                        {
                            _tcService.LockApt(outAptInfo.Apt_Usrn, outAptInfo.Apt_Usrn, "U");
                            throw ex;
                        }
                    }
                }

                // }
            }
            _logger.LogInformation("预约Commit:" + outAptInfo.ToJson());
            var res = _outAptInfoRepository.InsertOutAptInfo(outAptInfo);
            if (res > 0)
            {
                return outAptInfo;
            }
            return null;
        }

        public int QuickCommit(Out_Apt_Info aptInfo, string lastName, string firstName, int gender, string birthday, string patName, string phone, string email, int language)
        {
            if (aptInfo.Pat_Id == 0)
            {
                // 非绑定就诊人
                Pub_Pat_Info patInfo = new Pub_Pat_Info();
                patInfo.Pat_Name = patName;
                patInfo.Last_Name = lastName;
                patInfo.First_Name = firstName;
                patInfo.Gender = gender;
                patInfo.Birthday = birthday;
                patInfo.Phone_NO = phone;
                patInfo.Email = email;
                patInfo.Pat_Source = 2;
                patInfo.Is_Deleted = false;
                var id = _pubPatInfoRepository.InsertPubPatInfo(patInfo);
                aptInfo.Pat_Id = id;
            }
            aptInfo.Source_Type = 16;
            aptInfo.Create_Time = DateTime.Now;
            aptInfo.Status = 0;
            aptInfo.Match_Code = Common.CreateCode(16);
            aptInfo.Inner_Status = 0;
            aptInfo.Channel = 1;
            _logger.LogInformation("快速预约QuickCommit:" + aptInfo.ToJson());
            return _outAptInfoRepository.InsertOutAptInfo(aptInfo);
        }

        public SchedulingSlotList QuerySchedulingSlotListByLanguage(int hosId, int deptId, string fromDate, string toDate, int servId, int language, int aptType)
        {
            List<DoctorWithHosDeptByLanguage> doctorDetailBylanguageList = _doctorService.FindDetailListByLanguage(hosId, deptId, language, aptType);

            SchedulingSlotList schedulingSlotList = new SchedulingSlotList(fromDate, toDate, doctorDetailBylanguageList, language);

            List<SchedulingParamByLanguage> schedulingParamList = _outAptInfoRepository.SelectOnlineDeptServDoctorLanguage(hosId, deptId, 0, servId, language, 0);

            foreach (var map in schedulingParamList)
            {
                string hisDeptId = map.HisDeptId;
                string hisServId = map.HisServId;
                string careProvId = map.CareProvId;

                var scheduling = _tcService.GetScheduling(fromDate, toDate, hisDeptId, hisServId, careProvId);
                if (scheduling != null && scheduling.SlotDateList != null && scheduling.SlotDateList.Count > 0)
                {

                    foreach (var slotDate in scheduling.SlotDateList)
                    {
                        //List<SchedulingSlotBylanguage> list = schedulingSlotList.getSchedulingSlotBylanguages().stream().filter(
                        //        o->o.getDate().equals(slotDate.getDate())).collect(Collectors.toList());
                        List<SchedulingSlotBylanguage> list = schedulingSlotList.SchedulingSlotBylanguages.FindAll(p => p.Date == slotDate.Date);
                        SchedulingSlotBylanguage schedulingSlot = null;
                        if (list != null && list.Count > 0)
                        {
                            schedulingSlot = list[0];

                            foreach (var doctorSlot in schedulingSlot.DoctorWithHosDeptByLanguages)
                            {
                                if (doctorSlot.HasSlot == 1)
                                {
                                    continue;
                                }

                                //List<Resource> resourceList = slotDate.getResourceList().stream().filter(
                                //        o->o.getCareProvID().equals(doctorSlot.getDoctorWithHosDeptByLanguage().getCareProveId().toString()))
                                //        .collect(Collectors.toList());
                                var resourceList = slotDate.ResourceList?.ToList().FindAll(p => p.CareProvID == doctorSlot.DoctorWithHosDeptByLanguage.CareProveId.ToString());
                                // 快速 + 在线
                                if ((doctorSlot.DoctorWithHosDeptByLanguage.AptType & 4) > 0)
                                {
                                    if (resourceList != null && resourceList.Count > 0 && resourceList[0].SlotList != null && resourceList[0].SlotList.Length > 0)
                                    {
                                        doctorSlot.HasSlot = doctorSlot.HasSlot | 1;
                                        schedulingSlot.HasSlot = schedulingSlot.HasSlot | 1;
                                    }
                                }
                            }
                        }


                    }
                }
            }
            return schedulingSlotList;
        }

        public Scheduling QuerySchedulingByApp(int hosId, int deptId, int doctorId, int servId, string fromDate, string toDate, int language)
        {
            List<SchedulingParam> list = _outAptInfoRepository.SelectDeptServDoctor(hosId, deptId, doctorId, servId, language, 0);
            Scheduling scheduling = new Scheduling();
            if (list != null && list.Count > 0)
            {
                string hisDeptId = list[0].His_Dept_Id;
                string hisServId = list[0].His_Serv_Id;
                string careProvId = list[0].Care_Prov_Id;
                scheduling = _tcService.GetScheduling(fromDate, toDate, hisDeptId, hisServId, careProvId);
                scheduling.DeptId = list[0].Apt_Dept_Id;
                scheduling.HosId = hosId != 0 ? hosId.ToString() : "";
                scheduling.ServId = list[0].Serv_Id;
            }

            return scheduling;
        }

        public Scheduling QuerySchedulingByApplet()
        {
            var nowDate = DateTime.Now;
            var fromDate = nowDate.ToString("yyyy-MM-dd");
            var toDate = nowDate.AddDays(30).ToString("yyyy-MM-dd");
            List<SchedulingParam> list = _outAptInfoRepository.SelectDeptServDoctor(0, 0, 0, 0, 1, 0);
            Scheduling scheduling = new Scheduling();

            //ConcurrentBag<int> res = new ConcurrentBag<int>();
            //List<int> ls = new List<int>();
            //for (int i = 0; i < 10000; i++)
            //{
            //    ls.Add(i);
            //}
            //int aa = System.Environment.TickCount;
            //Parallel.ForEach(ls, (op) =>
            //{
            //    Thread.Sleep(1000);
            //    //Interlocked.Increment(ref op);
            //    res.Add(op);
            //});
            //Console.WriteLine(System.Environment.TickCount - aa); //单位毫秒
            if (list != null && list.Count > 0)
            {
                int aa = System.Environment.TickCount;
                scheduling = _tcService.GetScheduling(fromDate, toDate, "49", "115", "98");
                Console.WriteLine(System.Environment.TickCount - aa);

                aa = System.Environment.TickCount;//科室不传
                scheduling = _tcService.GetScheduling(fromDate, toDate, null, "115", "98");
                Console.WriteLine(System.Environment.TickCount - aa);

                aa = System.Environment.TickCount;//医生不传   可
                scheduling = _tcService.GetScheduling(fromDate, toDate, "49", "115", null);
                Console.WriteLine(System.Environment.TickCount - aa);

                aa = System.Environment.TickCount;//服务不传
                scheduling = _tcService.GetScheduling(fromDate, toDate, "49", null, "98");
                Console.WriteLine(System.Environment.TickCount - aa);

                aa = System.Environment.TickCount;//只传科室
                scheduling = _tcService.GetScheduling(fromDate, toDate, "49", null, null);
                Console.WriteLine(System.Environment.TickCount - aa);
                //scheduling = _tcService.GetScheduling(fromDate, toDate, hisDeptId, hisServId, careProvId);
                scheduling.DeptId = list[0].Apt_Dept_Id;
                //scheduling.HosId = hosId != 0 ? hosId.ToString() : "";
                scheduling.ServId = list[0].Serv_Id;
            }

            return scheduling;
        }

        public Dictionary<string, List<SlotDateModel>> QueryOnlineSchedulingByApp(int doctorId, string from, string to)
        {
            List<Scheduling> retList = new List<Scheduling>();
            //获取服务器时间 7天内的
            var nowDate = DateTime.Now;
            var fromDate = nowDate.ToString("yyyy-MM-dd");
            var toDate = nowDate.AddDays(6).ToString("yyyy-MM-dd");
            var docSlot = _dicDoctorRepository.GetDocSlot(doctorId);
            var isLimite = false;//内科,全科不做时间限制  其他科室放9点到15点的号
            var isLimiteWeekend = true;//儿科眼科，号源限制，周一至周五，9点-15点//全部限制双休
            if (docSlot != null && docSlot.Count > 0)
            {
                foreach (var item in docSlot)
                {
                    if (item.DeptId != 17 && item.DeptId != 23)//内科,全科不做时间限制  其他科室放9点到15点的号
                    {
                        isLimite = true;
                    }
                    //if (item.DeptId == 1055 || item.DeptId == 1065)//儿科眼科，号源限制，周一至周五，9点-15点
                    //{
                    //isLimiteWeekend = true;
                    //}
                    Scheduling scheduling = new Scheduling();
                    scheduling = _tcService.GetSchedulingNew(fromDate, toDate, item.HisDeptId + "", item.HisServId + "", item.DocProvId + "");
                    scheduling.DeptId = item.HisDeptId.ToString();
                    scheduling.HosId = "";
                    scheduling.ServId = item.HisServId + "";
                    if (scheduling != null && scheduling.SlotDateList != null && scheduling.SlotDateList.Count > 0)
                    {
                        retList.Add(scheduling);
                    }
                }
            }


            //var list = _doctorService.GetDocHosIds(doctorId);
            //var onlineDepts = _dicDoctorRepository.GetAllOnlineDeptDocInfo();
            //var careProvId = _dicDoctorRepository.GetDocHisCareProvId(doctorId);
            //var onlineDept = onlineDepts.Find(p => p.DocId == doctorId);
            //if (onlineDept != null)
            //{
            //    var hisServ = _dicDeptRepository.GetHisServ(onlineDept.DeptId);
            //    Scheduling scheduling = new Scheduling();
            //    scheduling = _tcService.GetSchedulingNew(from, to, hisServ.HisDeptId + "", hisServ.HisServId + "", careProvId + "");
            //    //scheduling = _tcService.GetSchedulingNew(from, to, "84", "799", careProvId + "");//TODO
            //    scheduling.DeptId = hisServ.HisDeptId.ToString();
            //    scheduling.HosId = "";
            //    scheduling.ServId = hisServ.HisServId + "";
            //    if (scheduling != null && scheduling.SlotDateList != null && scheduling.SlotDateList.Count > 0)
            //    {
            //        retList.Add(scheduling);
            //    }
            //}

            Dictionary<string, List<SlotDateModel>> retDic = new Dictionary<string, List<SlotDateModel>>();
            foreach (var Scheduling in retList)
            {
                if (Scheduling != null && Scheduling.SlotDateList != null && Scheduling.SlotDateList.Count > 0)
                {
                    foreach (var SlotDate in Scheduling.SlotDateList)
                    {
                        var dateTime = SlotDate.Date;
                        if (isLimiteWeekend)
                        {
                            var showTime = Convert.ToDateTime(dateTime);
                            var weekend = (int)showTime.DayOfWeek;
                            if (weekend == 0 || weekend == 6)
                            {
                                continue;
                            }
                        }
                        if (!retDic.ContainsKey(dateTime))
                        {
                            retDic.Add(dateTime, new List<SlotDateModel>());
                        }

                        if (SlotDate != null && SlotDate.ResourceList != null && SlotDate.ResourceList.Length > 0)
                        {
                            foreach (var reso in SlotDate.ResourceList)
                            {
                                if (reso != null && reso.SlotList != null && reso.SlotList.Length > 0)
                                {
                                    foreach (var slot in reso.SlotList)
                                    {
                                        DateTime dtDate;
                                        if (DateTime.TryParse(slot.StartTime, out dtDate))
                                        {
                                            var timeStr = dtDate.ToString("HH:mm");
                                            if (!retDic[dateTime].Where(w => w.Date.Contains(timeStr)).Any())
                                            {
                                                if (isLimite && !IsAptTime(timeStr))//限制科室只放出9-15点的排班
                                                {
                                                    continue;
                                                }
                                                //过滤掉当前时间1小时的排班数据，患者只能预约当前时间1小时候后1周的排班
                                                if (dateTime == DateTime.Now.ToString("yyyy-MM-dd") && !IsAfterOneHour(timeStr))//1小时修改为30分钟
                                                {
                                                    continue;
                                                }
                                                if (dateTime == DateTime.Now.ToString("yyyy-MM-dd") && IsTodayNoonTime(timeStr))//当天11点-13点预约，可约当天13:30之后的
                                                {
                                                    continue;
                                                }
                                                if (IsPassTomorowFirstSlot(dateTime, timeStr))
                                                {
                                                    continue;
                                                }
                                                retDic[dateTime].Add(new SlotDateModel { Date = timeStr, AptUsrn = slot.Usrn, DeptId = Scheduling.DeptId, ServId = Scheduling.ServId });
                                            }
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }
                            }
                        }

                    }
                }

            }
            //var ls = new List<SlotDateModel>();
            //var listkey = retDic.Where(w => w.Key == DateTime.Now.ToString("yyyy-MM-dd"))?.FirstOrDefault().Value;
            //if (listkey != null)
            //{
            //    foreach (var item in listkey)
            //    {
            //        ls.Add(item);
            //    }
            //}

            //DateTime d2 = Convert.ToDateTime(DateTime.Now.AddHours(1).ToString("HH:mm"));
            //foreach (var item in ls)
            //{
            //    DateTime d1 = Convert.ToDateTime(item.Date);
            //    if (DateTime.Compare(d1, d2) < 0)
            //    {
            //        retDic[DateTime.Now.ToString("yyyy-MM-dd")].Remove(item);
            //    }
            //}
            return retDic;
        }

        private bool IsPassTomorowFirstSlot(string slotTimeDate, string slotTimeHour)
        {
            var time = DateTime.Now;
            if (time.Hour >= 18)
            {//晚上约 第二天早上9点30以后的排班
                if (time.AddDays(1).ToString("yyyy-MM-dd") == slotTimeDate)
                {
                    var soltTime = Convert.ToDateTime(slotTimeDate + " " + slotTimeHour);
                    if (soltTime <= Convert.ToDateTime(slotTimeDate + " 09:30"))
                    {
                        return true;
                    }
                }
            }
            if (time.Hour < 9)
            {
                //早上约 今日9点30以后的排班
                if (time.ToString("yyyy-MM-dd") == slotTimeDate)
                {
                    var soltTime = Convert.ToDateTime(slotTimeDate + " " + slotTimeHour);
                    if (soltTime <= Convert.ToDateTime(slotTimeDate + " 09:30"))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool IsAptTime(string timeStr)
        {
            DateTime time = Convert.ToDateTime(timeStr);
            DateTime times = Convert.ToDateTime("09:00");
            DateTime timee = Convert.ToDateTime("17:00");
            if (time > times && time < timee)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool IsAfterOneHour(string timeStr)
        {
            DateTime time = Convert.ToDateTime(timeStr);
            DateTime times = DateTime.Now.AddMinutes(30);
            if (time > times)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool IsTodayNoonTime(string timeStr)
        {
            DateTime time = Convert.ToDateTime(timeStr);
            DateTime curTime = DateTime.Now;
            var today = curTime.ToString("yyyy-MM-dd");
            if (curTime > Convert.ToDateTime(today + " 11:00") && curTime < Convert.ToDateTime(today + " 13:00") && time < Convert.ToDateTime("13:30"))
            {
                return true;
            }
            return false;
        }

        public List<SchedulingParamByLanguage> FindSchedulingParamByLanguage(int hosId, int deptId, int doctorId, int language)
        {
            return _outAptInfoRepository.SelectDeptServDoctorLanguage(hosId, deptId, doctorId, 0, language, 0);
        }

        public List<AptDataResb> FindAptDetailList(int language, int userId, int aptStatus, int year, int aptType)
        {
            List<AptData> list = _outAptInfoRepository.SelectAptWithVaccineApt(language, userId, aptStatus, year, aptType);

            List<AptDataResb> result = new List<AptDataResb>();
            AptDataResb resb = null;

            //SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月");
            for (int i = 0; i < list.Count; i++)
            {
                string time = Convert.ToDateTime(list[i].Apt_Time).ToString("yyyy年MM月");
                if (result.Find(p => p.AptMonth == time) == null)
                {
                    resb = new AptDataResb();
                    resb.AptMonth = time;
                    resb.AptData = new List<AptData>();
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (Convert.ToDateTime(list[j].Apt_Time).ToString("yyyy年MM月") == time)
                        {
                            resb.AptData.Add(list[j]);
                        }
                    }
                    result.Add(resb);
                }


            }
            //TM java写的有问题  再改成现有的集合返回去
            ////string time = sf.format(list.get(i).get("APT_TIME"));

            //List<Map<String, Object>> children = Lists.newLinkedList();
            //for (int j = i; j < list.size(); j++)
            //{
            //    Map<String, Object> data = list.get(j);
            //    if (time.equals(sf.format(data.get("APT_TIME"))))
            //    {
            //        children.add(data);
            //    }
            //    else
            //    {
            //        break;
            //    }
            //    i = j;
            //}
            //param.put("AptMonth", time);
            //param.put("AptData", children);
            //result.add(params);
            return result;
        }

        public bool GetAppointmentsForPatient(string mrn)
        {
            //var response = _tcService.GetAppointmentsForPatient(mrn);
            var res = _tcService.GetEpisodeWithDiagnosesInLastYear(mrn);
            if (res.TotalRows != 0 && res.RowsReturned != 0)//response.TotalRows != 0 && response.RowsReturned != 0 && 
            {
                return true;
            }
            return false;
        }

        public PatMapInsurance GetPatUserInfo(int userId)
        {
            PatMapInsurance response = new PatMapInsurance();
            var patuser = _pubPatInfoRepository.GetPubPatInfoList(userId);
            var insurance = _pubInsuranceRepository.GetPubInsurancesForIds(patuser.Select(w => w.Id).ToList());
            foreach (var item in patuser)
            {
                PatMapInsuranceDetail model = new PatMapInsuranceDetail();
                model.PubPatInfo = item;
                model.PubInsurance = insurance.Where(w => w.PatId == item.Id).FirstOrDefault();
                response.Data.Add(model);
            }
            return response;
        }

        public PatMapInsurance GetPatUserInfoFornewPortal()
        {
            var user = GetBaseUserInfo();
            var pat = GetPatUserInfo(user.ID);
            foreach (var item in pat.Data)
            {
                if (item.PubPatInfo.PayType <= 0 && string.IsNullOrEmpty(item.PubPatInfo.EmergencyName))
                {
                    item.PubPatInfo.IsImproved = true;
                }
            }
            return pat;
        }

        public int InsertPubPatInfo(PatMapInsuranceDetail request)
        {
            var patid = _pubPatInfoRepository.InsertPubPatInfo(request.PubPatInfo);
            request.PubInsurance.PatId = patid;
            _pubMapUserPatRepository.InsertPubMapUserPat(new Pub_Map_User_Pat
            {
                Create_Time = DateTime.Now,
                Is_Deleted = false,
                Pat_ID = patid,
                Relation_Ship = 2,
                Update_Time = DateTime.Now,
                User_ID = request.PubPatInfo.UserID
            });
            _pubInsuranceRepository.AddPubInsurances(request.PubInsurance);
            return 0;
        }

        public PAPerson GetTcUser(string mrn, int language)
        {
            //_tcService.GetScheduling("2021-4-13", "2021-4-13", "84", "311", "");
            //_tcService.GetAppointmentsForPatient("P0002606");
            //_tcService.GetPatient("P0002606", "", "");
            //_tcService.AddTcPatInfo(new Pub_Pat_Info { Gender = 1, Phone_NO="13425113567", Last_Name="ces",First_Name="name",Pat_Name="cesname", Birthday="1990-10-13", });
            //_tcService.GetEpisodeWithDiagnosesInLastYear(mrn);
            //_tcService.LockAptSave("722||7742-65847-1100-311-1", "722||7742-65847-1100-311-1", "L");
            //_tcService.CommitApt("", "", "722||7742-65847-1100-311-1", "722||7742-65847-1100-311-1", "P0002606");
            //_tcService.CancelAppt("722||7742-65847-1100-311-1", "722||7742-65847-1100-311-1");
            var pat = _tcService.GetPatient(mrn, "", "").FirstOrDefault();
            pat.PAPERName = pat.PAPERName + pat.PAPERName2;
            pat.PAPERDobStr = pat.PAPERDob.ToString("yyyy-MM-dd");
            if (language == 1)
            {
                pat.PAPERSex = pat.PAPERSex == "男 Male" ? "男" : "女";
                pat.Gender = pat.PAPERSex == "男 Male" ? 1 : 0;
            }
            else
            {
                pat.PAPERSex = pat.PAPERSex == "男 Male" ? "Male" : "Female";
                pat.Gender = pat.PAPERSex == "男 Male" ? 1 : 0;
            }
            pat.PAPERAge = pat.PAPERAge.Split(' ')[0];
            return pat;
        }

        public List<MyAppointment> GetMyAppointment(int type, int pat, int year)
        {
            var outauthpats = _authorizationService.GetUserAuthPats(GetBaseUserInfo().ID, 1);
            var onlineauthpats = _authorizationService.GetUserAuthPats(GetBaseUserInfo().ID, 2);
            DateTime begin = DateTime.MinValue;
            DateTime end = DateTime.MinValue;
            if (year != 0)
            {
                begin = DateTime.Parse(year + "-01-01 00:00");
                end = DateTime.Parse(year + "-12-31 23:59");
            }

            List<MyAppointment> response = new List<MyAppointment>();
            var list = new List<MyAppointment>();
            List<int> onlinepats = new List<int>();
            //线上预约在待确认中不显示，直接显示在即将就诊中
            if (type != 1)
            {
                if (pat != 0)
                {
                    if (onlineauthpats.Where(w => w.Id == pat).Any())
                    {
                        onlinepats.Add(pat);
                    }
                }
                else
                {
                    onlinepats = onlineauthpats.Select(w => w.Id).ToList();
                }
                var helper = _sysRepository.GetSysHelpers("医助")?.FirstOrDefault();
                list = _pubPatInfoRepository.GetonlineMyAppointment(type, onlinepats, begin, end, false)?.ToList();
                list.ForEach(w =>
                {
                    if (w.LinKingAptStatus == 8 && (w.Status == 2 || w.Status == 4))
                    {
                        w.Status = 6;
                    }
                    w.HelperImId = helper.ImId;
                });
            }
            var docsInfo = _dicDoctorRepository.GetAllOnlineDeptDocInfo();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var doc = docsInfo.Find(p => p.DocId == item.DocId);
                    if (doc != null)
                    {
                        item.DeptId = doc.DeptId;
                        item.DocCNName = doc.DocNameCn;
                        item.DocENName = doc.DocNameEn;
                        item.DeptCNName = doc.DeptNameCn;
                        item.DeptENName = doc.DeptNameEn;
                    }
                }
                //线上预约
                response.AddRange(list);
            }

            //线下预约没有待支付这一选项
            if (type != 0)
            {
                #region  线下预约
                //线下预约,现在改为获取线下TC的预约记录，不走数据库了 除了待确认，待确认走线下表
                GetAllPatDetailForPatsRequest request = new GetAllPatDetailForPatsRequest();
                if (pat != 0)
                {
                    if (outauthpats.Where(w => w.Id == pat).Any())
                    {
                        request.Patids.Add(pat);
                    }
                }
                else
                {
                    //var pats = _pubPatInfoRepository.GetUserRelationship(GetBaseUserInfo().ID);
                    var pats = outauthpats;
                    request.Patids = pats.Select(w => w.Id).ToList();
                }
                request.Year = year;
                request.Type = type;
                HttpContent content = new StringContent(JsonConvert.SerializeObject(request));
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var res = new BaseResponse<List<MyAppointment>>();
                res.Data = new List<MyAppointment>();
                if (request.Patids.Count() > 0)
                {
                    res = JsonConvert.DeserializeObject<BaseResponse<List<MyAppointment>>>(_httpClient.PostAsync("Admin/Api/User/GetAllPatDetailForPats", content).Result.Content.ReadAsStringAsync().Result);
                }
                if (year != 0)
                {
                    res.Data = res.Data.Where(w => w.AptTime >= begin && w.AptTime <= end).ToList();
                }

                //获取outaptinfo数据，通过患者ID与usrn     或者 患者ID与预约时间来查找本次预约
                var outApp = _pubPatInfoRepository.GetOutMyAppointmentForPat(request.Patids);
                foreach (var item in res.Data)
                {
                    if (!request.Patids.Contains(item.PatId))
                    {
                        continue;
                    }
                    var app = new MyAppointment();
                    app = outApp.Where(w => w.PatId == item.PatId && w.Usrn == item.Usrn).FirstOrDefault();
                    if (app == null)
                    {
                        app = outApp.Where(w => w.PatId == item.PatId && w.AptTime == item.AptTime).FirstOrDefault();
                    }
                    if (app != null)
                    {
                        if (app.DocId != 0 || app.DeptId != 0)
                        {
                            if (!(app.Status == 1 && item.Status == 4))
                            {
                                app.Status = item.Status;
                            }
                            response.Add(app);
                        }
                        else
                        {
                            item.DocImage = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/微信图片_20210713185519_74174720210713185531698.png";
                            response.Add(item);
                        }
                    }
                    else
                    {
                        item.DocImage = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/微信图片_20210713185519_74174720210713185531698.png";
                        response.Add(item);
                    }
                }
                if (request.Patids.Count() > 0)
                {
                    if (type == -1 || type == 1)
                    {
                        //待确认状态走线下表
                        var outappdata = _pubPatInfoRepository.GetOutMyAppointmentForUnconfirmed(request.Patids, begin, end);
                        foreach (var item in outappdata)
                        {
                            if (!response.Where(w => w.ID == item.ID).Any())
                            {
                                response.Add(item);
                            }
                        }
                    }

                    //疫苗
                    response.AddRange(_pubPatInfoRepository.GetVaccineMyAppointment(GetBaseUserInfo().ID, type, pat, begin, end));
                    //核酸
                    response.AddRange(_pubPatInfoRepository.GetNucleicAcidMyAppointment(GetBaseUserInfo().ID, type, pat, begin, end));
                }
                #endregion
            }
            response = response.Where(w => w.AptTime != DateTime.MinValue && w.AptTime != DateTime.MaxValue).ToList();
            //过滤疫苗预约数据
            response = response.Where(w => w.SourceType != 256).ToList();
            return response;
        }

        public List<MyAppointment> GetOutAptForNewPortal(int type, int language, int pat = 0)
        {
            DateTime begin = DateTime.MinValue;
            DateTime end = DateTime.MinValue;
            //if (year != 0)
            //{
            //    begin = DateTime.Parse(year + "-01-01 00:00");
            //    end = DateTime.Parse(year + "-12-31 23:59");
            //}

            List<MyAppointment> response = new List<MyAppointment>();
            var authpats = _authorizationService.GetUserAuthPats(GetBaseUserInfo().ID, 1);
            #region  线下预约
            //线下预约,现在改为获取线下TC的预约记录，不走数据库了 除了待确认，待确认走线下表
            GetAllPatDetailForPatsRequest request = new GetAllPatDetailForPatsRequest();
            if (pat != 0)
            {
                if (!authpats.Where(w => w.Id == pat).Any())
                {
                    return response;
                }
                request.Patids.Add(pat);
            }
            else
            {
                //var pats = _pubPatInfoRepository.GetUserRelationship(GetBaseUserInfo().ID);
                var pats = authpats;
                request.Patids = pats.Select(w => w.Id).ToList();
            }
            request.Type = type;
            HttpContent content = new StringContent(JsonConvert.SerializeObject(request));
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var res = JsonConvert.DeserializeObject<BaseResponse<List<MyAppointment>>>(_httpClient.PostAsync("Admin/Api/User/GetOutAptForNewPortal", content).Result.Content.ReadAsStringAsync().Result);
            //if (year != 0)
            //{
            //    res.Data = res.Data.Where(w => w.AptTime >= begin && w.AptTime <= end).ToList();
            //}

            //获取outaptinfo数据，通过患者ID与usrn     或者 患者ID与预约时间来查找本次预约
            var outApp = _pubPatInfoRepository.GetOutMyAppointmentForPat(request.Patids);
            foreach (var item in res.Data)
            {
                var app = new MyAppointment();
                app = outApp.Where(w => w.PatId == item.PatId && w.Usrn == item.Usrn).FirstOrDefault();
                if (app == null)
                {
                    app = outApp.Where(w => w.PatId == item.PatId && w.AptTime == item.AptTime).FirstOrDefault();
                }
                if (app != null)
                {
                    if (app.DocId != 0 || app.DeptId != 0)
                    {
                        if (!(app.Status == 1 && item.Status == 4))
                        {
                            app.Status = item.Status;
                        }
                        app.Remark = item.Remark;
                        response.Add(app);
                    }
                    else
                    {
                        item.DocImage = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/微信图片_20210713185519_74174720210713185531698.png";
                        response.Add(item);
                    }
                }
                else
                {
                    item.DocImage = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/微信图片_20210713185519_74174720210713185531698.png";
                    response.Add(item);
                }
            }

            if (type == -1 || type == 1)
            {
                //待确认状态走线下表
                var outappdata = _pubPatInfoRepository.GetOutMyAppointmentForUnconfirmed(request.Patids, begin, end);
                foreach (var item in outappdata)
                {
                    if (!response.Where(w => w.ID == item.ID).Any())
                    {
                        response.Add(item);
                    }
                }
            }

            foreach (var item in response)
            {
                //if (DateTime.Now.ToString("yyyy-MM-dd") == item.AptTime.ToString("yyyy-MM-dd"))
                //{
                //    item.IsNeedQuest = true;
                //}
                //if (item.PatId != 0)
                //{
                //    var questdata = _pubQuestDataRepository.GetPatQuestData(item.PatId, 3, item.AptTime);
                //    if (questdata.Any())
                //    {
                //        item.IsAnswer = true;
                //        item.IsPass = questdata.FirstOrDefault().IsPass;
                //    }
                //}

                if (language == 1)
                {
                    item.HosName = item.HosCNName;
                    item.DeptName = item.DeptCNName;
                    item.DocName = item.DocCNName;
                    item.ServName = item.ServCNName;
                }
                else
                {
                    item.HosName = item.HosENName;
                    item.DeptName = item.DeptENName;
                    item.DocName = item.DocENName;
                    item.ServName = item.ServENName;
                    if (item.Remark == "健康评估")
                    {
                        item.Remark = "Health Evaluation";
                    }
                    if (item.Remark == "流感疫苗")
                    {
                        item.Remark = "Vaccine";
                    }
                }
                if (item.Remark == "健康评估" || item.Remark == "Health Evaluation")
                {
                    item.WechatStatus = 2;
                }
                if (item.Remark == "流感疫苗" || item.Remark == "Vaccine")
                {
                    item.WechatStatus = 1;
                }
            }

            if (type == 1)
            { response = response.Where(w => w.Status == 1).ToList(); }
            if (type == 5)
            { response = response.Where(w => w.Status == 2 || w.Status == 5 || (w.Status == 4 && w.AptTime.Date < DateTime.Now.Date)).ToList(); }
            if (type == 4)
            { response = response.Where(w => w.Status == 4).ToList(); }

            #endregion

            response = response.Where(w => w.AptTime != DateTime.MinValue && w.AptTime != DateTime.MaxValue).ToList();
            response = response.OrderByDescending(w => w.AptTime).ThenByDescending(t=>t.CreateTime).ToList();
            return response;
        }

        public List<MyAppointment> GetCignaAppointment(int type, int pat, int year)
        {
            if (string.IsNullOrEmpty(GetBaseUserInfo().U_Id))
            {
                return new List<MyAppointment>();
            }

            DateTime begin = DateTime.MinValue;
            DateTime end = DateTime.MinValue;
            if (year != 0)
            {
                begin = DateTime.Parse(year + "-01-01 00:00");
                end = DateTime.Parse(year + "-12-31 23:59");
            }

            List<MyAppointment> response = new List<MyAppointment>();
            var helper = _sysRepository.GetSysHelpers("医助")?.FirstOrDefault();
            var list = _pubPatInfoRepository.GetCignaAppointment(GetBaseUserInfo().ID, type, pat, begin, end)?.ToList();
            list.ForEach(w =>
            {
                if (w.LinKingAptStatus == 8 && (w.Status == 2 || w.Status == 4))
                {
                    w.Status = 6;
                }
                w.HelperImId = helper.ImId;
            });

            var docsInfo = _dicDoctorRepository.GetAllOnlineDeptDocInfo();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var doc = docsInfo.Find(p => p.DocId == item.DocId);
                    if (doc != null)
                    {
                        item.DeptId = doc.DeptId;
                        item.DocCNName = doc.DocNameCn;
                        item.DocENName = doc.DocNameEn;
                        item.DeptCNName = doc.DeptNameCn;
                        item.DeptENName = doc.DeptNameEn;
                    }
                }
                //线上预约
                response.AddRange(list);
            }

            return response;
        }


        public MyAppointmentDetail GetMyAppointmentDetail(int Id, int myAppointmentType, int language, DateTime apttime, int patid)
        {
            MyAppointmentDetail response = new MyAppointmentDetail();
            switch (myAppointmentType)
            {
                case 0:
                    response = _pubPatInfoRepository.GetNucleicAcidMyAppointmentDetail(Id);
                    response.Notice = _appConfigurtaion.AptType3;
                    break;
                case 1:
                    response = _pubPatInfoRepository.GetonlineMyAppointmentDetail(Id);
                    response.Notice = _appConfigurtaion.AptType1;
                    response.OrderDetail = _onlineOrderRepository.GetOrderDetailForAptId(response.ID.ToString(), language);
                    break;
                case 2:
                    response = _pubPatInfoRepository.GetonlineMyAppointmentDetail(Id);
                    response.Notice = _appConfigurtaion.AptType2;
                    response.OrderDetail = _onlineOrderRepository.GetOrderDetailForAptId(response.ID.ToString(), language);
                    break;
                case 3:
                    response = _pubPatInfoRepository.GetOutMyAppointmentDetail(Id);
                    response.Notice = _appConfigurtaion.AptType3;
                    break;
                case 4:
                    response = _pubPatInfoRepository.GetVaccineMyAppointmentDetail(Id);
                    response.Notice = _appConfigurtaion.AptType3;
                    break;
                case 6:
                    response = GetMyAppointmentOut(apttime, patid);
                    response.Notice = _appConfigurtaion.AptType3;
                    break;
                default:
                    break;
            }
            return response;
        }

        private MyAppointmentDetail GetMyAppointmentOut(DateTime apttime, int patid)
        {
            var pat = _pubPatInfoRepository.SelectPatById(patid);
            MyAppointmentDetail response = new MyAppointmentDetail();
            GetAllPatDetailForPatsRequest request = new GetAllPatDetailForPatsRequest();
            request.Patids.Add(patid);
            request.Year = 0;
            request.Type = -1;
            HttpContent content = new StringContent(JsonConvert.SerializeObject(request));
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var res = JsonConvert.DeserializeObject<BaseResponse<List<MyAppointment>>>(_httpClient.PostAsync("Admin/Api/User/GetAllPatDetailForPats", content).Result.Content.ReadAsStringAsync().Result);


            var data = res.Data.Where(w => w.AptTime == apttime)?.FirstOrDefault();
            var hos = _dicHosRepository.GetHosByHosCode(data.HosCNName);
            response.ID = 0;
            response.AptTime = data.AptTime;
            response.Status = data.Status;
            response.Remark = "";
            response.CreateTime = DateTime.Now;
            response.PatId = patid;
            response.PatName = pat.PatName;
            response.PID = pat.PatMrn;
            response.Phone = pat.PhoneNo;
            response.HosId = hos == null ? 0 : hos.Id;
            response.HosCNName = hos?.CN_Name;
            response.HosENName = hos?.EN_Name;
            response.LONGITUDE = hos?.Longitude;
            response.LATITUDE = hos?.Latitude;
            response.HosCNAddr = hos?.CN_SMS_Addr;
            response.HosENAddr = hos?.EN_SMS_Addr;
            response.HosCNPhone = hos?.CN_Mobile;
            response.HosENPhone = hos?.EN_Mobile;
            response.DeptId = 0;
            response.DeptCNName = data.DeptCNName;
            response.DeptENName = data.DeptENName;
            response.DocId = 0;
            response.DocCNName = data.DocCNName;
            response.DocENName = data.DocENName;
            response.DocImage = "";
            response.MyAppointmentType = 6;
            response.DocImage = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/微信图片_20210713185519_74174720210713185531698.png";
            response.PADDRESSCN = hos.P_ADDRESS_CN;
            response.PADDRESSEN = hos.P_ADDRESS_EN;
            response.PADDRESSLAT = hos.P_ADDRESS_LAT;
            response.PADDRESSLON = hos.P_ADDRESS_LON;
            //if (DateTime.Now.ToString("yyyy-MM-dd") == data.AptTime.ToString("yyyy-MM-dd"))
            //{
            //    response.IsNeedQuest = true;
            //}
            //if (patid != 0)
            //{
            //    var questdata = _pubQuestDataRepository.GetPatQuestData(patid, 3, data.AptTime);
            //    if (questdata.Any())
            //    {
            //        response.IsAnswer = true;
            //        response.IsPass = questdata.FirstOrDefault().IsPass;
            //        response.QuestTime = questdata.FirstOrDefault().CreateTime;
            //    }
            //}
            response.IsNeedQuest = true;
            if (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(response.AptTime.ToString("yyyy-MM-dd")))
            {
                var questData = _pubQuestDataRepository.GetPatQuestData(patid, 3, data.AptTime);
                if (DateTime.Now.ToString("yyyy-MM-dd") == response.AptTime.ToString("yyyy-MM-dd"))
                {
                    if (questData.Any())
                    {
                        if (questData != null && questData.FirstOrDefault().CreateTime.ToString("yyyy-MM-dd") == response.AptTime.ToString("yyyy-MM-dd"))
                        {
                            response.IsAnswer = true;
                            response.IsPass = questData.FirstOrDefault().IsPass;
                            response.QuestTime = questData.FirstOrDefault().CreateTime;
                        }
                    }
                }
                else if (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")) < Convert.ToDateTime(response.AptTime.ToString("yyyy-MM-dd")))
                {
                    if (questData.Any())
                    {
                        response.IsAnswer = true;
                        response.IsPass = questData.FirstOrDefault().IsPass;
                        response.QuestTime = questData.FirstOrDefault().CreateTime;
                    }
                }
            }
            else
            {
                response.IsNeedQuest = false;
            }
            return response;
        }

        public MyPrescription GetMyPrescription(int status, int patId, string useragent = "sino")
        {
            var user = GetBaseUserInfo();
            MyPrescription response = new MyPrescription();
            List<Out_Internet_Prescription_Info> info = new List<Out_Internet_Prescription_Info>();

            var authpat = new List<Pub_Pat_Info>();
            authpat = _authorizationService.GetUserAuthPats(user.ID, (int)AuthType.ONLINE);
            if (patId != 0)
            {
                if (!authpat.Where(w => w.Id == patId).Any())
                {
                    return response;
                }
                else
                {
                    info = _prescriptionInfoRepository.GetPrescriptionForPatId(patId, status).ToList();
                }
            }
            else
            {
                foreach (var item in authpat)
                {
                    info.AddRange(_prescriptionInfoRepository.GetPrescriptionForPatId(item.Id, status).ToList());
                }
            }

            var de = _prescriptionInfoRepository.GetPrescriptionDrug(info.Select(w => w.Prescription_No).ToList()).ToList();
            response.Info = info.MapTo<List<MyPrescriptionList>>();
            Parallel.ForEach(response.Info, w =>
            {
                int count = 0;
                w.Detail = de.Where(f => f.Prescripton_No == w.Prescription_No).ToList();
                foreach (var item in w.Detail)
                {
                    count += item.Cnt;
                }
                w.DetailCount = count;
            });
            return response;
        }


        public MyPrescriptionDetail GetMyPrescriptionDetail(string orderNo, int language)
        {
            MyPrescriptionDetail response = new MyPrescriptionDetail();
            var info = _prescriptionInfoRepository.GetPrescriptionForId(orderNo, language);
            List<string> list = new List<string>();
            list.Add(info.Prescription_No);
            var de = _prescriptionInfoRepository.GetPrescriptionDrug(list).ToList();
            response = info.MapTo<MyPrescriptionDetail>();
            response.Detail = de.Where(f => f.Prescripton_No == response.Prescription_No).ToList();
            response.OrderDetail = _onlineOrderRepository.GetOrderDetailForPrescriptionAptId(response.Id);
            //if (response.OrderDetail.OrderStatus == 6 || response.OrderDetail.OrderStatus == 7 || response.OrderDetail.OrderStatus == 8)
            //{
            //    response.Status = response.OrderDetail.OrderStatus;
            //}
            var order = _onlineOrderRepository.GetOrderByNo(orderNo);
            if (order != null)
            {
                response.InsuranceInfo = _pubInsuranceRepository.GetPubInsuranceById(order.InsuranceId);
                response.OrderDetail.PayWay = order.PayWay;
                response.OrderDetail.PayTime = order.PayTime;
            }
            return response;
        }

        public CignaPrescriptionDetail GetCignaPrescriptionDetail(string orderNo, int language)
        {
            var dia = _dicDiagnosisRepository.GetDiagnoseList(orderNo);
            CignaPrescriptionDetail response = new CignaPrescriptionDetail();
            response.Order = _onlineOrderRepository.GetOrderByNo(orderNo);
            response.PatInfo = _pubPatInfoRepository.SelectById(response.Order.PatId);
            response.PrescriptionInfo = _prescriptionInfoRepository.GetPrescriptionForId(orderNo, language);
            if (response.PrescriptionInfo != null)
            {
                response.PrescriptionInfo.AllergyHistory = dia?.FirstOrDefault()?.AllergyHistory;
                List<string> list = new List<string>();
                list.Add(response.PrescriptionInfo?.Prescription_No);
                response.DrugDetail = _prescriptionInfoRepository.GetPrescriptionDrug(list).ToList();
            }
            else
            {
                response.PrescriptionInfo = new Out_Internet_Prescription_Info();
                response.PrescriptionInfo.Patient_Name = response.PatInfo.Pat_Name;
                response.PrescriptionInfo.Patient_Sex = response.PatInfo.Gender == 0 ? "female" : "male";
                response.PrescriptionInfo.Patient_Birthday = response.PatInfo.Birthday;
                response.PrescriptionInfo.PID = response.PatInfo.Pat_MRN;
                var apt = _onlineAptInfoRepository.GetAptInfo(response.Order.AptId);
                response.PrescriptionInfo.Dept_Name = _dicDeptRepository.SelectByIdLanguage(language, apt.DeptId)?.Name;
                var doc = _dicDoctorRepository.SelectByPrimaryKey(response.Order.DocId);
                response.PrescriptionInfo.Doc_Name = language == 2 ? doc.EN_Name : doc.CN_Name;
                response.PrescriptionInfo.AllergyHistory = dia?.FirstOrDefault()?.AllergyHistory;
                response.PrescriptionInfo.Appt_Number = response.Order.OrderNo;
                response.PrescriptionInfo.Diagnosis = dia?.FirstOrDefault()?.Diagnosis;
                response.DrugDetail = new List<Out_Internet_Prescription_Drug>();
            }
            //var user = _pubPatInfoRepository.GetUserByPatIds(response.Order.PatId);

            return response;
        }

        public int UpdatePrescriptionStatus(string orderNo, int status)
        {
            //推药助
            if (status == 1024)
            {
                var order = _onlineOrderRepository.GetOrderByNo(orderNo);
                var mhelper = _sysRepository.GetSysHelpers("药助")?.FirstOrDefault();
                if (mhelper != null)
                {
                    if (order.IsInsuranceUser)
                    {
                        _verifyCodeLogService.SendCignaSMS(mhelper.Phone, "新的订单已签收，请及时向患者进行用药宣教(保险客户)");
                    }
                    else
                    {
                        _verifyCodeLogService.SendCusSms(mhelper.Phone, "新的订单已签收，请及时向患者进行用药宣教", 1);
                    }
                }
            }
            return _prescriptionInfoRepository.UpdatePrescriptionStatusForOrder(orderNo, status);
        }

        public List<AptInfos> FindLastAptByPat(string patId)
        {
            List<AptInfos> aptInfoList = _outAptInfoRepository.SelectAptsByPat(patId);
            aptInfoList = aptInfoList.FindAll(p => p.Apt_Time > DateTime.Now);
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //aptInfoList = aptInfoList.stream().filter(o-> {
            //    try
            //    {
            //        return sdf.parse(o.get("APT_TIME").toString()).after(new Date());
            //    }
            //    catch (ParseException e)
            //    {
            //        e.printStackTrace();
            //        return false;
            //    }
            //}).collect(Collectors.toList());

            //Map<String, Object> map = Collections.min(aptInfoList, (o1, o2)-> {
            //    Date date1 = new Date();
            //    Date date2 = new Date();
            //    try
            //    {
            //        date1 = sdf.parse(o1.get("APT_TIME").toString());
            //        date2 = sdf.parse(o2.get("APT_TIME").toString());
            //    }
            //    catch (ParseException e)
            //    {
            //        e.printStackTrace();
            //    }
            //    return date2.compareTo(date1);
            //});
            return aptInfoList;
        }

        public bool OutAptUpdateStatus()
        {
            var data = _outAptInfoRepository.GetAllOutAptData();
            foreach (var item in data)
            {
                _outAptInfoRepository.UpdateOutAptStatus(item, 4);
            }
            return true;
        }

        public OnlineSearchResult OnlineSearch(string keyWords, int language)
        {
            OnlineSearchResult res = new OnlineSearchResult();
            var docs = _doctorService.GetAllOnlineDoctors(language, keyWords);
            res.DocList = docs;
            res.DeptList = new List<DeptByLanguage>();
            res.DeptList.AddRange(_deptService.SelectOnlineByLanguage(keyWords, language, 1));
            var revist = _deptService.SelectOnlineByLanguage(keyWords, language, 2);
            var idList = res.DeptList.Select(p => p.Id);
            foreach (var item in revist)
            {
                if (!idList.Contains(item.Id))
                {
                    res.DeptList.Add(item);
                }
            }
            res.DeptList = res.DeptList.FindAll(p => p.Id != 0);
            return res;
        }


        public BaseResponse<bool> AddVaccineAppt(VaccineApptRequest request, int language = 1)
        {
            BaseResponse<bool> response = new BaseResponse<bool>();
            request.PatIds = request.PatIds.Distinct().ToArray();
            var pats = _pubPatInfoRepository.SelectByIds(request.PatIds.ToList());
            Pub_User_Info user = GetBaseUserInfo();
            //每个用户下面只能有6个排队中的患者
            var patids = _pubPatInfoRepository.GetPatIdsByUserId(user.ID);
            var count = _pubPatInfoRepository.GetOutVaccineApptList(patids.Select(w => w.Pat_ID).ToList(), 4);
            if (patids.Where(w => w.Relation_Ship == 8).Any())
            {
                _pubPatInfoRepository.UpdateMapUserPatRelation(user.ID);
            }
            bool authpass = true;
            var authpasscontent = "";
            var authpats = _authorizationService.GetUserAuthPats(user.ID, 1);
            foreach (var item in request.PatIds)
            {
                if (!authpats.Where(w => w.Id == item).Any())
                {
                    if (language != 1)
                    {
                        authpasscontent = "患者：" + pats.Where(w => w.Id == item).FirstOrDefault().Pat_Name + "没有授权，请授权后再登记排队";
                    }
                    else
                    {
                        authpasscontent = "Authorization required for patient(" + pats.Where(w => w.Id == item).FirstOrDefault().Pat_Name + ")";
                    }
                    authpass = false;
                }
            }
            if (!authpass)
            {
                response.Code = 0;
                response.Data = false;
                response.Msg = authpasscontent;

                return response;
            }

            if (count.Where(w => w.Status == 4).ToList().Count + request.PatIds.Length > 6)
            {
                response.Code = 0;
                response.Data = false;
                if (language != 1)
                {
                    response.Msg = "You can add up to 6 patient";
                }
                else
                {
                    response.Msg = "最多只能预约6个，请勿多次提交";
                }
                return response;
            }

            //Pub_User_Info user = new Pub_User_Info { ID = 1234, Nick_Name = "lalal" };
            var data = _pubPatInfoRepository.GetOutVaccineApptList(request.PatIds.ToList(), 4);
            var disdata = new List<VaccineApptIsAdd>();
            pats.ForEach(w => { disdata.AddRange(_pubPatInfoRepository.VaccineApptIsAdd(w.Pat_Name, w.Phone_NO)); });
            List<string> contentpat = new List<string>();
            foreach (var item in request.PatIds)
            {
                var pat = pats.Where(w => w.Id == item).FirstOrDefault();
                if (pat != null)
                {
                    if (string.IsNullOrEmpty(pat.Pat_Name) || string.IsNullOrEmpty(pat.Birthday) || string.IsNullOrEmpty(pat.Phone_NO) || string.IsNullOrEmpty(pat.Card_ID) || pat.Gender == null)
                    {
                        contentpat.Add(pat.Pat_Name);
                    }
                }
            }
            if (contentpat.Any())
            {
                var setting = new JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                };
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (language != 1)
                {
                    dic.Add("key", string.Join(",", contentpat) + " You cannot register for the queue, please complete the patient information first");
                }
                else
                {
                    dic.Add("key", string.Join(",", contentpat) + " 患者信息暂未完善，无法登记排队，请完善信息后登记");
                }
                dic.Add("value", JsonConvert.SerializeObject(pats.Where(w => w.Pat_Name == contentpat[0]).FirstOrDefault(), setting));
                response.Code = 12;
                response.Data = false;
                response.Msg = JsonConvert.SerializeObject(dic);
                return response;
            }
            if (data.Where(w => w.Status == 4).Any())
            {
                List<string> content = new List<string>();
                foreach (var item in request.PatIds)
                {
                    var itempat = pats.Where(w => w.Id == item);
                    if (!itempat.Any())
                    {
                        content.Add(item.ToString());
                    }
                    else
                    {
                        if (data.Where(w => w.PatId == item).Any())
                        {
                            content.Add(itempat.FirstOrDefault().Pat_Name);
                        }
                    }
                }
                response.Code = 0;
                response.Data = false;
                if (language != 1)
                {
                    response.Msg = string.Join(",", content) + " has already submitted once. Please don't submit again";
                }
                else
                {
                    response.Msg = string.Join(",", content) + " 已经提交申请，请勿重复提交";
                }
                return response;
            }
            //判断相同姓名与手机号是否已经提交过排队了
            foreach (var item in request.PatIds)
            {
                var pat = pats.Where(w => w.Id == item)?.FirstOrDefault();
                if (disdata.Where(w => w.PatName == pat.Pat_Name && w.Phone == pat.Phone_NO).Any())
                {
                    contentpat.Add(pat.Pat_Name);
                }
            }
            if (contentpat.Any())
            {
                response.Code = 0;
                response.Data = false;

                if (language != 1)
                {
                    response.Msg = string.Join(",", contentpat) + " has already submitted once. Please don't submit again";
                }
                else
                {
                    response.Msg = string.Join(",", contentpat) + "  已经提交申请，请勿重复提交";
                }
                return response;
            }

            foreach (var item in request.PatIds)
            {
                Thread.Sleep(200);
                _tCPatInfoService.SavePatMrn(item);
                var flowid = _pubPatInfoRepository.InsertOutVaccineApptFlow(new Out_Vaccine_Appt_Flow
                {
                    CREATE_TIME = DateTime.Now,
                    CREATE_USER = user.ID.ToString(),
                    RESOUCE_TYPE = 1,
                    STATUS = 1,
                    REQUEST_PARAM = JsonConvert.SerializeObject(request)
                });
                var model = new Out_Vaccine_Appt
                {
                    FLOW_ID = flowid,
                    PAT_ID = item,
                    USER_ID = user.ID,
                    VACCINE_ID = 1,
                    PAY_TYPE = 1,
                    IS_TREATMENT = false,
                    INSURANCE_ID = 0,
                    INSURANCE_NO = "",
                    PAY_IMAGE = "",
                    HPV_TYPE = "",
                    HPT_PIN = "",
                    ORIGIN = request.Origin,
                    STATUS = 4,
                    MATCH_CODE = "",
                    APT_TIME = DateTime.MinValue,
                    HOS_ID = 0,
                    DEPT_ID = 0,
                    DOC_ID = 0,
                    REMAKE = request.Remake,
                    CREATE_USER = user.Nick_Name,
                    CREATE_TIME = DateTime.Now,
                    LANGUAGE = 1,
                    NewVaccineType = 1,
                    QueueNumber = GetOutVaccineApptQueueNumber(),
                    UPDATE_TIME = DateTime.Now
                };
                _pubPatInfoRepository.InsertOutVaccineAppt(model);
            }
            response.Msg = "成功";
            response.Code = 1;
            response.Data = true;
            return response;
        }

        public bool CancelVaccineAppt(int flowid)
        {
            var res = _pubPatInfoRepository.UpdateOutVaccineApptStauts(flowid);
            if (res > 0)
            {
                return true;
            }
            else { return false; }
        }

        public List<VaccineApptForUser> GetOutVaccineApptList(int status, int language)
        {
            List<Pub_Pat_Info> pat = _authorizationService.GetUserAuthPats(GetBaseUserInfo().ID, (int)AuthType.ONLINE);
            //var pat = _pubPatInfoRepository.GetUserRelationship(GetBaseUserInfo().ID);
            // status 4全部 3排队中 2待预约  1带接种 0是首页展示
            var isHeard = false;
            if (status == 0)
            {
                isHeard = true;
                status = 4;
            }
            var data = _pubPatInfoRepository.GetOutVaccineApptList(pat.Select(w => w.Id).ToList(), status);
            if (isHeard && data != null && data.Count > 2)
            {//首页展示 取前3条
                data = data.Take(3).ToList();
            }
            var dataitem = _pubPatInfoRepository.ApptForUser(data.Where(w => w.Status != 2 && w.Status != 4).Select(f => f.Id).ToList(), language);
            var dataCompany = _pubPatInfoRepository.CompanyApptForUser(data.Where(w => w.Type == 1).Select(f => f.Id).ToList(), language);
            foreach (var item in data)
            {
                if (item.Status == 15)
                {
                    item.Status = 8;
                }
                if (item.Type == 0)
                {
                    if (item.Status != 2 && item.Status != 4)
                    {
                        var detail = dataitem.OrderByDescending(g => g.CallTime).ToList().Where(w => w.Id == item.Id).FirstOrDefault();
                        if (detail != null)
                        {
                            item.HosName = detail.HosName;
                            item.HosPhone = detail.HosPhone;
                            item.AptTime = detail.AptTime;
                            item.Addr = detail.Addr;
                            item.PatType = detail.PatType;
                            item.CallTime = detail.CallTime;
                            item.VaccineName = detail.VaccineName;
                            item.VaccineBrand = detail.VaccineBrand;
                        }
                    }
                    item.NumStr = GetNumber(item.Num);
                }
                if (item.Type == 1)
                {
                    var detail = dataCompany.Find(w => w.Id == item.Id);
                    if (detail != null)
                    {
                        item.HosName = detail.HosName;
                        item.HosPhone = detail.HosPhone;
                        item.Addr = detail.Addr;
                        item.VaccineName = detail.VaccineName;
                        item.VaccineBrand = detail.VaccineBrand;
                    }
                }
                if (item.Status == 8 && item.InnerStatus > 4)
                {
                    item.Status = 7;
                }
            }
            return data;
        }

        public int AgainRequeue(int id)
        {
            var data = _pubPatInfoRepository.GetVaccineForId(id);
            var call = _pubPatInfoRepository.GetVaccineAppCall(data.CallId);
            var user = _pubPatInfoRepository.GetOutVaccineApptForCall(call);
            List<int> vaccineids = new List<int>();
            vaccineids.Add(data.VaccineId);
            _pubPatInfoRepository.UpdateOutVaccineApptStautsForId(vaccineids, 4);
            List<int> mapcallIds = new List<int>();
            mapcallIds.Add(data.MapCallId);
            _pubPatInfoRepository.UpdateOutVaccineMapCall(mapcallIds);

            ConfirmCallRequest request = new ConfirmCallRequest();
            request.CallId = call.Id;
            request.Model = call;
            request.User = user.Take(1).ToList();
            HttpContent content = new StringContent(JsonConvert.SerializeObject(request));
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var res = JsonConvert.DeserializeObject<BaseResponse<int>>(_httpClient.PostAsync("Admin/Api/User/ConfirmCall", content).Result.Content.ReadAsStringAsync().Result);
            return 1;
        }

        public VaccineApptForUser GetOutVaccineApptForId(int id, int language)
        {
            var data = _pubPatInfoRepository.GetOutVaccineApptForId(id);
            List<int> ids = new List<int>();
            ids.Add(data.Id);
            if (data.Type == 0)
            {
                var dataitem = _pubPatInfoRepository.ApptForUser(ids, language).ToList();
                var detail = dataitem.FirstOrDefault();
                if (detail != null)
                {
                    data.HosName = detail.HosName;
                    data.HosPhone = detail.HosPhone;
                    data.AptTime = detail.AptTime;
                    data.Addr = detail.Addr;
                    data.PatType = detail.PatType;
                    data.CallTime = detail.CallTime;
                    data.VaccineName = detail.VaccineName;
                    data.VaccineBrand = detail.VaccineBrand;
                }
                data.NumStr = GetNumber(data.Num);
            }
            if (data.Type == 1)
            {
                var dataCompany = _pubPatInfoRepository.CompanyApptForUser(ids, language).FirstOrDefault();
                if (dataCompany != null)
                {
                    data.HosName = dataCompany.HosName;
                    data.HosPhone = dataCompany.HosPhone;
                    data.Addr = dataCompany.Addr;
                    data.VaccineName = dataCompany.VaccineName;
                    data.VaccineBrand = dataCompany.VaccineBrand;
                }
            }
            if (data.Status == 15)
            {
                data.Status = 8;
            }
            if (data.Status == 8 && data.InnerStatus > 4)
            {
                data.Status = 7;
            }
            return data;
        }

        public bool QueueNumber()
        {
            var createnumber = _redisHelper.StringIncrementAsync("OutVaccineApptQueueNumber", 0).Result;
            var data = _pubPatInfoRepository.GetOldOutApptData();
            foreach (var item in data)
            {
                item.QueueNumber = GetOutVaccineApptQueueNumber();
            }
            var ret = _pubPatInfoRepository.UpdateOutVaccineAppt(data);
            if (ret > 0)
            {
                return true;
            }
            else { return false; }
        }

        public string GetNumber(int number)
        {
            if (number < 999999)
            {
                var str = "";
                for (int i = 0; i < 6 - number.ToString().Length; i++)
                {
                    str += "0";
                }
                return "S" + str + number;
            }
            return "S999999";
        }

        public int GetOutVaccineApptQueueNumber()
        {
            var number = _redisHelper.StringIncrementAsync("OutVaccineApptQueueNumber").Result;
            return (int)number;
        }

        public int CreateTCOrder(TCCreateOrderRequest request)
        {
            var model = request.MapTo<Out_DoctorAdvice>();
            return _outDoctorAdviceRepository.InsertDoctorAdvice(model);
        }

        //------------------------------------------------------------------------------疫苗预约
        public Dictionary<string, List<VaccSlotDateModel>> GetVaccineScheduling(VaccineSchedulingReq requst)
        {
            List<Dic_Vaccine_Serv> list = _outAptInfoRepository.SelectVaccineServ(requst.HosId);

            int servType = 0;
            if (!string.IsNullOrEmpty(requst.PatBirthday))
            {
                var age = Convert.ToDateTime(requst.PatBirthday).GetAgeByBirth();
                if (age < 3)
                {
                    servType = 1;
                }
                else if (age >= 3 && age < 14)
                {
                    servType = 2;
                }
                else if (age >= 14)
                {
                    servType = 3;
                }
            }

            Scheduling scheduling = new Scheduling();
            if (list != null && list.Count > 0)
            {
                var serv = list.Find(p => p.ServType == servType);
                if (serv != null)
                {
                    scheduling = _tcService.GetScheduling(requst.StartTime, requst.EndTime, serv.HisDeptId.ToString(), serv.HisServId.ToString(), serv.CareProvId.ToString());
                    scheduling.DeptId = serv.HisDeptId.ToString();
                    scheduling.HosId = requst.HosId.ToString();
                    scheduling.ServId = serv.HisServId.ToString();
                    scheduling.HisDocId = serv.CareProvId.ToString();
                }
            }

            return GetVaccScheduling(scheduling);
        }

        private Dictionary<string, List<VaccSlotDateModel>> GetVaccScheduling(Scheduling scheduling)
        {
            Dictionary<string, List<VaccSlotDateModel>> retDic = new Dictionary<string, List<VaccSlotDateModel>>();
            if (scheduling != null && scheduling.SlotDateList != null && scheduling.SlotDateList.Count > 0)
            {
                foreach (var SlotDate in scheduling.SlotDateList)
                {
                    var dateTime = SlotDate.Date;
                    if (!retDic.ContainsKey(dateTime))
                    {
                        retDic.Add(dateTime, new List<VaccSlotDateModel>());
                    }

                    if (SlotDate != null && SlotDate.ResourceList != null && SlotDate.ResourceList.Length > 0)
                    {
                        foreach (var reso in SlotDate.ResourceList)
                        {
                            if (reso != null && reso.SlotList != null && reso.SlotList.Length > 0)
                            {
                                foreach (var slot in reso.SlotList)
                                {
                                    DateTime dtDate;
                                    if (DateTime.TryParse(slot.StartTime, out dtDate))
                                    {
                                        var timeStr = dtDate.ToString("HH");
                                        if (Convert.ToInt32(timeStr) < 12)
                                        {
                                            timeStr = timeStr + ":00AM";
                                        }
                                        else
                                        {
                                            timeStr = timeStr + ":00PM";
                                        }
                                        if (!retDic[dateTime].Where(w => w.Date.Contains(timeStr)).Any())
                                        {
                                            var vaccSlot = new VaccSlotDateModel { Date = timeStr, DeptId = scheduling.DeptId, ServId = scheduling.ServId, DocId = scheduling.HisDocId };
                                            vaccSlot.AptUsrn.Add(slot.Usrn);
                                            retDic[dateTime].Add(vaccSlot);
                                        }
                                        else
                                        {
                                            retDic[dateTime].Find(p => p.Date == timeStr).AptUsrn.Add(slot.Usrn);
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                    }

                }
            }
            return retDic;
        }

        public VaccineAptInfo GetVaccineAptInfo(int id, int language)
        {
            var info = _outAptInfoRepository.GetVaccineAptInfo(id, language);
            if (info == null)
            {
                return new VaccineAptInfo();
            }
            if (language == 2)
            {
                info.PatDesc = info.PatType == 1 ? "3 yrs and above" : "Under 3 yrs";
            }
            else
            {
                info.PatDesc = info.PatType == 1 ? "三岁及以上" : "三岁以下";
            }
            info.VaccineOriginName = GetOriginName(info.VaccineOrigin, language);
            var userPat = _pubPatInfoRepository.GetUserPatByPatId(info.PatId);
            if (userPat == null || userPat.Find(p => p.Relation_Ship == 1) == null)
            {
                info.Temporary = true;
            }
            return info;
        }
        private string GetOriginName(int origin, int language)
        {
            switch (origin)
            {
                case 1:
                    return language == 1 ? "国产" : "Domestic";
                case 2:
                    return language == 1 ? "进口" : "Joint Venture";
                default:
                    return "";
            }
        }

        public Dictionary<int, string> VaccineAptCommit(VaccineApt apt, ref bool isTcInterfaceError)
        {
            isTcInterfaceError = false;
            Dictionary<int, string> result = new Dictionary<int, string>();
            //授权验证
            var auTick = _authorizationService.IsHasAuth(GetBaseUserInfo().ID, apt.PatId, (int)AuthType.OFFLINE, apt.Language);
            if (!string.IsNullOrEmpty(auTick))
            {
                result.Add(0, auTick);
                return result;
            }
            _logger.LogInformation("VaccineAptCommit: " + apt.ToJson());
            var pat = _pubPatInfoRepository.SelectById(apt.PatId);
            pat = _fileService.GetFileContentSelect<Pub_Pat_Info>(pat);
            if (pat == null)
            {
                result.Add(0, apt.Language == 2 ? "Patient error" : "患者错误");
                return result;
            }
            DateTime aptTime;
            if (DateTime.TryParse(apt.AptDayTime, out aptTime))
            {
                apt.AptDayTime = aptTime.ToString("yyyy-MM-dd");
            }
            var aptDay = Convert.ToDateTime(apt.AptDayTime);
            List<Dic_Vaccine_Serv> list = _outAptInfoRepository.SelectVaccineServ(apt.HosId);
            if (list != null)
            {
                int servType = 0;
                if (!string.IsNullOrEmpty(pat.Birthday))
                {
                    var age = Convert.ToDateTime(pat.Birthday).GetAgeByBirth();
                    if (age < 3)
                    {
                        servType = 1;
                    }
                    else if (age >= 3 && age < 14)
                    {
                        servType = 2;
                    }
                    else if (age >= 14)
                    {
                        servType = 3;
                    }
                }
                Dic_Vaccine_Serv serv = list.Find(p => p.HisDeptId == apt.HisDeptId && p.HisServId == apt.HisServId && p.CareProvId == apt.CareProvId && p.ServType == servType);
                if (serv != null)
                {
                    if (apt.VaccId > 0)
                    {//个人疫苗预约
                        if (serv.ServType == 1)
                        {
                            if (aptDay >= Convert.ToDateTime(pat.Birthday).AddYears(3))
                            {//2021-09-29                   2021-09-26
                                result.Add(0, apt.Language == 2 ? "Patient need to be under 3yrs,any question please contact customer service Ying" : "就诊人年龄需小于三岁，如有疑问请联系客服小影");
                                return result;
                            }
                        }
                        else
                        {
                            //1、预约日期-出生日期+3天<3岁  是：进入下一步判断.  否：提示该就诊人不符合条件
                            if (aptDay < Convert.ToDateTime(pat.Birthday).AddYears(3))
                            {
                                result.Add(0, apt.Language == 2 ? "Patient need to be over 3yrs,any question please contact customer service Ying" : "就诊人年龄需大于等于三岁，如有疑问请联系客服小影");
                                return result;
                            }
                        }
                    }
                    else
                    {//企业疫苗预约
                        if (aptDay < Convert.ToDateTime(pat.Birthday).AddYears(3))
                        {
                            result.Add(0, apt.Language == 2 ? "Patient need to be over 3yrs,any question please contact customer service Ying" : "就诊人年龄需大于等于三岁，如有疑问请联系客服小影");
                            return result;
                        }
                    }
                }
            }
            #region 20211203新需求 把就诊人的逻辑舍弃   
            //2、患者是否为绑定就诊人 -是：预约时直接预约成功，预约进TC  - 否：进入下一步判断
            //3、手机号验证码通过后，根据手机号、姓、名、出生日期判断是否同时存在TC，
            //        -存在，预约成功进TC
            //        - 不存在：TC中新增患者，预约进TC
            //  TC中新增患者  失败(不管是添加失败 还是TC已存在)    提示 预约信息发生错误，请联系客服小影
            //     
            //var userPat = _pubPatInfoRepository.GetUserPatByPatId(pat.Id);
            //if (string.IsNullOrEmpty(pat.Pat_ID) || userPat == null || userPat.Find(p => p.Relation_Ship == 1) == null)
            //{
            //    var tcPats = _tcService.GetPat(pat.Phone_NO, pat.Birthday);
            //    var hasPat = tcPats.Find(p => p.PAPERName?.Trim().ToLower() == pat.Last_Name?.Trim().ToLower() && p.PAPERName2?.Trim().ToLower() == pat.First_Name?.Trim().ToLower());
            //    if (tcPats == null || hasPat == null)
            //    {
            //        //推TC
            //        try
            //        {
            //            _tcService.AddTcPatInfo(pat, apt.VaccId > 0 ? "009" : "50");
            //        }
            //        catch (System.Exception e) { isTcInterfaceError = true; }

            //        //更新就诊信息
            //        var tcPat = _tcService.GetPat(pat.Phone_NO, pat.Birthday);
            //        if (tcPat != null && tcPat.Count > 0 && tcPat.Find(p => p.PAPERName?.Trim().ToLower() == pat.Last_Name?.Trim().ToLower() && p.PAPERName2?.Trim().ToLower() == pat.First_Name?.Trim().ToLower()) != null)
            //        {
            //            try
            //            {
            //                SendFileToTc(new List<string>() { pat.IDCardUrlFront, pat.IDCardUrlBack }, tcPat[0].PAPERRowId, pat.Card_ID);
            //                BindPatInfo(ref pat, tcPat[0]);
            //            }
            //            catch (System.Exception e) { isTcInterfaceError = true; }
            //        }
            //        else
            //        {
            //            isTcInterfaceError = true;
            //            //result.Add(0, apt.Language == 2 ? "There is an error in the reservation information, please contact the customer service Xiaoying" : "预约信息发生错误，请联系客服小影");
            //            //return result;
            //        }
            //    }
            //    else
            //    {
            //        var tcPat = tcPats.Find(p => p.PAPERName?.Trim().ToLower() == pat.Last_Name?.Trim().ToLower() && p.PAPERName2?.Trim().ToLower() == pat.First_Name?.Trim().ToLower());
            //        if (tcPat != null)
            //        {
            //            try
            //            {
            //                BindPatInfo(ref pat, tcPat);
            //            }
            //            catch (System.Exception e) { isTcInterfaceError = true; }
            //        }
            //    }
            //}
            #endregion
            //预约
            var time = Convert.ToDateTime(apt.AptDayTime).ToString("yyyy-MM-dd");
            var scheduling = _tcService.GetScheduling(time, time, apt.HisDeptId.ToString(), apt.HisServId.ToString(), apt.CareProvId.ToString());
            scheduling.DeptId = apt.HisDeptId.ToString();
            scheduling.HosId = apt.HosId.ToString();
            scheduling.ServId = apt.HisServId.ToString();
            scheduling.HisDocId = apt.CareProvId.ToString();
            var data = GetVaccScheduling(scheduling);
            var usrnList = data[time].Find(p => p.Date == apt.AptHourTime)?.AptUsrn;
            if (usrnList != null)
            {
                if (isTcInterfaceError)
                {
                    var ret = AddOutAptInfo(apt, "");//添加预约记录
                    if (ret > 0)
                    {
                        if (!string.IsNullOrEmpty(pat.Pat_ID))
                        {
                            SendPdfFileToTc(1431, pat.Pat_ID);
                        }
                        var apptid = 0;
                        Out_Apt_Info oAInFo = _outAptInfoRepository.GetOutAptInfo(ret);
                        Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(oAInFo.Pat_Id);
                        Dic_Hos hos = _dicHosRepository.SelectByPrimaryKey(oAInFo.Hos_Id);
                        var smsLog = new Pub_Sms_Log();
                        smsLog.Sms_Type = 12;//PP预约确认短信
                        smsLog.Request = "aptId:" + ret;
                        _pubSmsLogRepository.InsertPubSmsLog(smsLog);
                        _pubMessageService.SendConfirmSms(hos, oAInFo, patInfo, smsLog);
                        //修改排队状态  预约操作状态(1=已确认/2=取消/3=待处理/4=排队中/5已叫号/6已过号/7已完成/8已预约/9预约已取消)
                        if (apt.VaccId > 0)
                        {
                            _outAptInfoRepository.UpdateVaccAptStatus(apt.VaccId, 8, isTcInterfaceError);
                        }
                        else
                        {//企业预约,添加排队预约记录 减去预约次数
                            var groupId = CutAptCount(pat.Phone_NO);
                            apptid = AddVaccApt(apt, groupId, isTcInterfaceError);
                            _outAptInfoRepository.BindAptId(ret, apptid);
                            //_outAptInfoRepository.InsertOutVaccineAppt(new Out_Vaccine_Appt() { });
                        }

                        result.Add(apptid, "");
                        return result;
                    }
                }
                else
                {
                    foreach (var usrn in usrnList)
                    {

                        try
                        {
                            if (_tcService.LockApt(usrn, usrn, "L"))
                            {
                                var res = _tcService.CommitApt(apt.HisDeptId.ToString(), apt.HisServId.ToString(), usrn, usrn, pat.Pat_ID);
                                if (!res)
                                {//TC预约失败
                                    isTcInterfaceError = true;
                                    _tcService.LockApt(usrn, usrn, "U");
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        catch (System.Exception ex)
                        {
                            _tcService.LockApt(usrn, usrn, "U");
                            continue;
                        }
                        SendPdfFileToTc(1431, pat.Pat_ID);
                        //提交预约备注给TC
                        CommitAptRemark(usrn, apt);
                        var ret = AddOutAptInfo(apt, usrn);//添加预约记录
                        if (ret > 0)
                        {
                            var apptid = 0;
                            Out_Apt_Info oAInFo = _outAptInfoRepository.GetOutAptInfo(ret);
                            Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(oAInFo.Pat_Id);
                            Dic_Hos hos = _dicHosRepository.SelectByPrimaryKey(oAInFo.Hos_Id);
                            var smsLog = new Pub_Sms_Log();
                            smsLog.Sms_Type = 12;//PP预约确认短信
                            smsLog.Request = "aptId:" + ret;
                            var id = _pubSmsLogRepository.InsertPubSmsLog(smsLog);
                            smsLog.Id = id;
                            _pubMessageService.SendConfirmSms(hos, oAInFo, patInfo, smsLog);
                            //修改排队状态  预约操作状态(1=已确认/2=取消/3=待处理/4=排队中/5已叫号/6已过号/7已完成/8已预约/9预约已取消)
                            if (apt.VaccId > 0)
                            {
                                _outAptInfoRepository.UpdateVaccAptStatus(apt.VaccId, 8, isTcInterfaceError);
                            }
                            else
                            {//企业预约,添加排队预约记录 减去预约次数
                                var groupId = CutAptCount(pat.Phone_NO);
                                apptid = AddVaccApt(apt, groupId, isTcInterfaceError);
                                _outAptInfoRepository.BindAptId(ret, apptid);
                                //_outAptInfoRepository.InsertOutVaccineAppt(new Out_Vaccine_Appt() { });
                            }

                            result.Add(apptid, "");
                            return result;
                        }

                    }
                }
            }
            result.Add(0, apt.Language == 2 ? "The time period has occupied, please choose another time or contact customer service" : "该时间段已约满，请选择其他时间或联系客服");
            return result;
        }
        private int CutAptCount(string phone)
        {
            _logger.LogInformation("CutAptCount: " + phone);
            var groupId = 0;
            var group = _vaccineAptRepository.GetVaccGroupList(phone);
            if (group != null)
            {
                groupId = group.GroupId;
                _vaccineAptRepository.CutVaccGroupListCount(phone);
            }
            else
            {
                group = _vaccineAptRepository.GetVaccGroupList(GetBaseUserInfo().Phone);
                if (group != null)
                {
                    groupId = group.GroupId;
                    _vaccineAptRepository.CutVaccGroupListCount(GetBaseUserInfo().Phone);
                }
            }
            return groupId;
        }

        private int AddVaccApt(VaccineApt apt, int groupId, bool isTcInterfaceError)
        {
            var flowid = _outAptInfoRepository.InsertOutVaccineApptFlow(new Out_Vaccine_Appt_Flow
            {
                CREATE_TIME = DateTime.Now,
                CREATE_USER = "admin",
                RESOUCE_TYPE = 1,
                STATUS = 1,
                REQUEST_PARAM = ""
            });

            var groupInfo = _vaccineAptRepository.GetOutVaccineApptGroup(groupId);

            var model = new Out_Vaccine_Appt
            {
                FLOW_ID = flowid,
                PAT_ID = apt.PatId,
                USER_ID = GetBaseUserInfo().ID,
                VACCINE_ID = 1,
                PAY_TYPE = 1,
                IS_TREATMENT = true,
                INSURANCE_ID = 0,
                INSURANCE_NO = "",
                PAY_IMAGE = "",
                HPV_TYPE = "",
                HPT_PIN = "",
                ORIGIN = apt.Origin.Value,
                STATUS = 8,//已预约
                MATCH_CODE = "VaccineAppt",
                APT_TIME = Convert.ToDateTime(apt.AptDayTime + " " + apt.AptHourTime.Replace("AM", "").Replace("PM", "")),
                HOS_ID = apt.HosId,
                DEPT_ID = apt.HisDeptId,
                DOC_ID = apt.CareProvId,
                REMAKE = string.IsNullOrEmpty(groupInfo?.Remark) ? "企业疫苗预约" : groupInfo?.Remark,
                CREATE_USER = "admin",
                CREATE_TIME = DateTime.Now,
                LANGUAGE = 1,
                NewVaccineType = 1,
                UPDATE_TIME = DateTime.Now,
                Type = 1,
                GroupId = groupId,
                IsTcInterfaceError = isTcInterfaceError
            };
            return _outAptInfoRepository.InsertOutVaccineAppt(model);
        }


        private void SendFileToTc(List<string> idstr, string rowId, string remark)
        {
            if (idstr == null || idstr.Count == 0)
            {
                return;
            }
            List<int> ids = new List<int>();
            foreach (var item in idstr)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var burl = JsonConvert.DeserializeObject<FileContenModel>(item);
                    if (burl != null)
                    {
                        var id = burl.Content.FirstOrDefault()?.Id;
                        if (id != null)
                        {
                            ids.Add(id.ToInt());
                        }
                    }
                }

            }
            var files = _fileRepository.GetFilesForContent(ids);
            if (files != null && files.Count > 0)
            {
                foreach (var item in files)
                {
                    var pName = item.FileUrl.Split('\\')?.LastOrDefault();
                    var res = _tcService.CustomCRMPictures(rowId, string.IsNullOrEmpty(remark) ? "新患者录入图片" : remark, pName, item.Content);
                    _logger.LogInformation("SendFileToTc:" + item.Id + "   reb:" + res);
                }
            }
        }
        public MemoryStream Test(int type)
        {
            var dateNowFirst = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd").Substring(0, 8) + "01");
            var startDate = dateNowFirst.AddMonths(-1).ToString("yyyy-MM-dd");
            var endDate = dateNowFirst.ToString("yyyy-MM-dd");
            if (type == 3)
            {
                var list = GetAptListFromMonth(startDate, endDate);
                var dic = new Dictionary<string, int>();
                List<DataBtwAptCount> report = new List<DataBtwAptCount>();

                for (int i = 0; i < 24; i++)
                {
                    var hour = i + "";
                    if (hour.Length == 1)
                    {
                        hour = "0" + hour;
                    }

                    dic.Add(hour + ":00:00-" + hour + ":59:59", 0);

                }
                foreach (var item in list)
                {
                    var apthour = item.CREATE_TIME.Hour + "";
                    if (apthour.Length == 1)
                    {
                        apthour = "0" + apthour;
                    }
                    var key = apthour + ":00:00-" + apthour + ":59:59";
                    dic[key] = dic[key] + 1;
                }
                DataBtwAptCount dataBtwApt = null;
                foreach (var item in dic.Keys)
                {
                    dataBtwApt = new DataBtwAptCount();
                    dataBtwApt.AptCount = dic[item];
                    dataBtwApt.TimeBtw = item;
                    report.Add(dataBtwApt);
                }
                MemoryStream m = ExcelHelp.RequestFormDMExcel<DataBtwAptCount>(report);
                return m;
            }
            if (type == 4)
            {

                var list = _dicHosRepository.SelectHosWithLanguage(1);
                var msgList = GetSurveyReplyMsgCount(startDate, endDate);
                List<SurveyData> reportList = new List<SurveyData>();
                SurveyData data = null;
                foreach (var item in list)
                {
                    data = new SurveyData();
                    data.Name = item.ShortName;
                    var thisHosMsgs = msgList.FindAll(p => p.Hos_Id == item.Id);
                    if (thisHosMsgs?.Count > 0)
                    {
                        data.MsgAmount = thisHosMsgs.Count;
                        var retMsg = thisHosMsgs.FindAll(p => !string.IsNullOrEmpty(p.Content));
                        if (retMsg?.Count > 0)
                        {
                            data.ReplyAmount = retMsg.Count;
                        }
                    }
                    if (data.ReplyAmount > 0 && data.MsgAmount > 0)
                    {
                        data.ReplyRate = Math.Round((double)data.ReplyAmount / data.MsgAmount, 2) * 100 + "%";
                    }
                    else
                    {
                        data.ReplyRate = "0";
                    }
                    reportList.Add(data);
                }
                MemoryStream m = ExcelHelp.RequestFormDMExcel<SurveyData>(reportList);
                return m;
            }

            if (type == 1)
            {
                //var list = GetAptListFromMonth("2021-11-26", "2021-12-03");
                var list = GetAptListFromMonth(startDate, endDate);
                var deptList = _dicDeptRepository.GetAllDept();
                List<DataApt> reportList = new List<DataApt>();
                DataApt data = null;
                if (list?.Count > 0)
                {
                    var deptIds = list.Select(p => p.DEPT_ID).ToList().Distinct();

                    foreach (var item in deptIds)
                    {
                        data = new DataApt();
                        var deptApts = list.FindAll(p => p.DEPT_ID == item);
                        var cancelCount = deptApts.FindAll(p => p.INNER_STATUS == 2 || p.STATUS == 2)?.Count();
                        var dept = deptList.Find(p => p.Id == item);

                        data.Name = dept == null ? "PP找不到科室" : dept.CN_Name;

                        if (list.Count > 0)
                        {
                            if (deptApts?.Count > 0)
                            {
                                data.AptRate = Math.Round((double)deptApts.Count * 100 / list.Count, 2) + "%";
                            }
                            else
                            {
                                data.AptRate = "0";
                            }
                            if (deptApts?.Count > 0 && cancelCount > 0)
                            {
                                data.CancelRate = Math.Round(Convert.ToInt32(cancelCount) * 100 / (double)deptApts.Count, 2) + "%";
                            }
                            else
                            {
                                data.CancelRate = "0";
                            }
                        }
                        else
                        {
                            data.AptRate = "0";
                            data.CancelRate = "0";
                        }
                        reportList.Add(data);
                    }
                    MemoryStream m = ExcelHelp.RequestFormDMExcel<DataApt>(reportList);
                    return m;
                }
            }
            if (type == 2)
            {
                dateNowFirst = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd").Substring(0, 8) + "01");
                startDate = dateNowFirst.AddMonths(-6).ToString("yyyy-MM-dd");
                endDate = dateNowFirst.ToString("yyyy-MM-dd");
                var list = GetDeptAptMore(startDate, endDate);
                MemoryStream m = ExcelHelp.RequestFormDMExcel<DataPatAptMore>(list);
                return m;
            }
            if (type == 2020)
            {
                var list = GetAptListFromMonth("2020-01-01", "2021-01-01");
                var deptList = _dicDeptRepository.GetAllDept();
                List<DataApt> reportList = new List<DataApt>();
                DataApt data = null;
                if (list?.Count > 0)
                {
                    var deptIds = list.Select(p => p.DEPT_ID).ToList().Distinct();

                    foreach (var item in deptIds)
                    {
                        data = new DataApt();
                        var deptApts = list.FindAll(p => p.DEPT_ID == item);
                        var cancelCount = deptApts.FindAll(p => p.INNER_STATUS == 2 || p.STATUS == 2)?.Count();
                        var dept = deptList.Find(p => p.Id == item);

                        data.Name = dept == null ? "PP找不到科室" : dept.CN_Name;

                        if (list.Count > 0)
                        {
                            if (deptApts?.Count > 0)
                            {
                                data.AptRate = Math.Round((double)deptApts.Count * 100 / list.Count, 2) + "%";
                            }
                            else
                            {
                                data.AptRate = "0";
                            }
                            if (deptApts?.Count > 0 && cancelCount > 0)
                            {
                                data.CancelRate = Math.Round(Convert.ToInt32(cancelCount) * 100 / (double)deptApts.Count, 2) + "%";
                            }
                            else
                            {
                                data.CancelRate = "0";
                            }
                        }
                        else
                        {
                            data.AptRate = "0";
                            data.CancelRate = "0";
                        }
                        reportList.Add(data);
                    }
                    MemoryStream m = ExcelHelp.RequestFormDMExcel<DataApt>(reportList);
                    return m;
                }
            }
            if (type == 2021)
            {
                var list = GetAptListFromMonth("2021-01-01", "2021-12-03");
                var deptList = _dicDeptRepository.GetAllDept();
                List<DataApt> reportList = new List<DataApt>();
                DataApt data = null;
                if (list?.Count > 0)
                {
                    var deptIds = list.Select(p => p.DEPT_ID).ToList().Distinct();

                    foreach (var item in deptIds)
                    {
                        data = new DataApt();
                        var deptApts = list.FindAll(p => p.DEPT_ID == item);
                        var cancelCount = deptApts.FindAll(p => p.INNER_STATUS == 2 || p.STATUS == 2)?.Count();
                        var dept = deptList.Find(p => p.Id == item);

                        data.Name = dept == null ? "PP找不到科室" : dept.CN_Name;

                        if (list.Count > 0)
                        {
                            if (deptApts?.Count > 0)
                            {
                                data.AptRate = Math.Round((double)deptApts.Count * 100 / list.Count, 2) + "%";
                            }
                            else
                            {
                                data.AptRate = "0";
                            }
                            if (deptApts?.Count > 0 && cancelCount > 0)
                            {
                                data.CancelRate = Math.Round(Convert.ToInt32(cancelCount) * 100 / (double)deptApts.Count, 2) + "%";
                            }
                            else
                            {
                                data.CancelRate = "0";
                            }
                        }
                        else
                        {
                            data.AptRate = "0";
                            data.CancelRate = "0";
                        }
                        reportList.Add(data);
                    }
                    MemoryStream m = ExcelHelp.RequestFormDMExcel<DataApt>(reportList);
                    return m;
                }
            }
            if (type == 32020)
            {
                var list = GetAptListFromMonth("2020-01-01", "2021-01-01");
                var dic = new Dictionary<string, int>();
                List<DataBtwAptCount> report = new List<DataBtwAptCount>();

                for (int i = 0; i < 24; i++)
                {
                    var hour = i + "";
                    if (hour.Length == 1)
                    {
                        hour = "0" + hour;
                    }

                    dic.Add(hour + ":00:00-" + hour + ":59:59", 0);

                }
                foreach (var item in list)
                {
                    var apthour = item.CREATE_TIME.Hour + "";
                    if (apthour.Length == 1)
                    {
                        apthour = "0" + apthour;
                    }
                    var key = apthour + ":00:00-" + apthour + ":59:59";
                    dic[key] = dic[key] + 1;
                }
                DataBtwAptCount dataBtwApt = null;
                foreach (var item in dic.Keys)
                {
                    dataBtwApt = new DataBtwAptCount();
                    dataBtwApt.AptCount = dic[item];
                    dataBtwApt.TimeBtw = item;
                    report.Add(dataBtwApt);
                }
                MemoryStream m = ExcelHelp.RequestFormDMExcel<DataBtwAptCount>(report);
                return m;
            }
            if (type == 32021)
            {
                var list = GetAptListFromMonth("2021-01-01", "2021-12-03");
                var dic = new Dictionary<string, int>();
                List<DataBtwAptCount> report = new List<DataBtwAptCount>();

                for (int i = 0; i < 24; i++)
                {
                    var hour = i + "";
                    if (hour.Length == 1)
                    {
                        hour = "0" + hour;
                    }

                    dic.Add(hour + ":00:00-" + hour + ":59:59", 0);

                }
                foreach (var item in list)
                {
                    var apthour = item.CREATE_TIME.Hour + "";
                    if (apthour.Length == 1)
                    {
                        apthour = "0" + apthour;
                    }
                    var key = apthour + ":00:00-" + apthour + ":59:59";
                    dic[key] = dic[key] + 1;
                }
                DataBtwAptCount dataBtwApt = null;
                foreach (var item in dic.Keys)
                {
                    dataBtwApt = new DataBtwAptCount();
                    dataBtwApt.AptCount = dic[item];
                    dataBtwApt.TimeBtw = item;
                    report.Add(dataBtwApt);
                }
                MemoryStream m = ExcelHelp.RequestFormDMExcel<DataBtwAptCount>(report);
                return m;
            }
            if (type == 5)
            {
                var allUser = _pubUserInfoRepository.GetAllUser();
                List<MyUser> users = new List<MyUser>();
                MyUser myUser = null;
                foreach (var item in allUser)
                {
                    myUser = new MyUser();
                    myUser.Id = item.ID;
                    myUser.Gender = item.Gender;
                    if (!string.IsNullOrEmpty(item.Birthday))
                    {
                        myUser.Age = Convert.ToDateTime(item.Birthday).GetAgeByBirth();
                    }
                    users.Add(myUser);
                }
                List<UserAgeCount> list = new List<UserAgeCount>();
                list.Add(new UserAgeCount() { AgeBtw = "未填写", UserCount = users.FindAll(p => p.Age == 0).Count });
                list.Add(new UserAgeCount() { AgeBtw = "20以下", UserCount = users.FindAll(p => p.Age > 0 && p.Age <= 20).Count });
                list.Add(new UserAgeCount() { AgeBtw = "21-30", UserCount = users.FindAll(p => p.Age > 20 && p.Age <= 30).Count });
                list.Add(new UserAgeCount() { AgeBtw = "31-40", UserCount = users.FindAll(p => p.Age > 30 && p.Age <= 40).Count });
                list.Add(new UserAgeCount() { AgeBtw = "41-50", UserCount = users.FindAll(p => p.Age > 40 && p.Age <= 50).Count });
                list.Add(new UserAgeCount() { AgeBtw = "50以上", UserCount = users.FindAll(p => p.Age > 50).Count });
                list.Add(new UserAgeCount() { AgeBtw = "男性", UserCount = users.FindAll(p => p.Gender == 1).Count });
                list.Add(new UserAgeCount() { AgeBtw = "女性", UserCount = users.FindAll(p => p.Gender == 0).Count });
                list.Add(new UserAgeCount() { AgeBtw = "性别未录入", UserCount = users.FindAll(p => p.Gender != 0 && p.Gender != 1).Count });
                MemoryStream m = ExcelHelp.RequestFormDMExcel<UserAgeCount>(list);
                return m;
            }
            
            //SendPdfFileToTc(1431, "62081");
            return null;
        }




        private void SendPdfFileToTc(int id, string rowId)
        {
            List<int> idstr = new List<int>();
            idstr.Add(id);
            var files = _fileRepository.GetFilesForContent(idstr);
            if (files != null && files.Count > 0)
            {
                foreach (var item in files)
                {
                    var pName = item.FileUrl.Split('\\')?.LastOrDefault();
                    var res = _tcService.CustomCRMPictures(rowId, "流感接种前问卷", pName, item.Content);
                    _logger.LogInformation("SendFileToTc:" + item.Id + "   reb:" + res);
                }
            }
        }


        private void BindPatInfo(ref Pub_Pat_Info pat, PAPerson tcPat)
        {
            pat.Pat_ID = tcPat.PAPERRowId;
            pat.Pat_MRN = tcPat.PAPMINo;
            _tcService.UpdatePatientPortalLink("", pat.Pat_MRN, true);
            _pubPatInfoRepository.UpdatePubPatInfo(pat);
            //var pubMapUserPat = _pubMapUserPatRepository.GetUserPat(GetBaseUserInfo().ID, pat.Id);
            //if (pubMapUserPat != null)
            //{
            //    //修改就诊人关系
            //    pubMapUserPat.Relation_Ship = 1;
            //    _pubMapUserPatRepository.UpdatePubMapUserPat(pubMapUserPat);
            //}
            _tCPatInfoService.SavePatMrn(pat.Id);
        }

        public bool CommitAptRemark(string usrn, VaccineApt apt)
        {
            try
            {
                var remark = string.Empty;
                if (apt.VaccId > 0)
                {
                    var vacc = GetVaccineAptInfo(apt.VaccId, 1);
                    remark = "[" + vacc.VaccineBrand + "]";
                }
                else
                {
                    var groupId = 0;
                    var pat = _pubPatInfoRepository.SelectById(apt.PatId);
                    var group = _vaccineAptRepository.GetVaccGroupList(pat.Phone_NO);
                    if (group != null)
                    {
                        groupId = group.GroupId;
                    }
                    else
                    {
                        group = _vaccineAptRepository.GetVaccGroupList(GetBaseUserInfo().Phone);
                        if (group != null)
                        {
                            groupId = group.GroupId;
                        }
                    }
                    if (groupId > 0)
                    {
                        var groupDan = _vaccineAptRepository.GetOutVaccineApptGroup(groupId);
                        if (groupDan != null)
                        {
                            remark = groupDan.Remark;
                        }
                    }
                }
                var res = _tcService.UpdateAppointment(usrn, remark);
                _logger.LogInformation("疫苗预约AptRemark:" + usrn + "  remark:" + remark + "  res:" + res);
                return res;
            }
            catch (System.Exception e)
            { return false; }
        }
        public int AddOutAptInfo(VaccineApt apt, string usrn)
        {
            var outAptInfo = new Out_Apt_Info();
            outAptInfo.Apt_Id = apt.VaccId;
            outAptInfo.Apply_User_Id = GetBaseUserInfo().ID;
            outAptInfo.Apt_Proj = apt.HisServId;
            outAptInfo.Apt_Time = Convert.ToDateTime(apt.AptDayTime + " " + apt.AptHourTime.Replace("AM", "").Replace("PM", ""));
            outAptInfo.Apt_Usrn = usrn;
            outAptInfo.Create_Time = DateTime.Now;
            outAptInfo.Dept_ID = apt.HisDeptId;
            outAptInfo.Doc_Id = apt.CareProvId;
            outAptInfo.Hos_Id = apt.HosId;
            outAptInfo.Status = 4;//确认预约
            outAptInfo.Source_Type = 256;
            // 添加匹配码，便于确认
            outAptInfo.Match_Code = Common.CreateCode(16);
            outAptInfo.Inner_Status = 4;//确认预约
            outAptInfo.Pat_Id = apt.PatId;
            outAptInfo.Pat_Status = 1;
            //if (apt.Channel > 0)
            //{
            if (apt.Channel == 1)
            {
                if (GetBaseUserInfo()?.Key_Type == 1)
                {
                    outAptInfo.Channel = 5;
                }
                else if (GetBaseUserInfo()?.Key_Type == 2)
                {
                    outAptInfo.Channel = 6;
                }
                else
                {
                    outAptInfo.Channel = 1;
                }
            }
            else
            {
                outAptInfo.Channel = apt.Channel.Value;
            }
            //}
            //else
            //{
            //    outAptInfo.Channel = 0;
            //}

            _logger.LogInformation("疫苗预约Commit:" + outAptInfo.ToJson());
            var res = _outAptInfoRepository.InsertOutAptInfo(outAptInfo);
            return res;
        }

        public void PushApt()
        {

            List<Out_Apt_Info> list = _outAptInfoRepository.SelectTomorrow();
            if (list != null && list.Count() > 0)
            {
                _logger.LogInformation("开始发送提前短信！");
                //Pub_User_Info patUserInfo = null;
                Pub_Pat_Info patInfo = null;
                Dic_Hos hos = null;
                Dic_Map_Dept_Serv mapDeptServ = null;
                var aptTheDayBeforeCn = _appConfigurtaion.GetAptTheDayBeforeCn;
                var aptTheDayBeforeEn = _appConfigurtaion.GetAptTheDayBeforeEn;
                var cut = _appConfigurtaion.GetAptSmsOn;
                var aptUserTomorrowConfirmSmsTemplateEN = _appConfigurtaion.GetAptUserTomorrowConfirmSmsTemplateEN;
                var aptUserTomorrowConfirmSmsTemplateCN = _appConfigurtaion.GetAptUserTomorrowConfirmSmsTemplateCN;
                foreach (var info in list)
                {
                    //patUserInfo = _pubUserInfoRepository.SelectByPatId(info.Pat_Id != 0 ? info.Pat_Id : 0);
                    patInfo = _pubPatInfoRepository.SelectById(info.Pat_Id);
                    hos = _dicHosRepository.SelectByPrimaryKey(info.Hos_Id);
                    if (info.Apt_Proj != 0)
                        if (info.Apt_Id > 0)
                        {//疫苗预约 存的Apt_Proj  是his的Apt_Proj并不是线下存的本地Apt_Proj服务
                            mapDeptServ = _dicMapDeptServRepository.SelectByHisKey(info.Apt_Proj);
                        }
                        else
                        {//线下预约
                            mapDeptServ = _dicMapDeptServRepository.SelectByPrimaryKey(info.Apt_Proj);
                        }
                    var lan = 2;
                    if (Common.IsChineseName(patInfo.Pat_Name))
                    {
                        lan = 1;
                    }
                    if (patInfo != null)
                    {
                        //发送通知，根据用户app语言版本发送中英文
                        //int userId = patUserInfo != null ? patUserInfo.ID : patUserInfo.ID;
                        string JpushContent = null;
                        if (lan == 2)
                        {//dd MMMM
                            JpushContent = aptTheDayBeforeEn.Replace("[data]", Convert.ToDateTime(info.Apt_Time).ToString("dd MMMM"));
                        }
                        else
                        {//MM月dd日
                            JpushContent = aptTheDayBeforeCn.Replace("[data]", Convert.ToDateTime(info.Apt_Time).ToString("MM月dd日"));
                        }
                        PushUserMessage(patInfo.Id, info.Id.ToString(), 5, "预约就诊", JpushContent);
                        //_jGPushService.PushMessageToUsers(patInfo.Id,);
                        //发送短信，根据患者姓名发送中英文
                        // 判断短信开关是否开启

                        if (cut != "true")
                        {
                            break;
                        }
                        if (string.IsNullOrEmpty(patInfo.Phone_NO))
                        {
                            break;
                        }

                    }
                    if (cut != "true")
                    {
                        continue;
                    }
                    //发送短信
                    if (mapDeptServ != null && mapDeptServ.Is_Send)
                    {
                        string smsContent, carContent, addr;
                        string yjContent = null;
                        string deptAddrName = "";
                        Dic_Map_Hos_Dept mapHosDept;
                        //判断病人名称是否英文
                        if (lan == 2)
                        {
                            //发送英文短信
                            addr = hos.EN_SMS_Addr;
                            mapHosDept = _dicMapHosDeptRepository.SelectByHosIdDeptID(info.Hos_Id, info.Dept_ID, 0);
                            deptAddrName = mapHosDept != null && mapHosDept.En_Sms_Addr != null ? mapHosDept.En_Sms_Addr : "";
                            smsContent = aptUserTomorrowConfirmSmsTemplateEN.Replace("[name]", patInfo.Pat_Name)
                                    .Replace("[date]", Convert.ToDateTime(info.Apt_Time).ToString("yyyy/MMM/dd HH:mm"))//
                                    .Replace("[addr]", addr.Replace("[deptAddr]", deptAddrName));
                            carContent = hos.EN_Parking_Info.Replace("[date]", Convert.ToDateTime(info.Apt_Time).ToString("yyyy/MMM/dd HH:mm"))
                                    .Replace("[hos]", hos.EN_Abbreviated_Addr);
                            //预检短信（商城门诊）
                            //                        if (hos.getId().equals(17)) {
                            //                            yjContent = "【SinoUnited Health】Triage notice: From Monday to Saturday, please come to 3rd floor. For Sunday come to 6th floor. Address: Suite 301, 3F; Suite 601, 6F, West Offices, Shanghai Centre, No.1376 West Nanjing Road";
                            //                        }
                        }
                        else
                        {
                            //发送中文短信
                            addr = hos.CN_SMS_Addr;
                            mapHosDept = _dicMapHosDeptRepository.SelectByHosIdDeptID(info.Hos_Id, info.Dept_ID, 0);
                            deptAddrName = mapHosDept != null && mapHosDept.Cn_Sms_Addr != null ? mapHosDept.Cn_Sms_Addr : "";
                            smsContent = aptUserTomorrowConfirmSmsTemplateCN.Replace("[name]", patInfo.Pat_Name)
                                    .Replace("[date]", Convert.ToDateTime(info.Apt_Time).ToString("yyyy年MM月dd日 HH:mm"))
                                    .Replace("[addr]", addr.Replace("[deptAddr]", deptAddrName));
                            carContent = hos.CN_Parking_Info.Replace("[date]", Convert.ToDateTime(info.Apt_Time).ToString("yyyy年MM月dd日 HH:mm"))
                                    .Replace("[hos]", hos.CN_Abbreviated_Addr);
                            //预检短信（商城门诊）
                            //                        if (hos.getId().equals(17)) {
                            //                            yjContent = "【曜影医疗】预检提示：欢迎预约曜影商城门诊部，周一至周六请到三楼预检，周日请至六楼，地址：南京西路1376号西峰办公室3层301/6层601";
                            //                        }
                        }

                        try
                        {
                            smsContent = smsContent + carContent;
                            _smsSurveyService.Send(patInfo.Phone_NO, smsContent, "");
                            if (yjContent != null)
                            {
                                _smsSurveyService.Send(patInfo.Phone_NO, yjContent, "");
                            }
                            _logger.LogInformation("发送提前一天发送短信成功，手机号：" + patInfo.Phone_NO);
                        }
                        catch (System.Exception e)
                        {
                            _logger.LogError("发送提前一天发送短信失败，预约id：" + info.Id);
                        }
                    }
                    if (patInfo.Pat_Name.IsChinese())
                    {
                        _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "按照政府最新法规要求，以及您的就医体验，就诊时请携带本人或者代办人的有效身份证件原件。", 1);
                    }
                    else
                    {
                        _verifyCodeLogService.SendCusSms(patInfo.Phone_NO, "In accordance with the latest government regulations and to improve your experience, please bring valid ID of yourself or the agent when visit our clinic.", 2);
                    }
                    //patUserInfo = null;
                    patInfo = null;
                    hos = null;
                    mapDeptServ = null;
                }
            }
        }



        public bool PushUserMessage(int patId, string Business, int jgPushType, string title, string content)
        {
            bool result = false;
            string[] pushKey = new string[1];
            string accptMd = "3";
            var users = _pubPatInfoRepository.GetUsersByPatId(patId);
            //获取用户信息
            //Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            foreach (var userInfo in users)
            {
                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.SelectDoctorUnRead(userInfo.ID);
                        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 = userInfo.ID, Is_Read = false, Notice_Type = 1, Remake = "", States = 1, Text = content, User_Id = userInfo.ID });
                    // userId, userId, NoticeType.USER.getValue(), content, jgPushType, Business, null);
                }
            }
            return result;
        }


        public int SendCheckedSms()
        {
            //Date limitTime = CalendarUtil.addSeconds(new Date(), aptCheckSmsDelayInterval);
            List<ConfirmAptInfo> sendList = _outAptInfoRepository.FindCheckedList();
            foreach (var map in sendList)
            {
                string patName = map.PAT_NAME;
                string phone = map.PHONE_NO;
                _logger.LogInformation("延迟发送短信");

                Pub_Sms_Log smsLog = new Pub_Sms_Log();
                smsLog.Sms_Type = 12;//PP预约确认短信
                smsLog.Request = "aptId:" + map.ID;
                smsLog.Id = _pubSmsLogRepository.InsertPubSmsLog(smsLog);

                // 发送确认短信
                SendSmsByID(map.ID, 1, smsLog); //1预约短信
                // 修改预约内部状态
                _outAptInfoRepository.ChangeInnerStatus(map.ID, 4);//4已确认
            }
            if (sendList == null)
            {
                return 0;
            }
            return sendList.Count;
        }

        public bool SendSmsByID(int aptId, int smsType, Pub_Sms_Log smsLog)
        {
            //根据预约号查询预约信息
            Out_Apt_Info oAInFo = _outAptInfoRepository.GetOutAptInfo(aptId);
            Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(oAInFo.Pat_Id);
            Dic_Hos hos = _dicHosRepository.SelectByPrimaryKey(oAInFo.Hos_Id);
            if (smsType == 1)
            {
                return _pubMessageService.SendConfirmSms(hos, oAInFo, patInfo, smsLog);
            }
            else
            {
                return _pubMessageService.SendCancelSms(hos, oAInFo, patInfo, smsLog);
            }
        }

        public BaseResponse<VaccGroupCount> VaccinePhoneConfirm(string phone, string code, int language)
        {
            BaseResponse<VaccGroupCount> res = new BaseResponse<VaccGroupCount>();
            VaccGroupCount info = new VaccGroupCount();
            var log = _verifyCodeLogService.CheckCode(phone, code);
            if (log > 0)
            {
                var group = _vaccineAptRepository.GetVaccGroupList(phone);
                if (group != null)
                {
                    var groupInfo = _vaccineAptRepository.GetOutVaccineApptGroup(group.GroupId);
                    info.SurplusCount = group.ApptCount - group.AptCount > -1 ? group.ApptCount - group.AptCount : 0;
                    info.IsCompanyPhone = true;
                    res.Code = 1;
                    res.Msg = "成功";
                    res.Data = info;
                }
                else
                {
                    res.Msg = language == 1 ? "您还未在企业登记，请先联系企业管理员登记或进行个人预约" : "This number haven't registered in any group, please contact HR for help";
                }
            }
            else
            {
                res.Msg = language == 1 ? "未找到验证码" : "Invalid Verification Code";
            }


            return res;
        }


        public BaseResponse<VaccGroupCount> VaccineUserPhoneConfirm(int language)
        {
            BaseResponse<VaccGroupCount> res = new BaseResponse<VaccGroupCount>();
            var user = GetBaseUserInfo();
            _logger.LogInformation("验证次数1VaccineUserPhoneConfirm:" + user.ID + "  手机:" + user.Phone);
            VaccGroupCount info = new VaccGroupCount();
            var group = _vaccineAptRepository.GetVaccGroupList(user.Phone);
            if (group != null)
            {

                var groupInfo = _vaccineAptRepository.GetOutVaccineApptGroup(group.GroupId);
                info.SurplusCount = group.ApptCount - group.AptCount > -1 ? group.ApptCount - group.AptCount : 0;
                info.IsCompanyPhone = true;
                res.Code = 1;
                res.Msg = "成功";
                _logger.LogInformation("验证次数2VaccineUserPhoneConfirm: 剩余次数" + info.SurplusCount);
            }
            else
            {
                _logger.LogInformation("验证次数2VaccineUserPhoneConfirm: 获取团单失败");
                res.Code = 1;
                res.Msg = language == 1 ? "您还未在企业登记，请先联系企业管理员登记或进行个人预约" : "This number haven't registered in any group, please contact HR for help";
            }
            res.Data = info;
            return res;
        }

        public BaseResponse<VaccGroupInfo> GetCompanyVaccineAptInfo(int patId, int language)
        {
            BaseResponse<VaccGroupInfo> res = new BaseResponse<VaccGroupInfo>();
            VaccGroupInfo info = new VaccGroupInfo();
            var pat = _pubPatInfoRepository.SelectById(patId);
            //if (string.IsNullOrEmpty(pat.Pat_Name) || string.IsNullOrEmpty(pat.Birthday) || string.IsNullOrEmpty(pat.Phone_NO) || string.IsNullOrEmpty(pat.Card_ID))
            //{
            //    var setting = new JsonSerializerSettings
            //    {
            //        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            //    };
            //    Dictionary<string, string> dic = new Dictionary<string, string>();
            //    if (language != 1)
            //    {
            //        dic.Add("key", pat.Pat_Name + " You cannot register for the queue, please complete the patient information first");
            //    }
            //    else
            //    {
            //        dic.Add("key", pat.Pat_Name + " 患者信息暂未完善，无法登记排队，请完善信息后登记");
            //    }
            //    dic.Add("value", JsonConvert.SerializeObject(pat, setting));
            //    res.Code = 12;
            //    res.Msg = JsonConvert.SerializeObject(dic);
            //    return res;
            //}
            var group = _vaccineAptRepository.GetVaccGroupList(pat.Phone_NO);
            if (group == null)
            {
                group = _vaccineAptRepository.GetVaccGroupList(GetBaseUserInfo().Phone);
            }
            if (group != null)
            {
                var groupInfo = _vaccineAptRepository.GetOutVaccineApptGroup(group.GroupId);
                if (groupInfo != null)
                {
                    info.HosId = groupInfo.HosId;
                    var hos = _dicHosRepository.SelectByPrimaryKey(groupInfo.HosId);
                    if (hos != null)
                    {
                        info.HosName = language == 1 ? hos.CN_Abbreviated_Addr : hos.EN_Abbreviated_Addr;
                    }
                    info.VaccineBrand = language == 1 ? groupInfo.VaccineBrandCN : groupInfo.VaccineBrandEN;
                    info.PatBirthday = pat.Birthday;
                    info.PatId = pat.Id;
                    info.PatName = pat.Pat_Name;
                    info.Origin = groupInfo.Origin;
                    info.PatPhone = pat.Phone_NO;
                    info.VaccineName = language == 1 ? groupInfo.VaccineNameCN : groupInfo.VaccineNameEN;
                    info.AptTimeBegin = groupInfo.AptTimeBegin;
                    info.AptTimeEnd = groupInfo.AptTimeEnd;
                    var userPat = _pubPatInfoRepository.GetUserPatByPatId(info.PatId);
                    if (userPat == null || userPat.Find(p => p.Relation_Ship == 1) == null)
                    {
                        info.Temporary = true;
                    }
                }
                res.Code = 1;
                res.Msg = "成功";
            }
            else
            {
                res.Code = 1;
                res.Msg = language == 1 ? "您还未在企业登记，请先联系企业管理员登记或进行个人预约" : "This number haven't registered in any group, please contact HR for help";
            }
            res.Data = info;
            return res;
        }

        public void SendSurvey()
        {
            List<Out_Apt_Info> list = _outAptInfoRepository.SelectToday();
            if (list != null && list.Count() > 0)
            {
                _logger.LogInformation("开始发送当天满意度调查短信");
                Pub_Pat_Info patInfo = null;
                Dic_Map_Dept_Serv mapDeptServ = null;
                Pub_Sms_Log smsLog = null;

                foreach (var info in list)
                {
                    patInfo = _pubPatInfoRepository.SelectById(info.Pat_Id);

                    smsLog = new Pub_Sms_Log();
                    smsLog.Request = "AptId=" + info.Id;
                    smsLog.Sms_Type = 41;//当天就真满意度调查短信
                    var id = _pubSmsLogRepository.InsertPubSmsLog(smsLog);
                    smsLog.Id = id;
                    if (info.Apt_Proj != 0)
                        if (info.Apt_Id > 0)
                        {//疫苗预约 存的Apt_Proj  是his的Apt_Proj并不是线下存的本地Apt_Proj服务
                            mapDeptServ = _dicMapDeptServRepository.SelectByHisKey(info.Apt_Proj);
                        }
                        else
                        {//线下预约
                            mapDeptServ = _dicMapDeptServRepository.SelectByPrimaryKey(info.Apt_Proj);
                        }


                    //发送短信
                    if (mapDeptServ != null && mapDeptServ.Is_Send)
                    {
                        string smsContent;
                        //判断病人名称是否英文
                        if (!patInfo.Pat_Name.IsChinese())
                        {
                            //发送英文短信
                            smsContent = "【SinoUnited Health】Thank you for choosing SinoUnited Health. Please reply with a number from “1” to“5”to rate your visit today. “5” means excellent and“1”means poor. If you have more recommendations, please also reply via this message.";
                        }
                        else
                        {
                            //发送中文短信
                            smsContent = "【曜影医疗】感谢您对曜影医疗的支持与信任,为了给您提供更优质的服务, 请对今天的就诊体验进行1~5分之间的评分，5分为最高，1分为最低，谢谢！如您对我们的服务有更多意见或建议，欢迎您回复告知。";
                        }
                        try
                        {
                            string result = _smsSurveyService.SendSurvey(patInfo.Phone_NO, smsContent, "");
                            smsLog.Result = "发送当天满意度调查短信成功，手机号：" + patInfo.Phone_NO;
                            smsLog.Send_Time = DateTime.Now.ToString();
                            smsLog.Sms_Content = smsContent;
                            _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);

                            //添加短信发送记录
                            Pub_Pat_Info finalPatInfo = patInfo;
                            Pub_Sms_Survey smsSurvey = new Pub_Sms_Survey()
                            {
                                Phone = finalPatInfo.Phone_NO,
                                Name = finalPatInfo.Pat_Name,
                                Apt_Time = info.Apt_Time.Value,
                                Pid = result.Split(',')[1],
                                Pat_Mrn = finalPatInfo.Pat_MRN,
                                Hos_Id = info.Hos_Id
                            };
                            _pubSmsLogRepository.InsertPubSmsSurvey(smsSurvey);

                        }
                        catch (System.Exception e)
                        {
                            smsLog.Result = "发送当天满意度调查短信失败，预约id：" + info.Id + "，手机号：" + patInfo.Phone_NO + ",错误信息：" + e.Message;
                            _pubSmsLogRepository.UpdateByPrimaryKey(smsLog);
                        }
                    }
                }
            }
        }

        public BaseResponse<int> LockAptUsrn(AptCommitModel model)
        {
            BaseResponse<int> res = new BaseResponse<int>();
            var apt = _outAptInfoRepository.GetAptByCondition(model);
            if (apt != null)
            {
                res.Msg = model.Language == 1 ? "您当天已经预约过该科室" : "This patient already have appointment with the same doctor on selected date";
                return res;
            }

            var user = GetBaseUserInfo();
            var patLocks = _sanFangRepository.GetPatLockUsrn(model.PatId);
            if (patLocks != null && patLocks.Find(p => p.UsrnStatus == "L") != null)
            {
                var patLock = patLocks.Find(p => p.UsrnStatus == "L");
                if (patLock.AptUsrn == model.AptUsrn)
                {
                    res.Msg = model.Language == 1 ? "成功" : "Success";
                    res.Code = 1;
                    return res;
                }
                else
                {
                    UnLockAptUsrn(model.PatId, patLock.AptUsrn, "预约换号解号");
                }
            }

            //var usrnRecord = _sanFangRepository.GetLockUsrn(user.ID, model.AptUsrn);//获取的是没有被下单的排班
            //if (usrnRecord != null && usrnRecord.UsrnStatus == "L")
            //{
            //    res.Msg = model.Language == 1 ? "成功" : "Success";
            //    res.Code = 1;
            //    return res;
            //}
            var lockret = _tcService.LockApt(model.AptUsrn, model.AptUsrn, "L");
            if (lockret)
            {
                _sanFangRepository.InsertLockUsrn(new Lock_Usrn() { AptUsrn = model.AptUsrn, CreateTime = DateTime.Now, UserId = GetBaseUserInfo().ID, UsrnStatus = "L", PatId = model.PatId, Record = model.ToJson(), IsUse = false, Remark = "" });
                res.Msg = model.Language == 1 ? "成功" : "Success";
                res.Code = 1;
                return res;
            }
            else
            {
                return GetTodayIsHasScheduling(model);
            }
        }



        /// <summary>
        /// 返回预约这天 是否还有号原
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private BaseResponse<int> GetTodayIsHasScheduling(AptCommitModel model)
        {
            BaseResponse<int> res = new BaseResponse<int>();
            //获取排班信息
            var scheduling = QuerySchedulingByApp(model.HosId, model.DeptId, model.DocId, model.AptProj, model.AptTime.Value.ToString("yyyy-MM-dd"), model.AptTime.Value.ToString("yyyy-MM-dd"), model.Language);
            if (scheduling != null)
            {
                if (scheduling.SlotDateList.Count > 0 && scheduling.SlotDateList.FirstOrDefault().ResourceList?.Length > 0)
                {
                    if (scheduling.SlotDateList.FirstOrDefault().ResourceList.FirstOrDefault().SlotList?.Length > 0)
                    {
                        res.Msg = model.Language == 1 ? "该号源已经被其他人约掉了，请重新选择时间" : "This slot is no longer available. Please choose another time";
                        res.Code = -1;
                        return res;
                    }
                }
            }
            res.Msg = model.Language == 1 ? "当天号源已约满，请重新选择日期" : "All the slots are full for the day. Please choose another date";
            res.Code = -2;
            return res;
        }

        public BaseResponse<int> AptCommit(AptCommitModel model)
        {
            BaseResponse<int> res = new BaseResponse<int>();

            var authRes = _authorizationService.IsHasAuth(GetBaseUserInfo().ID, model.PatId, (int)AuthType.OFFLINE, 1);
            if (!string.IsNullOrEmpty(authRes))
            {
                res.Code = 0;
                res.Msg = authRes;
                return res;
            }

            Out_Apt_Info outAptInfo = new Out_Apt_Info();
            outAptInfo.Apt_Proj = model.AptProj;
            outAptInfo.Apt_Time = model.AptTime;
            outAptInfo.Apt_Usrn = model.AptUsrn;
            outAptInfo.Create_Time = DateTime.Now;
            outAptInfo.Dept_ID = model.DeptId;
            outAptInfo.Doc_Id = model.DocId;
            outAptInfo.Hos_Id = model.HosId;
            outAptInfo.Pat_Id = model.PatId;
            outAptInfo.Remark = model.Remark;
            outAptInfo.Source_Type = model.SourceType;
            outAptInfo.Status = 0;//未录入 系统
            outAptInfo.Match_Code = Common.CreateCode(16);// 添加匹配码，便于确认
            outAptInfo.Inner_Status = 0;
            outAptInfo.Channel = model.Channel;
            if (outAptInfo.Channel == 1)
            {
                if (GetBaseUserInfo()?.Key_Type == 1)
                {
                    outAptInfo.Channel = 5;
                }
                else if (GetBaseUserInfo()?.Key_Type == 2)
                {
                    outAptInfo.Channel = 6;
                }
            }
            Pub_User_Info userInfo = GetBaseUserInfo();
            outAptInfo.Apply_User_Id = userInfo.ID;
            Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(outAptInfo.Pat_Id);
            var usrnRecord = _sanFangRepository.GetLockUsrn(model.PatId, model.AptUsrn);
            if (usrnRecord == null || usrnRecord.UsrnStatus == "U")
            {
                var newUsrn = string.Empty;
                //获取排班信息
                Scheduling scheduling = QuerySchedulingByApp(model.HosId, model.DeptId, model.DocId, model.AptProj, model.AptTime.Value.ToString("yyyy-MM-dd"), model.AptTime.Value.ToString("yyyy-MM-dd"), model.Language);
                if (scheduling != null)
                {
                    if (scheduling.SlotDateList.Count > 0 && scheduling.SlotDateList.FirstOrDefault().ResourceList?.Length > 0)
                    {
                        if (scheduling.SlotDateList.FirstOrDefault().ResourceList.FirstOrDefault().SlotList?.Length > 0)
                        {
                            foreach (var item in scheduling.SlotDateList.FirstOrDefault().ResourceList.FirstOrDefault().SlotList)
                            {
                                if (item.StartTime == model.AptTime?.ToString("HH:mm:ss"))
                                {
                                    newUsrn = item.Usrn;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (string.IsNullOrEmpty(newUsrn))
                {
                    return GetTodayIsHasScheduling(model);
                }
                model.AptUsrn = newUsrn;
                outAptInfo.Apt_Usrn = newUsrn;

                var relock = _tcService.LockApt(model.AptUsrn, model.AptUsrn, "L");
                if (!relock)
                {//重新锁号失败则 返回报错
                    return GetTodayIsHasScheduling(model);
                }
                else
                {
                    if (usrnRecord == null)
                    {
                        _sanFangRepository.InsertLockUsrn(new Lock_Usrn() { AptUsrn = model.AptUsrn, CreateTime = DateTime.Now, UserId = GetBaseUserInfo().ID, UsrnStatus = "L", PatId = model.PatId, Record = model.ToJson(), IsUse = false, Remark = "" });
                    }
                    else
                    {
                        usrnRecord.AptUsrn = newUsrn;
                        usrnRecord.UsrnStatus = "L";
                        usrnRecord.Record = model.ToJson();
                        _sanFangRepository.UpdateLockUsrn(usrnRecord);
                    }

                }
            }
            var aptRet = false;
            try
            {
                aptRet = _tcService.NewCommitApt(outAptInfo.Apt_Usrn, patInfo.Pat_ID);
            }
            catch (System.Exception ex)
            {
                _tcService.LockApt(outAptInfo.Apt_Usrn, outAptInfo.Apt_Usrn, "U");
                return GetTodayIsHasScheduling(model);
            }
            if (aptRet)
            {
                outAptInfo.Status = 1;
                outAptInfo.Inner_Status = 1;
                var outId = _outAptInfoRepository.InsertOutAptInfo(outAptInfo);
                usrnRecord.IsUse = true;
                usrnRecord.Record = model.ToJson();
                _sanFangRepository.UpdateLockUsrn(usrnRecord);
                res.Data = outId;
            }
            else
            {
                //解号
                UnLockAptUsrn(model.PatId, outAptInfo.Apt_Usrn, "预约失败解号");
                var reb = GetTodayIsHasScheduling(model);
                reb.Code = -3;
                return reb;
            }

            if (outAptInfo.Status == 1)
            {
                _pubMessageService.SendAptSmsMsg2User(outAptInfo.Hos_Id, patInfo, userInfo.Language, outAptInfo.Apt_Time);
            }
            string pName = patInfo.Pat_Name == null ? "" : patInfo.Pat_Name;
            _pubMessageService.SendAptWxMsg2User(outAptInfo.Hos_Id, outAptInfo.Doc_Id, outAptInfo.Dept_ID, outAptInfo.Apply_User_Id,
                    pName, patInfo.Phone_NO, outAptInfo.Apt_Time);
            res.Msg = model.Language == 1 ? "成功" : "Success";
            res.Code = 1;
            return res;

        }

        public bool UnLockAptUsrn(int patId, string usrn, string remark)
        {
            var res = _tcService.LockApt(usrn, usrn, "U");
            if (res)
            {
                var usrnRecord = _sanFangRepository.UnLockUsrn(patId, usrn, remark);
            }
            return res;
        }

        public void UpdateLockNoUseUsrnStatus()
        {
            //_sanFangRepository.UpdateLockNoUseUsrnStatus("系统超时解号");
            var list = _sanFangRepository.GetLockNoUseUsrnStatus();
            if (list?.Count > 0)
            {
                foreach (var item in list)
                {
                    var res = _tcService.LockApt(item.AptUsrn, item.AptUsrn, "U");
                    _sanFangRepository.UpdateLockNoUseUsrnStatusById(item.Id, "系统超时解号");
                }
            }
        }

        public bool ReservationByUser(OutVaccineApptReq outVaccineAppt)
        {
            int result = 0;

            //获取医保卡信息
            Pub_Map_User_Insurance userInsurance = _pubInsuranceRepository.GetPubMapUserInsurance(outVaccineAppt.InsuranceId);
            //添加流水信息
            Out_Vaccine_Appt_Flow outVaccineApptFlow = new Out_Vaccine_Appt_Flow();
            outVaccineApptFlow.REQUEST_PARAM = outVaccineAppt.ToString();
            outVaccineApptFlow.RESOUCE_TYPE = 1;
            outVaccineApptFlow.STATUS = 1;
            outVaccineApptFlow.CREATE_TIME = DateTime.Now;
            result += _outAptInfoRepository.InsertOutVaccineApptFlow(outVaccineApptFlow);

            foreach (var patId in outVaccineAppt.Pat)
            {
                //添加预约信息
                Out_Vaccine_Appt vaccineAppt = new Out_Vaccine_Appt();
                Pub_Pat_Info patInfo = _pubPatInfoRepository.SelectById(patId);
                if (patInfo == null)
                {
                    continue;
                }
                vaccineAppt.USER_ID = GetBaseUserInfo().ID;
                if (userInsurance != null)
                {
                    vaccineAppt.INSURANCE_NO = userInsurance.Insurance_No;
                    vaccineAppt.INSURANCE_ID = userInsurance.Id;
                    vaccineAppt.PAY_IMAGE = userInsurance.Pay_Image;
                }
                vaccineAppt.REMAKE = outVaccineAppt.Remake;
                vaccineAppt.IS_TREATMENT = outVaccineAppt.IsTreatment;
                vaccineAppt.HPV_TYPE = outVaccineAppt.HpvType;
                vaccineAppt.HPT_PIN = outVaccineAppt.HptPin;
                vaccineAppt.PAY_TYPE = outVaccineAppt.PayType;
                vaccineAppt.LANGUAGE = outVaccineAppt.Language;
                vaccineAppt.PAT_ID = patId;
                vaccineAppt.VACCINE_ID = outVaccineAppt.VaccineId;
                vaccineAppt.CREATE_TIME = DateTime.Now;
                vaccineAppt.STATUS = 0;
                vaccineAppt.FLOW_ID = outVaccineApptFlow.Id;
                vaccineAppt.MATCH_CODE = "VACCINE_APPT_" + Common.CreateCode(9);
                vaccineAppt.INSURANCE_ID = outVaccineAppt.InsuranceId;
                result += _outAptInfoRepository.InsertOutVaccineAppt(vaccineAppt);

                //发送微信模板消息
                _pubMessageService.SendVaccineAptWxMsg2User(GetBaseUserInfo().ID, patInfo.Pat_Name, patInfo.Phone_NO);
                //发送微信模板消息（发送到小影）
                _pubMessageService.SendVaccineAptWxMsg2Service(patInfo.Pat_Name, patInfo.Phone_NO);
            }

            return result > 1;
        }
        public List<SurveyModel> GetSurveySendMsgCount(string startDate, string endDate)
        {
            return _dataRepository.GetSurveySendMsgCount(startDate, endDate);
        }
        public List<Pub_Sms_Survey> GetSurveyReplyMsgCount(string startDate, string endDate)
        {
            return _dataRepository.GetSurveyReplyMsgCount(startDate, endDate);
        }

        public List<DataApts> GetAptListFromMonth(string startDate, string endDate)
        {
            return _dataRepository.GetAptListFromMonth(startDate, endDate);
        }

        public List<DataPatAptMore> GetDeptAptMore(string startDate, string endDate)
        {
            return _dataRepository.GetDeptAptMore(startDate, endDate);
        }
    }
}
