using PoJun.Dapper;
using ASHermed.SinoInterface.Api.IRepository.Test;
using ASHermed.SinoInterface.Entity.Test;
using ASHermed.SinoInterface.Repository.MySql;
using ASHermed.SinoInterface.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App.Entity;
using ASHermed.SinoInterface.Api.ContractModel.App.Model;
using ASHermed.SinoInterface.Api.ContractModel.TCTrans;
using System.IO;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{

    public class PubPatInfoRepository : BaseRepositoryToASHermed_SinoInterface<Pub_Pat_Info>, IPubPatInfoRepository
    {
        public int InsertPubPatInfo(Pub_Pat_Info patInfo)
        {
            patInfo.Encrypt();
            StringBuilder str = new StringBuilder();
            str.Append(@"insert into pub_pat_info (PAT_ID,PAT_MRN,LAST_NAME,FIRST_NAME,PAT_NAME,BIRTHDAY ,GENDER,CARD_ID,CARD_TYPE,CardValidity,PHONE_NO,PROVINCE,CITY,DISTRICT,EMAIL,NATIONALITY,IS_DEAD,IS_ACTIVE,PAT_SOURCE,IS_DELETED,MRN_NO,PAT_MRN_NUMBER,ID_NUMBER,GUARDIAN,Last_GUARDIAN,First_GUARDIAN,DOCUMENT_TYPE,CERTIFICATE_NUMBER,IsDefault,IDCardUrlFront,IDCardUrlBack,CityId,LocalAddress,EmergencyName,EmergencyPhone,EmergencyRelation,HowKnow,ContactWay,ContactValue,PayType,InsuranceCardUrl,Mrn,CreateTime) value (@PAT_ID,@PAT_MRN,@LAST_NAME,@FIRST_NAME,@PAT_NAME,@BIRTHDAY,@GENDER,@CARD_ID,@CARD_TYPE,@CardValidity,@PHONE_NO,@PROVINCE,@CITY,@DISTRICT,@EMAIL,@NATIONALITY,@IS_DEAD,@IS_ACTIVE,@PAT_SOURCE,@IS_DELETED,@MRN_NO,@PAT_MRN_NUMBER,@ID_NUMBER,@GUARDIAN,@Last_GUARDIAN,@First_GUARDIAN,@DOCUMENT_TYPE,@CERTIFICATE_NUMBER,@IsDefault,@IDCardUrlFront,@IDCardUrlBack,@CityId,@LocalAddress,@EmergencyName,@EmergencyPhone,@EmergencyRelation,@HowKnow,@ContactWay,@ContactValue,@PayType,@InsuranceCardUrl,@Mrn,@CreateTime) ");
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patInfo.Pat_ID);
            parms.Add("@PAT_MRN", patInfo.Pat_MRN);
            parms.Add("@LAST_NAME", patInfo.Last_Name);
            parms.Add("@FIRST_NAME", patInfo.First_Name);
            parms.Add("@PAT_NAME", patInfo.Pat_Name);
            parms.Add("@BIRTHDAY", patInfo.Birthday == "0001-01-01" ? "" : patInfo.Birthday);
            parms.Add("@GENDER", patInfo.Gender);
            parms.Add("@CARD_ID", patInfo.Card_ID);
            parms.Add("@CARD_TYPE", patInfo.Card_Type);
            parms.Add("@CardValidity", patInfo.CardValidity);
            parms.Add("@PHONE_NO", patInfo.Phone_NO);
            parms.Add("@PROVINCE", patInfo.Province);
            parms.Add("@CITY", patInfo.City);
            parms.Add("@DISTRICT", patInfo.District);
            parms.Add("@EMAIL", patInfo.Email);
            parms.Add("@NATIONALITY", patInfo.Nationality);
            parms.Add("@IS_DEAD", patInfo.Is_Dead);
            parms.Add("@IS_ACTIVE", patInfo.Is_Active);
            parms.Add("@PAT_SOURCE", patInfo.Pat_Source);
            parms.Add("@IS_DELETED", patInfo.Is_Deleted);
            parms.Add("@MRN_NO", patInfo.Mrn_NO);
            parms.Add("@PAT_MRN_NUMBER", patInfo.Pat_Mrn_Number);
            parms.Add("@ID_NUMBER", patInfo.Id_Number);
            parms.Add("@GUARDIAN", patInfo.Guardian);
            parms.Add("@Last_GUARDIAN", patInfo.Last_Guardian);
            parms.Add("@First_GUARDIAN", patInfo.First_Guardian);
            parms.Add("@DOCUMENT_TYPE", patInfo.Document_Type);
            parms.Add("@CERTIFICATE_NUMBER", patInfo.Certificate_Number);
            parms.Add("@IsDefault", patInfo.IsDefault);
            parms.Add("@IDCardUrlFront", patInfo.IDCardUrlFront);
            parms.Add("@IDCardUrlBack", patInfo.IDCardUrlBack);
            parms.Add("@CityId", patInfo.CityId);
            parms.Add("@LocalAddress", patInfo.LocalAddress);
            parms.Add("@EmergencyName", patInfo.EmergencyName);
            parms.Add("@EmergencyPhone", patInfo.EmergencyPhone);
            parms.Add("@EmergencyRelation", patInfo.EmergencyRelation);
            parms.Add("@HowKnow", patInfo.HowKnow);
            parms.Add("@ContactWay", patInfo.ContactWay);
            parms.Add("@ContactValue", patInfo.ContactValue);
            parms.Add("@PayType", patInfo.PayType);
            parms.Add("@InsuranceCardUrl", patInfo.InsuranceCardUrl);
            parms.Add("@Mrn", patInfo.Mrn);
            parms.Add("@CreateTime", DateTime.Now);
            var result = this.Insert(str.ToString(), parms);
            return result;
        }
        public int InsertGroupInfo(string groupId, int userId, int patId, int docId, int helpId, string orderNo)
        {
            StringBuilder str = new StringBuilder();
            str.Append(@"insert into tencent_group_record (GroupId,UserId,PatId,DocId,HelperId,IsForbiddenSpeech,Status,OrderNo) value (@GroupId,@UserId,@PatId,@DocId,@HelperId,@IsForbiddenSpeech,@Status,@OrderNo) ");
            var parms = new Dictionary<string, object>();
            parms.Add("@GroupId", groupId);
            parms.Add("@UserId", userId);
            parms.Add("@PatId", patId);
            parms.Add("@DocId", docId);
            parms.Add("@HelperId", helpId);
            parms.Add("@IsForbiddenSpeech", false);
            parms.Add("@Status", 1);
            parms.Add("@OrderNo", orderNo);
            var result = this.Insert(str.ToString(), parms);
            return result;
        }

        public int UpdateGroupOrder(Tencent_Group_Record group)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update tencent_group_record set ");
            str.Append(@"OrderNo=@OrderNo");
            str.Append(@" where GroupId=@GroupId");
            var parms = new Dictionary<string, object>();

            parms.Add("@OrderNo", group.OrderNo);
            parms.Add("@GroupId", group.GroupId);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int SynchroGroupOrder(int patId, int docId, string orderNo)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update tencent_group_record set ");
            str.Append(@"OrderNo=@OrderNo");
            str.Append(@" where `Status`=1 and PatId=@PatId and DocId=@DocId");
            var parms = new Dictionary<string, object>();
            parms.Add("@PatId", patId);
            parms.Add("@DocId", docId);
            parms.Add("@OrderNo", orderNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdatePubPatInfo(Pub_Pat_Info patInfo, int isNewPat = 0)
        {
            if (isNewPat != 0)
            {
                patInfo.Encrypt();
            }
            StringBuilder str = new StringBuilder();
            str.Append("update Pub_Pat_Info set ");
            if (!string.IsNullOrEmpty(patInfo.Pat_ID))
            {
                str.Append(@"PAT_ID=@PAT_ID,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_MRN))
            {
                str.Append(@"PAT_MRN=@PAT_MRN,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Name))
            {
                str.Append(@"LAST_NAME=@LAST_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.First_Name))
            {
                str.Append(@"FIRST_NAME=@FIRST_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_Name))
            {
                str.Append(@"PAT_NAME=@PAT_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.Birthday))
            {
                str.Append(@"BIRTHDAY=@BIRTHDAY,");
            }
            if (patInfo.Gender != null)
            {
                str.Append(@"GENDER=@GENDER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Card_ID))
            {
                str.Append(@"CARD_ID=@CARD_ID,");
            }
            if (patInfo.Card_Type > 0)
            {
                str.Append(@"CARD_TYPE=@CARD_TYPE,");
            }

            if (!string.IsNullOrEmpty(patInfo.CardValidity))
            {
                str.Append(@"CardValidity=@CardValidity,");
            }
            if (!string.IsNullOrEmpty(patInfo.Phone_NO))
            {
                str.Append(@"PHONE_NO=@PHONE_NO,");
            }
            if (!string.IsNullOrEmpty(patInfo.Province))
            {
                str.Append(@"PROVINCE=@PROVINCE,");
            }
            if (!string.IsNullOrEmpty(patInfo.City))
            {
                str.Append(@"CITY=@CITY,");
            }
            if (!string.IsNullOrEmpty(patInfo.District))
            {
                str.Append(@"DISTRICT=@DISTRICT,");
            }
            if (!string.IsNullOrEmpty(patInfo.Email))
            {
                str.Append(@"EMAIL=@EMAIL,");
            }
            if (!string.IsNullOrEmpty(patInfo.Nationality))
            {
                str.Append(@"NATIONALITY=@NATIONALITY,");
            }
            str.Append(@"IS_DEAD=@IS_DEAD,");
            str.Append(@"IS_ACTIVE=@IS_ACTIVE,");
            if (patInfo.Pat_Source > -1)
            {
                str.Append(@"PAT_SOURCE=@PAT_SOURCE,");
            }

            if (!string.IsNullOrEmpty(patInfo.Mrn_NO))
            {
                str.Append(@"MRN_NO=@MRN_NO,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_Mrn_Number))
            {
                str.Append(@"PAT_MRN_NUMBER=@PAT_MRN_NUMBER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Id_Number))
            {
                str.Append(@"ID_NUMBER=@ID_NUMBER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Guardian))
            {
                str.Append(@"GUARDIAN=@GUARDIAN,");
            }
            if (!string.IsNullOrEmpty(patInfo.GuardianPhone))
            {
                str.Append(@"GuardianPhone=@GuardianPhone,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Guardian))
            {
                str.Append(@"Last_GUARDIAN=@Last_GUARDIAN,");
            }
            if (!string.IsNullOrEmpty(patInfo.First_Guardian))
            {
                str.Append(@"First_GUARDIAN=@First_GUARDIAN,");
            }
            if (patInfo.Document_Type > -1)
            {
                str.Append(@"DOCUMENT_TYPE=@DOCUMENT_TYPE,");
            }
            if (!string.IsNullOrEmpty(patInfo.Certificate_Number))
            {
                str.Append(@"CERTIFICATE_NUMBER=@CERTIFICATE_NUMBER,");
            }
            if (patInfo.Last_Sign_Off != null)
            {
                str.Append(@"LAST_SIGN_OFF=@LAST_SIGN_OFF,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Sign_EpisodeNo))
            {
                str.Append(@"LAST_SIGN_EpisodeNo=@LAST_SIGN_EpisodeNo,");
            }
            str.Append(@"IsDefault=@IsDefault,");
            if (!string.IsNullOrEmpty(patInfo.IDCardUrlFront))
            {
                str.Append(@"IDCardUrlFront=@IDCardUrlFront,");
            }
            if (!string.IsNullOrEmpty(patInfo.IDCardUrlBack))
            {
                str.Append(@"IDCardUrlBack=@IDCardUrlBack,");
            }
            if (patInfo.CityId > 0)
            {
                str.Append(@"CityId=@CityId,");
            }
            if (!string.IsNullOrEmpty(patInfo.LocalAddress))
            {
                str.Append(@"LocalAddress=@LocalAddress,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyName))
            {
                str.Append(@"EmergencyName=@EmergencyName,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyPhone))
            {
                str.Append(@"EmergencyPhone=@EmergencyPhone,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyRelation))
            {
                str.Append(@"EmergencyRelation=@EmergencyRelation,");
            }
            if (patInfo.HowKnow > 0)
            {
                str.Append(@"HowKnow=@HowKnow,");
            }
            if (patInfo.PayType > 0)
            {
                str.Append(@"PayType=@PayType,");
            }
            if (!string.IsNullOrEmpty(patInfo.InsuranceCardUrl))
            {
                str.Append(@"InsuranceCardUrl=@InsuranceCardUrl,");
            }
            if (!string.IsNullOrEmpty(patInfo.Mrn))
            {
                str.Append(@"Mrn=@Mrn,");
            }
            if (patInfo.ContactWay > 0)
            {
                str.Append(@"ContactWay=@ContactWay,");
            }
            if (!string.IsNullOrEmpty(patInfo.ContactValue))
            {
                str.Append(@"ContactValue=@ContactValue,");
            }
            str.Append(@"IS_DELETED=@IS_DELETED");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patInfo.Pat_ID);
            parms.Add("@PAT_MRN", patInfo.Pat_MRN);
            parms.Add("@LAST_NAME", patInfo.Last_Name);
            parms.Add("@FIRST_NAME", patInfo.First_Name);
            parms.Add("@PAT_NAME", patInfo.Pat_Name);
            parms.Add("@BIRTHDAY", patInfo.Birthday);
            parms.Add("@GENDER", patInfo.Gender);
            parms.Add("@CARD_ID", patInfo.Card_ID);
            parms.Add("@CARD_TYPE", patInfo.Card_Type);
            parms.Add("@CardValidity", patInfo.CardValidity);
            parms.Add("@PHONE_NO", patInfo.Phone_NO);
            parms.Add("@PROVINCE", patInfo.Province);
            parms.Add("@CITY", patInfo.City);
            parms.Add("@DISTRICT", patInfo.District);
            parms.Add("@EMAIL", patInfo.Email);
            parms.Add("@NATIONALITY", patInfo.Nationality);
            parms.Add("@IS_DEAD", patInfo.Is_Dead);
            parms.Add("@IS_ACTIVE", patInfo.Is_Active);
            parms.Add("@PAT_SOURCE", patInfo.Pat_Source);
            parms.Add("@IS_DELETED", patInfo.Is_Deleted);
            parms.Add("@MRN_NO", patInfo.Mrn_NO);
            parms.Add("@PAT_MRN_NUMBER", patInfo.Pat_Mrn_Number);
            parms.Add("@ID_NUMBER", patInfo.Id_Number);
            parms.Add("@GUARDIAN", patInfo.Guardian);
            parms.Add("@GuardianPhone", patInfo.GuardianPhone);
            parms.Add("@Last_GUARDIAN", patInfo.Last_Guardian);
            parms.Add("@First_GUARDIAN", patInfo.First_Guardian);
            parms.Add("@DOCUMENT_TYPE", patInfo.Document_Type);
            parms.Add("@CERTIFICATE_NUMBER", patInfo.Certificate_Number);
            parms.Add("@LAST_SIGN_OFF", patInfo.Last_Sign_Off);
            parms.Add("@LAST_SIGN_EpisodeNo", patInfo.Last_Sign_EpisodeNo);
            parms.Add("@IsDefault", patInfo.IsDefault);
            parms.Add("@IDCardUrlFront", patInfo.IDCardUrlFront);
            parms.Add("@IDCardUrlBack", patInfo.IDCardUrlBack);
            parms.Add("@CityId", patInfo.CityId);
            parms.Add("@LocalAddress", patInfo.LocalAddress);
            parms.Add("@EmergencyName", patInfo.EmergencyName);
            parms.Add("@EmergencyPhone", patInfo.EmergencyPhone);
            parms.Add("@EmergencyRelation", patInfo.EmergencyRelation);
            parms.Add("@HowKnow", patInfo.HowKnow);
            parms.Add("@ContactWay", patInfo.ContactWay);
            parms.Add("@ContactValue", patInfo.ContactValue);
            parms.Add("@PayType", patInfo.PayType);
            parms.Add("@InsuranceCardUrl", patInfo.InsuranceCardUrl);
            parms.Add("@Mrn", patInfo.Mrn);
            parms.Add("@ID", patInfo.Id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public async Task<int> UpdatePubPatInfoAsync(Pub_Pat_Info patInfo, int isNewPat = 0)
        {
            if (isNewPat != 0)
            {
                patInfo.Encrypt();
            }
            StringBuilder str = new StringBuilder();
            str.Append("update Pub_Pat_Info set ");
            if (!string.IsNullOrEmpty(patInfo.Pat_ID))
            {
                str.Append(@"PAT_ID=@PAT_ID,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_MRN))
            {
                str.Append(@"PAT_MRN=@PAT_MRN,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Name))
            {
                str.Append(@"LAST_NAME=@LAST_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.First_Name))
            {
                str.Append(@"FIRST_NAME=@FIRST_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_Name))
            {
                str.Append(@"PAT_NAME=@PAT_NAME,");
            }
            if (!string.IsNullOrEmpty(patInfo.Birthday))
            {
                str.Append(@"BIRTHDAY=@BIRTHDAY,");
            }
            if (patInfo.Gender != null)
            {
                str.Append(@"GENDER=@GENDER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Card_ID))
            {
                str.Append(@"CARD_ID=@CARD_ID,");
            }
            if (patInfo.Card_Type > 0)
            {
                str.Append(@"CARD_TYPE=@CARD_TYPE,");
            }

            if (!string.IsNullOrEmpty(patInfo.CardValidity))
            {
                str.Append(@"CardValidity=@CardValidity,");
            }
            if (!string.IsNullOrEmpty(patInfo.Phone_NO))
            {
                str.Append(@"PHONE_NO=@PHONE_NO,");
            }
            if (!string.IsNullOrEmpty(patInfo.Province))
            {
                str.Append(@"PROVINCE=@PROVINCE,");
            }
            if (!string.IsNullOrEmpty(patInfo.City))
            {
                str.Append(@"CITY=@CITY,");
            }
            if (!string.IsNullOrEmpty(patInfo.District))
            {
                str.Append(@"DISTRICT=@DISTRICT,");
            }
            if (!string.IsNullOrEmpty(patInfo.Email))
            {
                str.Append(@"EMAIL=@EMAIL,");
            }
            if (!string.IsNullOrEmpty(patInfo.Nationality))
            {
                str.Append(@"NATIONALITY=@NATIONALITY,");
            }
            str.Append(@"IS_DEAD=@IS_DEAD,");
            str.Append(@"IS_ACTIVE=@IS_ACTIVE,");
            if (patInfo.Pat_Source > -1)
            {
                str.Append(@"PAT_SOURCE=@PAT_SOURCE,");
            }

            if (!string.IsNullOrEmpty(patInfo.Mrn_NO))
            {
                str.Append(@"MRN_NO=@MRN_NO,");
            }
            if (!string.IsNullOrEmpty(patInfo.Pat_Mrn_Number))
            {
                str.Append(@"PAT_MRN_NUMBER=@PAT_MRN_NUMBER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Id_Number))
            {
                str.Append(@"ID_NUMBER=@ID_NUMBER,");
            }
            if (!string.IsNullOrEmpty(patInfo.Guardian))
            {
                str.Append(@"GUARDIAN=@GUARDIAN,");
            }
            if (!string.IsNullOrEmpty(patInfo.GuardianPhone))
            {
                str.Append(@"GuardianPhone=@GuardianPhone,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Guardian))
            {
                str.Append(@"Last_GUARDIAN=@Last_GUARDIAN,");
            }
            if (!string.IsNullOrEmpty(patInfo.First_Guardian))
            {
                str.Append(@"First_GUARDIAN=@First_GUARDIAN,");
            }
            if (patInfo.Document_Type > -1)
            {
                str.Append(@"DOCUMENT_TYPE=@DOCUMENT_TYPE,");
            }
            if (!string.IsNullOrEmpty(patInfo.Certificate_Number))
            {
                str.Append(@"CERTIFICATE_NUMBER=@CERTIFICATE_NUMBER,");
            }
            if (patInfo.Last_Sign_Off != null)
            {
                str.Append(@"LAST_SIGN_OFF=@LAST_SIGN_OFF,");
            }
            if (!string.IsNullOrEmpty(patInfo.Last_Sign_EpisodeNo))
            {
                str.Append(@"LAST_SIGN_EpisodeNo=@LAST_SIGN_EpisodeNo,");
            }
            str.Append(@"IsDefault=@IsDefault,");
            if (!string.IsNullOrEmpty(patInfo.IDCardUrlFront))
            {
                str.Append(@"IDCardUrlFront=@IDCardUrlFront,");
            }
            if (!string.IsNullOrEmpty(patInfo.IDCardUrlBack))
            {
                str.Append(@"IDCardUrlBack=@IDCardUrlBack,");
            }
            if (patInfo.CityId > 0)
            {
                str.Append(@"CityId=@CityId,");
            }
            if (!string.IsNullOrEmpty(patInfo.LocalAddress))
            {
                str.Append(@"LocalAddress=@LocalAddress,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyName))
            {
                str.Append(@"EmergencyName=@EmergencyName,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyPhone))
            {
                str.Append(@"EmergencyPhone=@EmergencyPhone,");
            }
            if (!string.IsNullOrEmpty(patInfo.EmergencyRelation))
            {
                str.Append(@"EmergencyRelation=@EmergencyRelation,");
            }
            if (patInfo.HowKnow > 0)
            {
                str.Append(@"HowKnow=@HowKnow,");
            }
            if (patInfo.PayType > 0)
            {
                str.Append(@"PayType=@PayType,");
            }

            str.Append(@"InsuranceCardUrl=@InsuranceCardUrl,");

            if (!string.IsNullOrEmpty(patInfo.Mrn))
            {
                str.Append(@"Mrn=@Mrn,");
            }
            if (patInfo.ContactWay > 0)
            {
                str.Append(@"ContactWay=@ContactWay,");
            }
            if (!string.IsNullOrEmpty(patInfo.ContactValue))
            {
                str.Append(@"ContactValue=@ContactValue,");
            }
            str.Append(@"IS_DELETED=@IS_DELETED");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patInfo.Pat_ID);
            parms.Add("@PAT_MRN", patInfo.Pat_MRN);
            parms.Add("@LAST_NAME", patInfo.Last_Name);
            parms.Add("@FIRST_NAME", patInfo.First_Name);
            parms.Add("@PAT_NAME", patInfo.Pat_Name);
            parms.Add("@BIRTHDAY", patInfo.Birthday);
            parms.Add("@GENDER", patInfo.Gender);
            parms.Add("@CARD_ID", patInfo.Card_ID);
            parms.Add("@CARD_TYPE", patInfo.Card_Type);
            parms.Add("@CardValidity", patInfo.CardValidity);
            parms.Add("@PHONE_NO", patInfo.Phone_NO);
            parms.Add("@PROVINCE", patInfo.Province);
            parms.Add("@CITY", patInfo.City);
            parms.Add("@DISTRICT", patInfo.District);
            parms.Add("@EMAIL", patInfo.Email);
            parms.Add("@NATIONALITY", patInfo.Nationality);
            parms.Add("@IS_DEAD", patInfo.Is_Dead);
            parms.Add("@IS_ACTIVE", patInfo.Is_Active);
            parms.Add("@PAT_SOURCE", patInfo.Pat_Source);
            parms.Add("@IS_DELETED", patInfo.Is_Deleted);
            parms.Add("@MRN_NO", patInfo.Mrn_NO);
            parms.Add("@PAT_MRN_NUMBER", patInfo.Pat_Mrn_Number);
            parms.Add("@ID_NUMBER", patInfo.Id_Number);
            parms.Add("@GUARDIAN", patInfo.Guardian);
            parms.Add("@GuardianPhone", patInfo.GuardianPhone);
            parms.Add("@Last_GUARDIAN", patInfo.Last_Guardian);
            parms.Add("@First_GUARDIAN", patInfo.First_Guardian);
            parms.Add("@DOCUMENT_TYPE", patInfo.Document_Type);
            parms.Add("@CERTIFICATE_NUMBER", patInfo.Certificate_Number);
            parms.Add("@LAST_SIGN_OFF", patInfo.Last_Sign_Off);
            parms.Add("@LAST_SIGN_EpisodeNo", patInfo.Last_Sign_EpisodeNo);
            parms.Add("@IsDefault", patInfo.IsDefault);
            parms.Add("@IDCardUrlFront", patInfo.IDCardUrlFront);
            parms.Add("@IDCardUrlBack", patInfo.IDCardUrlBack);
            parms.Add("@CityId", patInfo.CityId);
            parms.Add("@LocalAddress", patInfo.LocalAddress);
            parms.Add("@EmergencyName", patInfo.EmergencyName);
            parms.Add("@EmergencyPhone", patInfo.EmergencyPhone);
            parms.Add("@EmergencyRelation", patInfo.EmergencyRelation);
            parms.Add("@HowKnow", patInfo.HowKnow);
            parms.Add("@ContactWay", patInfo.ContactWay);
            parms.Add("@ContactValue", patInfo.ContactValue);
            parms.Add("@PayType", patInfo.PayType);
            parms.Add("@InsuranceCardUrl", patInfo.InsuranceCardUrl);
            parms.Add("@Mrn", patInfo.Mrn);
            parms.Add("@ID", patInfo.Id);
            var result = await ExecuteAsync(str.ToString(), parms);
            return result;
        }

        public int UpdatePubPatInfo(PatWithRelationShip patInfo)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Pub_Pat_Info set ");
            str.Append(@"  
                            LAST_NAME=@LastName,
                            FIRST_NAME=@FirstName,
                            PAT_NAME=@PatName,
                            CARD_TYPE=@CardType,
                            CARD_ID=@CardId,
                            ID_NUMBER=@IdNumber,
                            BIRTHDAY=@Birthday,
                            GENDER=@Gender,
                            PHONE_NO=@PhoneNo,
                            EMAIL=@EMAIL,
                            GUARDIAN=@Guardian,
                            Last_GUARDIAN=@LastGuardian,
                            First_GUARDIAN=@FistGuardian,
                            DOCUMENT_TYPE=@GuardianCardType,
                            CERTIFICATE_NUMBER=@GuardianIdNumber,
                            IsDefault=@IsDefault ");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();
            parms.Add("@LastName", patInfo.LastName);
            parms.Add("@FirstName", patInfo.FirstName);
            parms.Add("@PatName", patInfo.PatName);
            parms.Add("@CardType", patInfo.CardType);
            parms.Add("@CardId", patInfo.CardId);
            parms.Add("@IdNumber", patInfo.IdNumber);
            parms.Add("@Birthday", patInfo.Birthday);
            parms.Add("@Gender", patInfo.Gender);
            parms.Add("@PhoneNo", patInfo.PhoneNo);
            parms.Add("@EMAIL", patInfo.Email);
            parms.Add("@Guardian", patInfo.Guardian);
            parms.Add("@LastGuardian", patInfo.LastGuardian);
            parms.Add("@FistGuardian", patInfo.FistGuardian);
            parms.Add("@GuardianCardType", patInfo.GuardianCardType);
            parms.Add("@GuardianIdNumber", patInfo.GuardianIdNumber);
            parms.Add("@IsDefault", patInfo.IsDefault);
            parms.Add("@ID", patInfo.Id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public Pub_Pat_Info SelectByPatId(string id)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@patId", id);
            var selectSql = @"select * from pub_pat_info
                            where PAT_ID = @patId
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }
        public Pub_Pat_Info GetPatByCardId(string id)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@CardId", id);
            parms.Add("@CardIdEns", id.Encrypt());
            var selectSql = @"select * from pub_pat_info
                            where (CARD_ID = @CardId OR CARD_ID=@CardIdEns)
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }
        public Pub_Pat_Info GetPatByName(string fName, string lName, string phone)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@FIRST_NAME", fName);
            parms.Add("@LAST_NAME", lName);
            parms.Add("@phone_no", phone);
            parms.Add("@phone_noens", phone.Encrypt());
            var selectSql = @"select * from pub_pat_info where LAST_NAME = @LAST_NAME and FIRST_NAME=@FIRST_NAME and (phone_no=@phone_no OR phone_no=@phone_noens) and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }

        public Pub_Pat_Info SelectById(int id)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", id);
            var selectSql = @"select `ID`, `PAT_ID`, `PAT_MRN`, `LAST_NAME`, `FIRST_NAME`, `PAT_NAME`, `BIRTHDAY`, `GENDER`, `CARD_ID`, `CARD_TYPE`, `CardValidity`, `PHONE_NO`, `PROVINCE`, `CITY`, `DISTRICT`, `EMAIL`, `NATIONALITY`, `IS_DEAD`, `IS_ACTIVE`, `PAT_SOURCE`, `IS_DELETED`, `MRN_NO`, `PAT_MRN_NUMBER`, `ID_NUMBER`, `GUARDIAN`, `Last_GUARDIAN`, `First_GUARDIAN`, `GuardianPhone`, `DOCUMENT_TYPE`, `CERTIFICATE_NUMBER`, `CLINIC_CARD`, `CLINIC_CARDTYPE`, `LAST_SIGN_OFF`, `LAST_SIGN_EpisodeNo`, `LinKingOpenId`, `IsDefault`, `IS_PEDIATRICS_USER`, `Pat_Remark`, `CityId`, `LocalAddress`, `EmergencyName`, `EmergencyPhone`, `EmergencyRelation`, `HowKnow`, `ContactWay`, `ContactValue`, `PayType`, `InsuranceCardUrl`, `Mrn`, `IsReadSignOff`, `CreateTime` from pub_pat_info
                            where Id = @Id
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt(); ;
        }

        public List<Pub_Pat_Info> SelectByIds(List<int> ids)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", ids);
            var selectSql = @"select    `ID`,
	                                    `PAT_ID`,
	                                    `PAT_MRN`,
	                                    `LAST_NAME`,
	                                    `FIRST_NAME`,
	                                    `PAT_NAME`,
	                                    `BIRTHDAY`,
	                                    `GENDER`,
	                                    `CARD_ID`,
	                                    `CARD_TYPE`,
	                                    `PHONE_NO`,
	                                    `PROVINCE`,
	                                    `CITY`,
	                                    `DISTRICT`,
	                                    `EMAIL`,
	                                    `NATIONALITY`,
	                                    `IS_DEAD`,
	                                    `IS_ACTIVE`,
	                                    `PAT_SOURCE`,
	                                    `IS_DELETED`,
	                                    `MRN_NO`,
	                                    `PAT_MRN_NUMBER`,
	                                    `ID_NUMBER`,
	                                    `GUARDIAN`,
	                                    `Last_GUARDIAN`,
	                                    `First_GUARDIAN`,
	                                    `DOCUMENT_TYPE`,
	                                    `CERTIFICATE_NUMBER`,
	                                    `CLINIC_CARD`,
	                                    `CLINIC_CARDTYPE`,
	                                    `LAST_SIGN_OFF`,
	                                    `LAST_SIGN_EpisodeNo`,
	                                    `LinKingOpenId`,
	                                    `IsDefault`,
	                                    `IS_PEDIATRICS_USER`,
	                                    `Pat_Remark`,
	                                    `CityId`,
	                                    `LocalAddress`,
	                                    `EmergencyName`,
	                                    `EmergencyPhone`,
	                                    `EmergencyRelation`,
	                                    `HowKnow`,
	                                    `ContactWay`  from pub_pat_info
                                 where Id IN @Id
                                  and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result.ToList().DeEncrypt();
        }


        public PatWithRelationShip SelectPatById(int id)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", id);
            var selectSql = @"SELECT
	                            ID,
	                            PAT_ID AS PatId,
	                            PAT_MRN AS PatMrn,
	                            LAST_NAME AS LastName,
	                            PAT_NAME AS PatName,
	                            FIRST_NAME AS FirstName,
	                            BIRTHDAY,
	                            GENDER,
	                            CARD_ID AS CardId,
	                            CARD_TYPE AS CardType,
	                            PHONE_NO AS PhoneNo,
	                            PROVINCE,
	                            CITY,
	                            DISTRICT,
	                            EMAIL,
	                            NATIONALITY,
	                            IS_DEAD AS IsDead,
	                            IS_ACTIVE AS IsActive,
	                            MRN_NO AS MrnNo 
                            FROM
	                            pub_pat_info      
                              where Id = @Id ";
            var result = Query<PatWithRelationShip>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }

        public Pub_Pat_Info SelectByMrn(string mrn)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Mrn", mrn);
            var selectSql = @"select * from pub_pat_info
                            where PAT_MRN = @Mrn
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault()?.DeEncrypt();
        }

        public List<Pub_Pat_Info> GetPatByPIdAsync(string mrn)
        {
            var parms = new Dictionary<string, object>
            {
                { "@Mrn", mrn }
            };

            const string selectSql = @"select * from pub_pat_info
                            where PAT_MRN = @Mrn
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result.ToList().DeEncrypt();
        }

        /// <summary>
        /// 查询包括已删除的数据
        /// 为了兼容老数据……
        /// </summary>
        /// <param name="mrn"></param>
        /// <returns></returns>
        public Pub_Pat_Info SelectAllByMrn(string mrn)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Mrn", mrn);
            var selectSql = @"SELECT
                              	pat.* 
                              FROM
                              	pub_pat_info AS pat
                              	INNER JOIN pub_map_user_pat AS map ON pat.Id = map.PAT_ID 
                              WHERE
                              	map.IS_DELETED = TRUE 
                              	AND pat.Mrn = @Mrn 
                              ORDER BY
                              	map.UPDATE_TIME DESC 
                              	LIMIT 1";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault()?.DeEncrypt();
        }

        public List<Pub_Pat_Info> SelectPatsByMrn(List<string> mrns)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Mrn", mrns);
            var selectSql = @"select * from pub_pat_info
                            where PAT_MRN in @Mrn
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.ToList()?.DeEncrypt();
        }
        public Pub_Pat_Info SelectByLinKingOpenId(string openid)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@LinKingOpenId", openid);
            var selectSql = @"select * from pub_pat_info
                            where LinKingOpenId = @LinKingOpenId
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }

        public Pub_Pat_Info GetPatByCondition(string phone, string lastName, string firstName)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PHONE_NO", phone);
            parms.Add("@PHONE_NOEnc", phone.Encrypt());
            parms.Add("@LAST_NAME", lastName);
            parms.Add("@FIRST_NAME", firstName);
            var selectSql = @"select * from pub_pat_info
                            where (PHONE_NO = @PHONE_NO OR PHONE_NO = @PHONE_NOEnc) and LAST_NAME=@LAST_NAME and FIRST_NAME=@FIRST_NAME
                              and IS_DELETED = false";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.FirstOrDefault().DeEncrypt();
        }

        public async Task<List<Pub_Pat_Info>> GetPatsByConditionAsync(string phone, string lastName, string firstName, int gender, string birthday)
        {
            const string sql = @"SELECT
                                 	* 
                                 FROM
                                 	pub_pat_info 
                                 WHERE
                                 	( PHONE_NO = @PHONE_NO OR PHONE_NO = @PHONE_NOEnc ) 
                                 	AND LAST_NAME = @LAST_NAME 
                                 	AND FIRST_NAME = @FIRST_NAME 
                                 	AND GENDER = @GENDER 
                                 	AND BIRTHDAY = @BIRTHDAY 
                                 	AND IS_DELETED = FALSE";

            var parms = new Dictionary<string, object>
            {
                { "@PHONE_NO", phone },
                { "@PHONE_NOEnc", phone.Encrypt() },
                { "@LAST_NAME", lastName },
                { "@FIRST_NAME", firstName },
                { "@GENDER", gender },
                { "@BIRTHDAY", birthday }
            };

            var result = await QueryAsync<Pub_Pat_Info>(sql, parms);
            return result?.ToList().DeEncrypt();
        }

        public int UpdatePatByLinKing(string linkingopenid, int patid)
        {
            var sql = @"UPDATE pub_pat_info
                        SET LinKingOpenId = @LinKingOpenId
                        WHERE ID = @ID ";
            var parms = new Dictionary<string, object>();
            parms.Add("@ID", patid);
            parms.Add("@LinKingOpenId", linkingopenid);
            return Execute(sql, parms);
        }

        public Tencent_Group_Record IsExistGroup(int userId, int patId, int docId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PatId", patId);
            parms.Add("@DocId", docId);
            parms.Add("@UserId", userId);
            var selectSql = @"select * from tencent_group_record where PatId=@PatId and DocId=@DocId and UserId=@UserId and `Status` =1";
            var result = Query<Tencent_Group_Record>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public Tencent_Group_Record IsExistGroupByPat(int patId, int docId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PatId", patId);
            parms.Add("@DocId", docId);
            var selectSql = @"select * from tencent_group_record where PatId=@PatId and DocId=@DocId and `Status` =1";
            var result = Query<Tencent_Group_Record>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public List<Tencent_Group_Record> GetGroupsByPat(int patId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PatId", patId);
            var selectSql = @"select * from tencent_group_record where PatId=@PatId and `Status` =1";
            var result = Query<Tencent_Group_Record>(selectSql, parms);
            return result?.ToList();
        }

        public int DeleteGroupMember(int groupId)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update tencent_group_record set ");
            str.Append(@"`Status`=@Status");
            str.Append(@" where Id=@GroupId");
            var parms = new Dictionary<string, object>();
            parms.Add("@Status", 3);
            parms.Add("@Id", groupId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int GroupForbiddenUser(string groupId, bool isForbidden)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update tencent_group_record set ");
            str.Append(@"IsForbiddenSpeech=@IsForbiddenSpeech");
            str.Append(@" where GroupId=@GroupId");
            var parms = new Dictionary<string, object>();
            parms.Add("@IsForbiddenSpeech", isForbidden);
            parms.Add("@GroupId", groupId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public Pub_User_Info GetUserByPatId(int patId, string source = "sino")
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patId);
            var selectSql = @"select * from pub_user_info where id in(select USER_ID from pub_map_user_pat where PAT_ID=@PAT_ID  and IS_DELETED = false)  and IS_DELETED = false";
            if (source == "sino")
            {
                selectSql += " and REGISTRATION_SOURCE < 4";
            }
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public Pub_User_Info GetUserByPatIdForJob(int patId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patId);
            var selectSql = @"select * from pub_user_info where id in(select USER_ID from pub_map_user_pat where PAT_ID=@PAT_ID)";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public Pub_User_Info GetUserByPatIds(int patId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@PAT_ID", patId);
            var selectSql = @"select * from pub_user_info where id in(select USER_ID from pub_map_user_pat where PAT_ID = @PAT_ID )  and IS_DELETED = false";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public DocIMInfo GetImIdByDocId(int docId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@DOC_ID", docId);
            var selectSql = @"select IMID,CN_NAME AS NAMECN,EN_NAME AS NAMEEN from sys_user du inner join dic_doctor d on d.id=du.DOCID where DOCID =@DOC_ID and `status` = 1";
            var result = Query<DocIMInfo>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public List<PatWithRelationShip> SelectByUserWithRelationTime(int userId, string type)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@USER_ID", userId);
            var selectSql = @"select   t1.GUARDIAN AS Guardian,
							           t1.Last_GUARDIAN AS LastGuardian,
							           t1.First_GUARDIAN AS FistGuardian,
							           t1.DOCUMENT_TYPE AS GuardianCardType,
							           t1.CERTIFICATE_NUMBER AS GuardianIdNumber,
							           t1.IsDefault AS IsDefault,
                                       t1.ID,
                                       t1.PAT_ID as PATID,
                                       t1.ID_NUMBER as IdNumber,
                                       PAT_MRN as PatMrn,
                                       LAST_NAME as LastName,
                                       PAT_NAME as PatName,
                                       FIRST_NAME as FirstName,
                                       BIRTHDAY,
                                       GENDER,
                                       CARD_ID as CardId,
                                       CARD_TYPE as CardType,
                                       PHONE_NO as PhoneNo,
                                       PROVINCE,
                                       CITY,
                                       DISTRICT,
                                       EMAIL,
                                       NATIONALITY,
                                       IS_DEAD as IsDead,
                                       IS_ACTIVE as IsActive,
                                       t2.RELATION_SHIP as RelationShip,
                                       t1.MRN_NO as MrnNo,
                                       t2.Ties,
                                IF
                                	( t1.PAYTYPE IS NULL OR t1.EmergencyName IS NULL, 0, 1 ) AS IsPerfect,
                                IF
                                	( t1.GUARDIAN IS NULL OR t1.GuardianPhone IS NULL OR t1.CERTIFICATE_NUMBER IS NULL, 0, 1 ) AS IsPerfectGuardian ";
            if (type == "report")
            {
                selectSql += ",IsReadSignOff ";
            }
            selectSql += @" from pub_pat_info t1,
                                     pub_map_user_pat t2
                                where t1.ID = t2.PAT_ID
                                  and t2.USER_ID = @USER_ID
                                    and (t2.RELATION_SHIP=1 or t2.RELATION_SHIP=2)
                                  and t2.IS_DELETED = false
                                  and t1.IS_DELETED = false
                                  ORDER BY t2.CREATE_TIME DESC";
            var result = Query<PatWithRelationShip>(selectSql, parms);
            return result?.ToList().DeEncrypt();
        }

        public List<PatWithRelationShip> SelectByUserWithRelationByApp(int userId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@userId", userId);
            var selectSql = @"SELECT
                              	t1.ID,
                              	t1.PAT_ID AS PatId,
                              	PAT_MRN AS PatMrn,
                              	LAST_NAME AS LastName,
                              	PAT_NAME AS PatName,
                              	FIRST_NAME AS FirstName,
                              	BIRTHDAY,
                              	GENDER,
                              	CARD_ID AS CardId,
                              	CARD_TYPE AS CardType,
                              	PHONE_NO AS PhoneNo,
                              	PROVINCE,
                              	CITY,
                              	DISTRICT,
                              	EMAIL,
                              	NATIONALITY,
                              	IS_DEAD AS IsDead,
                              	IS_ACTIVE AS IsActive,
                              	t2.RELATION_SHIP AS RelationShip,
                              	MRN_NO AS MrnNo,
                              	t2.Ties,
                              	Last_GUARDIAN AS LastGuardian,
                              	First_GUARDIAN AS FistGuardian,
                              	GuardianPhone,
                              	DOCUMENT_TYPE AS GuardianCardType,
                              	CERTIFICATE_NUMBER AS GuardianIdNumber ,
                                IF
                                	( t1.PAYTYPE IS NULL OR t1.EmergencyName IS NULL, 0, 1 ) AS IsPerfect,
                                IF
                                	( t1.GUARDIAN IS NULL OR t1.GuardianPhone IS NULL OR t1.CERTIFICATE_NUMBER IS NULL, 0, 1 ) AS IsPerfectGuardian
                              FROM
                              	pub_pat_info t1,
                              	pub_map_user_pat t2 
                              WHERE
                              	t1.ID = t2.PAT_ID 
                                and (t2.RELATION_SHIP=1 or t2.RELATION_SHIP=2)
                              	AND t2.USER_ID = @userId 
                              	AND t2.IS_DELETED = FALSE 
                              ORDER BY
                              	t2.CREATE_TIME DESC";
            var result = Query<PatWithRelationShip>(selectSql, parms);
            return result?.ToList().DeEncrypt();
        }

        public List<Pub_Pat_Info> GetUserRelationship(int userId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@userId", userId);
            var selectSql = @"select    `ID`,
	                                    `PAT_ID`,
	                                    `PAT_MRN`,
	                                    `LAST_NAME`,
	                                    `FIRST_NAME`,
	                                    `PAT_NAME`,
	                                    `BIRTHDAY`,
	                                    `GENDER`,
	                                    `CARD_ID`,
	                                    `CARD_TYPE`,
	                                    `PHONE_NO`,
	                                    `PROVINCE`,
	                                    `CITY`,
	                                    `DISTRICT`,
	                                    `EMAIL`,
	                                    `NATIONALITY`,
	                                    `IS_DEAD`,
	                                    `IS_ACTIVE`,
	                                    `PAT_SOURCE`,
	                                    `IS_DELETED`,
	                                    `MRN_NO`,
	                                    `PAT_MRN_NUMBER`,
	                                    `ID_NUMBER`,
	                                    `GUARDIAN`,
	                                    `Last_GUARDIAN`,
	                                    `First_GUARDIAN`,
	                                    `DOCUMENT_TYPE`,
	                                    `CERTIFICATE_NUMBER`,
	                                    `CLINIC_CARD`,
	                                    `CLINIC_CARDTYPE`,
	                                    `LAST_SIGN_OFF`,
	                                    `LAST_SIGN_EpisodeNo`,
	                                    `LinKingOpenId`,
	                                    `IsDefault`,
	                                    `IS_PEDIATRICS_USER`,
	                                    `Pat_Remark`,
	                                    `CityId`,
	                                    `LocalAddress`,
	                                    `EmergencyName`,
	                                    `EmergencyPhone`,
	                                    `EmergencyRelation`,
	                                    `HowKnow`,
	                                    `ContactWay`,
                                        `PayType`
                            from pub_pat_info where id in (select PAT_ID from pub_map_user_pat where USER_ID=@userId and IS_DELETED = 0 AND (RELATION_SHIP = 1 or RELATION_SHIP = 2 ) )";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.ToList().DeEncrypt();
        }

        public List<Pub_Pat_Info> GetUserRelation(int userId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@userId", userId);
            var selectSql = @"select    `ID`,
	                                    `PAT_ID`,
	                                    `PAT_MRN`,
	                                    `LAST_NAME`,
	                                    `FIRST_NAME`,
	                                    `PAT_NAME`,
	                                    `BIRTHDAY`,
	                                    `GENDER`,
	                                    `CARD_ID`,
	                                    `CARD_TYPE`,
	                                    `PHONE_NO`,
	                                    `PROVINCE`,
	                                    `CITY`,
	                                    `DISTRICT`,
	                                    `EMAIL`,
	                                    `NATIONALITY`,
	                                    `IS_DEAD`,
	                                    `IS_ACTIVE`,
	                                    `PAT_SOURCE`,
	                                    `IS_DELETED`,
	                                    `MRN_NO`,
	                                    `PAT_MRN_NUMBER`,
	                                    `ID_NUMBER`,
	                                    `GUARDIAN`,
	                                    `Last_GUARDIAN`,
	                                    `First_GUARDIAN`,
	                                    `DOCUMENT_TYPE`,
	                                    `CERTIFICATE_NUMBER`,
	                                    `CLINIC_CARD`,
	                                    `CLINIC_CARDTYPE`,
	                                    `LAST_SIGN_OFF`,
	                                    `LAST_SIGN_EpisodeNo`,
	                                    `LinKingOpenId`,
	                                    `IsDefault`,
	                                    `IS_PEDIATRICS_USER`,
	                                    `Pat_Remark`,
	                                    `CityId`,
	                                    `LocalAddress`,
	                                    `EmergencyName`,
	                                    `EmergencyPhone`,
	                                    `EmergencyRelation`,
	                                    `HowKnow`,
	                                    `ContactWay`,
                                        `PayType`
                            from pub_pat_info where id in (select PAT_ID from pub_map_user_pat where USER_ID=@userId and IS_DELETED = 0 )";
            var result = Query<Pub_Pat_Info>(selectSql, parms);
            return result?.ToList().DeEncrypt();
        }

        public List<PubPatInfoMapUser> GetPubPatInfoList(int userID)
        {
            var selectSql = new StringBuilder();
            selectSql.Append(@"SELECT
                                    t2.USER_ID AS UserID,
	                                t1.ID,
	                                t1.PAT_ID AS Pat_ID,
	                                t1.PAT_MRN AS Pat_MRN,
	                                t1.PAT_NAME AS Pat_Name,
	                                t1.LAST_NAME AS Last_Name,
	                                t1.FIRST_NAME AS First_Name,
	                                t1.BIRTHDAY AS Birthday,
	                                t1.GENDER AS Gender,
	                                t1.ID_NUMBER AS Id_Number,
	                                t1.CARD_TYPE AS Card_Type,
	                                t1.CARD_ID AS Card_ID,
	                                t1.PHONE_NO AS Phone_NO,
	                                t1.GUARDIAN AS Guardian,
	                                t1.Last_GUARDIAN AS Last_Guardian,
	                                t1.First_GUARDIAN AS First_Guardian,
	                                t1.DOCUMENT_TYPE AS Document_Type,
	                                t1.CERTIFICATE_NUMBER AS Certificate_Number
                                FROM
	                                pub_pat_info t1
	                                JOIN pub_map_user_pat t2 ON t1.ID = t2.PAT_ID
	                                LEFT JOIN pub_insurance t3 ON t3.PatId = t1.ID
                                WHERE t1.IS_DELETED = false AND t2.USER_ID = @UserID ");
            return Query<PubPatInfoMapUser>(selectSql.ToString(), new { UserID = userID }).ToList().DeEncrypt();
        }

        public int UpdatePatClinicCard(int id, string cardNo, string cardType)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Pub_Pat_Info set ");
            str.Append(@"CLINIC_CARD=@CLINIC_CARD,
                            CLINIC_CARDTYPE=@CLINIC_CARDTYPE ");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();

            parms.Add("@CLINIC_CARD", cardNo);
            parms.Add("@CLINIC_CARDTYPE", cardType);
            parms.Add("@ID", id);
            var result = Execute(str.ToString(), parms);
            return result;
        }



        public IEnumerable<MyAppointment> GetOutMyAppointment(int userId, int type, int pat, DateTime begin, DateTime end)
        {
            int status = type;
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT
                                    a.ID,-- 线下预约数据
	                                a.APT_TIME AS aptTime,
	                                a.`STATUS` AS status,
	                                a.REMARK AS remark,
                                    a.CREATE_TIME AS CreateTime,

	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                f.CN_NAME AS hosCNName,
	                                f.EN_NAME AS hosENName,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.APT_PROJ AS aptServId,-- 服务
	                                b.CN_NAME AS servCNName,
	                                b.EN_NAME AS servENName,
                                    
                                    '3' AS MyAppointmentType
	
                                FROM
	                                out_apt_info a
	                                LEFT JOIN dic_map_dept_serv b ON a.APT_PROJ = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
	                                LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
                                WHERE ");
            if (pat != 0)
            {
                selectSql.Append(" a.PAT_ID=@PatId ");
            }
            else
            {
                selectSql.Append(" a.PAT_ID IN (SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @Userid) ");
            }
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" and a.APT_TIME>@Begin AND a.APT_TIME<@End ");
            }
            if (status == 1)
            {
                selectSql.Append(" AND  (`STATUS`=0 or STATUS=1) AND `STATUS` != 2  ");
            }
            else if (status == 4)
            {
                selectSql.Append(" AND (APT_TIME>@AptTime or `STATUS`=@Status) AND `STATUS` != 2 ");
            }
            else if (status == 5)
            {
                selectSql.Append(" AND APT_TIME<@AptTime ");
            }
            var result = Query<MyAppointment>(selectSql.ToString(), new { Userid = userId, Status = status, AptTime = DateTime.Now.AddHours(1), PatId = pat, Begin = begin, End = end });
            return result;
        }

        public IEnumerable<MyAppointment> GetOutMyAppointmentForPat(List<int> patids)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT
                                    a.ID,-- 线下预约数据
	                                a.APT_TIME AS aptTime,
	                                a.`STATUS` AS status,
	                                a.REMARK AS remark,
                                    a.CREATE_TIME AS CreateTime,
                                    a.APT_USRN AS Usrn,
                                    a.SOURCE_TYPE AS SourceType,
                                    
	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
                                    e.PAT_MRN AS PID,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                f.CN_NAME AS hosCNName,
	                                f.EN_NAME AS hosENName,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.APT_PROJ AS aptServId,-- 服务
	                                b.CN_NAME AS servCNName,
	                                b.EN_NAME AS servENName,
                                    
                                    '3' AS MyAppointmentType
	
                                FROM
	                                out_apt_info a
	                                LEFT JOIN dic_map_dept_serv b ON a.APT_PROJ = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
	                                LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
                                WHERE  a.PAT_ID IN @PatIds ");
            var result = Query<MyAppointment>(selectSql.ToString(), new { PatIds = patids });
            return result;
        }

        public IEnumerable<MyAppointment> GetOutMyAppointmentForUnconfirmed(List<int> patids, DateTime begin, DateTime end)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT
                                    a.ID,-- 线下预约数据
	                                a.APT_TIME AS aptTime,
	                                '1' AS status,
	                                a.REMARK AS remark,
                                    a.CREATE_TIME AS CreateTime,
                                    a.APT_USRN AS Usrn,
                                    a.SOURCE_TYPE AS SourceType,

	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
                                    e.PAT_MRN AS PID,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                f.CN_NAME AS hosCNName,
	                                f.EN_NAME AS hosENName,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.APT_PROJ AS aptServId,-- 服务
	                                b.CN_NAME AS servCNName,
	                                b.EN_NAME AS servENName,
                                    
                                    '3' AS MyAppointmentType
	
                                FROM
	                                out_apt_info a
	                                LEFT JOIN dic_map_dept_serv b ON a.APT_PROJ = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
	                                LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
                                WHERE  a.PAT_ID IN @PatIds AND (a.`STATUS` = 0 or a.`STATUS` = 1)  ");
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" and a.APT_TIME>@Begin AND a.APT_TIME<@End ");
            }
            var result = Query<MyAppointment>(selectSql.ToString(), new { PatIds = patids, Begin = begin, End = end });
            return result;
        }

        public MyAppointmentDetail GetOutMyAppointmentDetail(int Id)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT
                                    a.ID,-- 线下预约数据
	                                a.APT_TIME AS aptTime,
	                                a.`STATUS` AS status,
	                                a.REMARK AS remark,
                                    a.CREATE_TIME AS CreateTime,

	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                f.CN_NAME AS hosCNName,
	                                f.EN_NAME AS hosENName,
                                    f.CN_SMS_ADDR AS hosCNAddr,
                                    f.EN_SMS_ADDR AS hosENAddr,
                                    f.CN_MOBILE AS hosCNPhone,
                                    f.EN_MOBILE AS hosENPhone,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.APT_PROJ AS aptServId,-- 服务
	                                b.CN_NAME AS servCNName,
	                                b.EN_NAME AS servENName,
                                    
                                    '3' AS MyAppointmentType
	
                                FROM
	                                out_apt_info a
	                                LEFT JOIN dic_map_dept_serv b ON a.APT_PROJ = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
	                                LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
                                WHERE a.ID = @Id");
            var result = Query<MyAppointmentDetail>(selectSql.ToString(), new { Id = Id }).FirstOrDefault();
            return result;
        }


        public IEnumerable<MyAppointment> GetonlineMyAppointment(int type, List<int> pat, DateTime begin, DateTime end, bool isInsuranceUser)
        {
            if (pat.Count() <= 0)
            {
                return new List<MyAppointment>();
            }
            int status = type;
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 线上
                                        SELECT       											
											    a.Id,-- 线上预约数据
											    a.AptTime AS aptTime,
											    a.`Status`,
                                                a.`LinKingAptStatus`,
											    g.`OrderStatus` AS orderStatus,
											    a.Remark AS remark,
                                                a.CreateTime AS CreateTime,
                                                g.OrderNo,
                                                tg.GroupId,

											    a.PatId AS patId,-- 患者数据
											    e.PAT_NAME AS patName,

											    a.HosId AS hosId,-- 诊所
											    d.CN_NAME AS hosCNName,
											    d.EN_NAME AS hosENName,

											    a.DeptId AS deptId,-- 科室
											    c.CN_NAME AS deptCNName,
											    c.EN_NAME AS deptENName,

											    a.DocId AS docId,-- 医生
											    d.CN_NAME AS docCNName,
											    d.EN_NAME AS docENName,
											    d.LIST_IMAGE AS docImage,

											    a.AptProj AS aptServId,-- 服务
											    CASE a.AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servCNName',
											    CASE a.AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servENName',
												
										        CASE a.AptType
											    WHEN '1' THEN'1'
											    WHEN '2' THEN'2'
											    ELSE '5'
								    	    END 'MyAppointmentType',
													
												oc.ID AS CommentId,
                                                a.ApplyUserId
                                        FROM online_apt_info a
                                        INNER JOIN online_order g ON a.ID = g.AptId
                                        LEFT JOIN tencent_group_record tg ON tg.OrderNo = g.OrderNo and tg.userid = a.ApplyUserId
                                        LEFT JOIN dic_dept c ON a.DeptId = c.ID
                                        LEFT JOIN dic_doctor d ON a.DocId = d.ID
                                        LEFT JOIN pub_pat_info e ON a.PatId = e.ID
                                        LEFT JOIN dic_hos f ON a.HosId = f.ID
                                        LEFT JOIN online_order_comment oc ON oc.OrderNo = g.OrderNo
                    WHERE g.IsInsuranceUser=@IsInsuranceUser ");
            //如果是保险用户获取预约列表，那么只拉取订单状态为10和20的，保险用户的数据
            //if (isInsuranceUser)
            //{
            //    selectSql.Append(" AND g.OrderStatus in (9,10,12,20) ");
            //}
            //if (pat != 0)
            //{
            selectSql.Append(" AND a.PatId IN @PatId ");
            //}
            //else
            //{
            //    selectSql.Append(" AND a.PatId IN (SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @Userid) ");
            //}
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" and a.AptTime>@Begin and a.AptTime <@End  ");
            }
            if (status != -1)
            {
                selectSql.Append(" AND (a.Status=@Status ");
            }
            if (status == 4)
            {
                selectSql.Append(" OR a.Status=2 OR a.Status=6 ");
                if (!isInsuranceUser)
                {
                    selectSql.Append(" OR a.Status=1 ");
                }
            }
            if (status == 1 && isInsuranceUser)
            {
                selectSql.Append(" OR a.Status=0 OR a.Status=1 ");

            }
            if (status != -1)
            {
                selectSql.Append(" ) ");
            }
            selectSql.Append(@"AND (g.AptType=1 OR g.AptType=2) ");
            var result = Query<MyAppointment>(selectSql.ToString(), new { IsInsuranceUser = isInsuranceUser, Status = status, PatId = pat, Begin = begin, End = end });
            return result;
        }

        public List<MyAppointment> GetCignaAppointment(int userId, int type, int pat, DateTime begin, DateTime end)
        {
            int status = type;
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT  a.Id,-- 线上预约数据
											    a.AptTime AS aptTime,
											    a.`Status`,
                                                a.`LinKingAptStatus`,
											    o.`OrderStatus` AS orderStatus,
											    a.Remark AS remark,
                                                a.CreateTime AS CreateTime,
                                                o.OrderNo,
                                                tg.GroupId,

											    a.PatId AS patId,-- 患者数据
											    e.PAT_NAME AS patName,

											    a.HosId AS hosId,-- 诊所
											    d.CN_NAME AS hosCNName,
											    d.EN_NAME AS hosENName,

											    a.DeptId AS deptId,-- 科室
											    c.CN_NAME AS deptCNName,
											    c.EN_NAME AS deptENName,

											    a.DocId AS docId,-- 医生
											    d.CN_NAME AS docCNName,
											    d.EN_NAME AS docENName,
											    d.LIST_IMAGE AS docImage,

											    a.AptProj AS aptServId,-- 服务
											    CASE a.AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servCNName',
											    CASE a.AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servENName',
												
										        CASE a.AptType
											    WHEN '1' THEN'1'
											    WHEN '2' THEN'2'
											    ELSE '5'
								    	    END 'MyAppointmentType',
													
												oc.ID AS CommentId
                                        FROM online_apt_info a
                                        INNER JOIN online_order o ON a.ID = o.AptId
                                        LEFT JOIN tencent_group_record tg ON tg.OrderNo = o.OrderNo
                                        LEFT JOIN dic_dept c ON a.DeptId = c.ID
                                        LEFT JOIN dic_doctor d ON a.DocId = d.ID
                                        LEFT JOIN pub_pat_info e ON a.PatId = e.ID
                                        LEFT JOIN dic_hos f ON a.HosId = f.ID
                                        LEFT JOIN online_order_comment oc ON oc.OrderNo = o.OrderNo
                    WHERE o.IsInsuranceUser=1 AND o.AptType=2 ");

            if (pat != 0)
            {
                selectSql.Append(" AND a.PatId=@PatId ");
            }
            else
            {
                selectSql.Append(" AND a.PatId IN (SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @Userid) ");
            }
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" and a.AptTime>@Begin and a.AptTime <@End  ");
            }
            //1全部，2即将就诊(医助待确认, 已确认) 3待确认(保险待审核, 保险预约审核)，4已完成(就诊中, 就诊结束)
            if (status == 2)
            {
                selectSql.Append(" and a.`Status` in (1,2) and o.OrderStatus =10  ");
            }
            if (status == 3)
            {
                selectSql.Append(" and a.`Status` =0 and o.OrderStatus in (9,12)  ");
            }
            if (status == 4)
            {
                selectSql.Append(" and a.`Status` in (5,6) ");
            }
            var result = Query<MyAppointment>(selectSql.ToString(), new { Userid = userId, Status = status, PatId = pat, Begin = begin, End = end });
            return result?.ToList();
        }

        public MyAppointmentDetail GetonlineMyAppointmentDetail(int Id)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 线上
                                        SELECT       											
											    a.Id,-- 线上预约数据
											    a.AptTime AS aptTime,
											    a.`Status` AS status,
											    a.Remark AS remark,
                                                a.CreateTime AS CreateTime,

											    a.PatId AS patId,-- 患者数据
											    e.PAT_NAME AS patName,

											    a.HosId AS hosId,-- 诊所
											    f.CN_NAME AS hosCNName,
											    f.EN_NAME AS hosENName,
                                                f.CN_SMS_ADDR AS hosCNAddr,
                                                f.EN_SMS_ADDR AS hosENAddr,
                                                f.CN_MOBILE AS hosCNPhone,
                                                f.EN_MOBILE AS hosENPhone,

											    a.DeptId AS deptId,-- 科室
											    c.CN_NAME AS deptCNName,
											    c.EN_NAME AS deptENName,

											    a.DocId AS docId,-- 医生
											    d.CN_NAME AS docCNName,
											    d.EN_NAME AS docENName,
											    d.LIST_IMAGE AS docImage,

											    a.AptProj AS aptServId,-- 服务
											    CASE AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servCNName',
											    CASE AptType
											    WHEN '1' THEN'视频问诊'
											    WHEN '2' THEN'复诊开药'
											    ELSE ''
								    	        END 'servENName',
												
										        CASE AptType
											    WHEN '1' THEN'1'
											    WHEN '2' THEN'2'
											    ELSE '5'
								    	    END 'MyAppointmentType'
                                        FROM online_apt_info a
                                        LEFT JOIN dic_dept c ON a.DeptId = c.ID
                                        LEFT JOIN dic_doctor d ON a.DocId = d.ID
                                        LEFT JOIN pub_pat_info e ON a.PatId = e.ID
                                        LEFT JOIN dic_hos f ON a.HosId = f.ID
                                  WHERE a.ID = @Id");
            var result = Query<MyAppointmentDetail>(selectSql.ToString(), new { Id = Id }).FirstOrDefault();
            return result;
        }


        public IEnumerable<MyAppointment> GetVaccineMyAppointment(int userId, int type, int pat, DateTime begin, DateTime end)
        {
            int status = type;
            switch (type)
            {
                //即将就诊
                case 4:
                    status = 1;
                    break;
                //待确认
                case 1:
                    status = 3;
                    break;
            }
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 疫苗
                             SELECT
                                    a.ID,-- 疫苗数据
	                                a.APT_TIME AS aptTime,
	                                a.`STATUS` AS status,
	                                a.REMAKE AS remark,
                                    a.CREATE_TIME AS CreateTime,

	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                d.CN_NAME AS hosCNName,
	                                d.EN_NAME AS hosENName,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.VACCINE_ID AS aptServId,-- 服务
	                                b.VACCINE_CN_NAME AS servCNName,
	                                b.VACCINE_EN_NAME AS servENName,
                                    
                                    '4' AS MyAppointmentType
	
                                FROM
	                                Out_Vaccine_Appt a
	                                LEFT JOIN dic_vaccine b ON a.VACCINE_ID = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
																	LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
								WHERE ");
            if (pat != 0)
            {
                selectSql.Append(" a.PAT_ID=@PatId ");
            }
            else
            {
                selectSql.Append(" a.PAT_ID IN (SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @Userid and IS_DELETED = 0) ");
            }
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" AND a.APT_TIME>@Begin AND a.APT_TIME<@End ");
            }
            if (status != -1)
            {
                selectSql.Append(" AND a.STATUS=@Status ");
            }
            var result = Query<MyAppointment>(selectSql.ToString(), new { Userid = userId, Status = status, PatId = pat, Begin = begin, End = end });
            return result;
        }
        public MyAppointmentDetail GetVaccineMyAppointmentDetail(int Id)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 疫苗
                             SELECT
                                    a.ID,-- 疫苗数据
	                                a.APT_TIME AS aptTime,
	                                a.`STATUS` AS status,
	                                a.REMAKE AS remark,
                                    a.CREATE_TIME AS CreateTime,

	                                a.PAT_ID AS patId,-- 患者数据
	                                e.PAT_NAME AS patName,
	
	                                a.HOS_ID AS hosId,-- 诊所
	                                f.CN_NAME AS hosCNName,
	                                f.EN_NAME AS hosENName,
                                    f.CN_SMS_ADDR AS hosCNAddr,
                                    f.EN_SMS_ADDR AS hosENAddr,
                                    f.CN_MOBILE AS hosCNPhone,
                                    f.EN_MOBILE AS hosENPhone,
	
	                                a.DEPT_ID AS deptId,-- 科室
	                                c.CN_NAME AS deptCNName,
	                                c.EN_NAME AS deptENName,
	
	                                a.DOC_ID AS docId,-- 医生
	                                d.CN_NAME AS docCNName,
	                                d.EN_NAME AS docENName,
	                                d.LIST_IMAGE AS docImage,
	
	                                a.VACCINE_ID AS aptServId,-- 服务
	                                b.VACCINE_CN_NAME AS servCNName,
	                                b.VACCINE_EN_NAME AS servENName,
                                    
                                    '4' AS MyAppointmentType
	
                                FROM
	                                Out_Vaccine_Appt a
	                                LEFT JOIN dic_vaccine b ON a.VACCINE_ID = b.ID
	                                LEFT JOIN dic_dept c ON a.DEPT_ID = c.ID
	                                LEFT JOIN dic_doctor d ON a.DOC_ID = d.ID
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
									LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
                                  WHERE a.ID = @Id");
            var result = Query<MyAppointmentDetail>(selectSql.ToString(), new { Id = Id }).FirstOrDefault();
            return result;
        }


        public IEnumerable<MyAppointment> GetNucleicAcidMyAppointment(int userId, int type, int pat, DateTime begin, DateTime end)
        {
            int status = type;
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 核酸
                             SELECT
                                a.ID,-- 核酸数据
	                            a.APT_TIME AS aptTime,
	                            a.`STATUS` AS status,
	                            a.REMARK AS remark,

	                            a.PAT_ID AS patId,-- 患者数据
	                            e.PAT_NAME AS patName,
	
	                            a.HOS_ID AS hosId,-- 诊所
	                            f.CN_NAME AS hosCNName,
	                            f.EN_NAME AS hosENName,
                                    
                                '0' AS MyAppointmentType
	
                                FROM
	                                out_na_apt_info a
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
									LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
							WHERE ");
            if (pat != 0)
            {
                selectSql.Append(" a.PAT_ID=@PatId ");
            }
            else
            {
                selectSql.Append(" a.PAT_ID IN (SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @Userid and IS_DELETED = 0) ");
            }
            if (begin != DateTime.MinValue)
            {
                selectSql.Append(" AND a.APT_TIME>@Begin AND a.APT_TIME<@End ");
            }
            if (status != -1)
            {
                selectSql.Append(" AND a.INNER_STATUS=@Status ");
            }
            if (status == 5)
            {
                selectSql.Append(" AND a.INNER_STATUS=4 AND APT_TIME<@AptTime ");
            }
            var result = Query<MyAppointment>(selectSql.ToString(), new { Userid = userId, Status = status, AptTime = DateTime.Now.AddHours(1), PatId = pat, Begin = begin, End = end });
            return result;
        }
        public MyAppointmentDetail GetNucleicAcidMyAppointmentDetail(int Id)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"-- 核酸
                             SELECT
                                a.ID,-- 核酸数据
	                            a.APT_TIME AS aptTime,
	                            a.`STATUS` AS status,
	                            a.REMARK AS remark,

	                            a.PAT_ID AS patId,-- 患者数据
	                            e.PAT_NAME AS patName,
	
	                            a.HOS_ID AS hosId,-- 诊所
	                            f.CN_NAME AS hosCNName,
	                            f.EN_NAME AS hosENName,
                                f.CN_SMS_ADDR AS hosCNAddr,
                                f.EN_SMS_ADDR AS hosENAddr,
                                f.CN_MOBILE AS hosCNPhone,
                                f.EN_MOBILE AS hosENPhone,
                                    
                                '0' AS MyAppointmentType
	
                                FROM
	                                out_na_apt_info a
	                                LEFT JOIN pub_pat_info e ON a.PAT_ID = e.ID
									LEFT JOIN dic_hos f ON a.HOS_ID = f.ID
							WHERE	a.ID=@Id ");
            var result = Query<MyAppointmentDetail>(selectSql.ToString(), new { Id = Id }).FirstOrDefault();
            return result;
        }

        public int CancelPatDefult(int userId)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update pub_pat_info set isdefault=0 where ID in (select PAT_ID from pub_map_user_pat where USER_ID = @USER_ID)");

            var parms = new Dictionary<string, object>();

            parms.Add("@USER_ID", userId);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public List<Pub_User_Info> GetAptByCondition()
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"select DISTINCT d.* from out_apt_info a
                                    join pub_pat_info b on b.ID = a.PAT_ID and b.IS_DELETED = 0
                                    join pub_map_user_pat c on c.PAT_ID = b.ID and c.IS_DELETED = 0
                                    join pub_user_info d on d.ID = c.USER_ID and c.IS_DELETED =0 and d.OPEN_ID is not null and d.PHONE !='18616555857'
                                    where a.DEPT_ID = 1055 and INNER_STATUS !=2";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.ToList();
        }

        public int PatInsuranceComform(string uId, bool isAgree)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"update pub_user_info set
                            Is_Insurance_Comform=@Is_Insurance_Comform
                            where U_ID=@U_ID
                            ");

            parms.Add("@Is_Insurance_Comform", isAgree);
            parms.Add("@U_ID", uId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int InsertOutVaccineApptFlow(Out_Vaccine_Appt_Flow model)
        {
            var sql = @" INSERT INTO `out_vaccine_appt_flow`(`REQUEST_PARAM`, `RESOUCE_TYPE`, `CREATE_USER`, `CREATE_TIME`, `STATUS`) VALUES (@REQUEST_PARAM, @RESOUCE_TYPE, @CREATE_USER, @CREATE_TIME, @STATUS) ";
            return Insert(sql, model);
        }

        public int InsertOutVaccineAppt(Out_Vaccine_Appt model)
        {

            var sql = @" INSERT INTO `out_vaccine_appt`(`FLOW_ID`, `PAT_ID`, `USER_ID`, `VACCINE_ID`, `PAY_TYPE`, `IS_TREATMENT`, `INSURANCE_ID`, `INSURANCE_NO`, `PAY_IMAGE`, `HPV_TYPE`, `HPT_PIN`, `ORIGIN`, `STATUS`, `MATCH_CODE`, `APT_TIME`, `HOS_ID`, `DEPT_ID`, `DOC_ID`, `REMAKE`, `CREATE_USER`, `CREATE_TIME`, `UPDATE_USER`, `UPDATE_TIME`, `LANGUAGE`,`NewVaccineType`,`QueueNumber`) 
VALUES ( @FLOW_ID, @PAT_ID, @USER_ID, @VACCINE_ID, @PAY_TYPE, @IS_TREATMENT, @INSURANCE_ID, @INSURANCE_NO, @PAY_IMAGE, @HPV_TYPE, @HPT_PIN, @ORIGIN, @STATUS, @MATCH_CODE, @APT_TIME, @HOS_ID, @DEPT_ID, @DOC_ID, @REMAKE, @CREATE_USER, @CREATE_TIME, @UPDATE_USER, @UPDATE_TIME, @LANGUAGE, @NewVaccineType, @QueueNumber); ";
            return Execute(sql, model);
        }

        public int UpdateOutVaccineApptStauts(int flowid)
        {
            var sql = @" Update `out_vaccine_appt` SET `STATUS`=@STATUS,`UPDATE_TIME`=@UpdateTime  WHERE FLOW_ID = @FLOW_ID ";
            return Execute(sql, new { STATUS = 2, UpdateTime = DateTime.Now, FLOW_ID = flowid });
        }

        public int UpdateOutVaccineApptStautsForId(List<int> ids, int status)
        {
            var sql = @" Update `out_vaccine_appt` SET `STATUS`=@STATUS,`UPDATE_TIME`=@UpdateTime  WHERE ID IN @Ids ";
            return Execute(sql, new { STATUS = status, UpdateTime = DateTime.Now, Ids = ids });
        }

        public int UpdateOutVaccineMapCall(List<int> ids)
        {
            var sql = @" Update out_vaccine_map_call Set IsDelete = True Where Id IN @Ids ";
            return Execute(sql, new { Ids = ids });
        }

        public List<VaccineApptForUser> GetOutVaccineApptList(List<int> ids, int status)
        {
            var sql = @" SELECT g.*,(SELECT COUNT(1) FROM out_vaccine_appt a
				INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID WHERE ( a.NewVaccineType = 1) 
				AND a.VACCINE_ID = 1 
					AND a.`STATUS` = 4  AND a.QueueNumber< g.num )AS Number  FROM (	
                                    SELECT
                                            a.ORIGIN AS Origin,
											a.QueueNumber AS Num,
	                                        a.Id,
                                            a.`STATUS`,
                                            a.Apt_time as AptTime,
                                            a.type,
	                                        b.ID AS FlowId,
	                                        a.PAT_ID AS PatId,
	                                        a.USER_ID AS UserId,
	                                        a.REMAKE AS Remake,
	                                        a.CREATE_TIME AS CreateTime,
	                                        c.PAT_NAME AS PatName,
	                                        c.GENDER AS Gender,
                                            i.INNER_STATUS as InnerStatus
                                        FROM
	                                        out_vaccine_appt a
	                                        INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID
	                                        LEFT JOIN pub_pat_info c ON a.PAT_ID = c.ID 
                                            LEFT JOIN out_apt_info i on a.ID = i.APT_ID
                                        WHERE
	                                        ( a.NewVaccineType = 1) 
	                                        AND a.VACCINE_ID = 1";
            if (status == 4)
            {//全部
                sql += @" AND(a.`STATUS` != 1 AND a.`STATUS` != 3 AND a.`STATUS` != 10) ";
            }
            else if (status == 3)
            {//排队中
                sql += @" AND a.`STATUS` = 4 ";
            }
            else if (status == 2)
            {//待预约
                sql += @" AND a.`STATUS` = 5 ";
            }
            else if (status == 1)
            {//带接种
                sql += @" AND a.`STATUS` = 8 ";
            }

            sql += @" AND a.PAT_ID IN @Ids  ORDER BY a.UPDATE_TIME DESC  ) g";
            return Query<VaccineApptForUser>(sql, new { Ids = ids }).ToList();
        }

        public VaccineApptForUser GetOutVaccineApptForId(int id)
        {
            var sql = @" SELECT g.*,(SELECT COUNT(1) FROM out_vaccine_appt a
				INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID WHERE ( a.NewVaccineType = 1) 
				AND a.VACCINE_ID = 1 
					AND a.`STATUS` = 4  AND a.QueueNumber< g.num )AS Number  FROM (	
                                    SELECT
                                            a.ORIGIN AS Origin,
											a.QueueNumber AS Num,
	                                        a.Id,
                                            a.`STATUS`,
                                            a.Apt_time as AptTime,
                                            a.type,
	                                        b.ID AS FlowId,
	                                        a.PAT_ID AS PatId,
	                                        a.USER_ID AS UserId,
	                                        a.REMAKE AS Remake,
	                                        a.CREATE_TIME AS CreateTime,
	                                        c.PAT_NAME AS PatName,
	                                        c.GENDER AS Gender,
                                            i.INNER_STATUS as InnerStatus
                                        FROM
	                                        out_vaccine_appt a
	                                        INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID
	                                        LEFT JOIN pub_pat_info c ON a.PAT_ID = c.ID 
                                            LEFT JOIN out_apt_info i on a.ID = i.APT_ID
                                        WHERE
	                                        ( a.NewVaccineType = 1) 
	                                        AND a.VACCINE_ID = 1 
                                            AND (a.`STATUS` != 1 AND a.`STATUS` != 3)  
                                            AND a.Id = @Id ) g";
            return Query<VaccineApptForUser>(sql, new { Id = id }).FirstOrDefault();
        }

        public List<VaccineApptForUser> ApptForUser(List<int> ids, int language = 1)
        {
            var sql = @" SELECT
                              a.ID,";
            if (language == 1)
            {
                sql += @"       d.CN_ABBREVIATED_ADDR AS HosName,
	                            d.CN_SMS_ADDR AS Addr,
	                            d.CN_MOBILE AS HosPhone,
                                g.VACCINE_CN_NAME AS VaccineName,
                                c.VaccineBrand, ";
            }
            else
            {
                sql += @"       d.EN_ABBREVIATED_ADDR AS HosName,
	                            d.EN_SMS_ADDR AS Addr,
	                            d.EN_MOBILE AS HosPhone,
                                g.VACCINE_EN_NAME AS VaccineName,
                                c.VaccineBrandEn AS VaccineBrand, ";
            }
            sql += @"           f.APT_TIME AS AptTime,
	                            c.PatType,
                                b.CreateTime AS CallTime     
                            FROM
	                            out_vaccine_appt a
	                            INNER JOIN out_vaccine_map_call b ON a.id = b.AppVaccineId 
	                            INNER JOIN out_vaccine_appt_call c ON c.id = b.CallId
	                            LEFT JOIN out_apt_info f ON f.APT_ID = a.ID
	                            LEFT JOIN dic_hos d ON d.ID = c.HosId
                                LEFT JOIN dic_vaccine g ON g.ID = c.VaccineId 
                            WHERE a.ID IN @Ids ";
            return Query<VaccineApptForUser>(sql, new { Ids = ids }).ToList();
        }

        public List<VaccineApptForUser> CompanyApptForUser(List<int> ids, int language = 1)
        {
            var sql = @" SELECT
                              a.ID,";
            if (language == 1)
            {
                sql += @"       d.CN_ABBREVIATED_ADDR AS HosName,
	                            d.CN_SMS_ADDR AS Addr,
	                            d.CN_MOBILE AS HosPhone,
                                g.VACCINE_CN_NAME AS VaccineName,
                                o.VaccineBrandCN AS VaccineBrand";
            }
            else
            {
                sql += @"       d.EN_ABBREVIATED_ADDR AS HosName,
	                            d.EN_SMS_ADDR AS Addr,
	                            d.EN_MOBILE AS HosPhone,
                                g.VACCINE_EN_NAME AS VaccineName,
                                o.VaccineBrandEN AS VaccineBrand ";
            }
            sql += @"           FROM
	                            out_vaccine_appt a
	                            LEFT JOIN out_apt_info f ON f.APT_ID = a.ID
	                            LEFT JOIN dic_hos d ON d.ID = a.Hos_Id
                                LEFT JOIN dic_vaccine g ON g.ID = a.VACCINE_ID
                                LEFT JOIN out_vaccine_appt_group o on  a.GroupId = o.id 
                            WHERE a.ID IN @Ids ";
            return Query<VaccineApptForUser>(sql, new { Ids = ids }).ToList();
        }

        public List<VaccineApptIsAdd> VaccineApptIsAdd(string patname, string phone)
        {
            var sql = @" SELECT
	                            a.ID,
	                            b.ID AS PatId,
	                            b.PHONE_NO AS Phone,
	                            b.PAT_NAME AS PatName 
                            FROM
	                            out_vaccine_appt a
	                            INNER JOIN pub_pat_info b ON a.PAT_ID = B.ID 
                            WHERE
                                ( a.NewVaccineType = 1 )    
                                AND a.VACCINE_ID = 1 
                                AND a.`STATUS` = 4 
	                            AND b.PHONE_NO = @Phone AND b.PAT_NAME = @PatName ";
            return Query<VaccineApptIsAdd>(sql, new { Phone = phone, PatName = patname }).ToList().DeEncrypt();
        }

        public List<Out_Vaccine_Appt> GetOldOutApptData()
        {
            var sql = @"select a.*  FROM
							out_vaccine_appt a
							INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID
							LEFT JOIN pub_pat_info c ON a.PAT_ID = c.ID 
                            where  a.VACCINE_ID = 1 
                            AND (a.`STATUS` = 4 OR a.`STATUS` = 3 )
                            AND newvaccinetype IS null";
            return Query<Out_Vaccine_Appt>(sql).ToList();
        }

        public int UpdateOutVaccineAppt(List<Out_Vaccine_Appt> model)
        {
            model.ForEach(w => { w.UPDATE_TIME = DateTime.Now; });
            var sql = @" Update `out_vaccine_appt` SET `STATUS`= 4,NewVaccineType=2,QueueNumber=@QueueNumber,`UPDATE_TIME`=@UPDATE_TIME  WHERE ID = @Id ";
            return Execute(sql, model);
        }

        public List<AllVaccineForCall> GetAllVaccineForCall()
        {
            var sql = @" SELECT
	                            a.ID AS VaccineId,
	                            b.Id AS MapCallId,
	                            b.CreateTime AS CallTime 
                            FROM
	                            out_vaccine_appt a
	                            INNER JOIN out_vaccine_map_call b ON a.id = b.AppVaccineId
	                            WHERE a.`STATUS` = 5 AND b.CreateTime < @CallTime AND b.IsDelete = false ";
            return Query<AllVaccineForCall>(sql, new { CallTime = DateTime.Now.AddDays(-2).AddMinutes(-2) }).ToList();
        }

        public AllVaccineForCall GetVaccineForId(int id)
        {
            var sql = @" SELECT
	                            a.ID AS VaccineId,
	                            b.Id AS MapCallId,
	                            b.CreateTime AS CallTime,
                                c.Id AS CallId 
                            FROM
	                            out_vaccine_appt a
	                            INNER JOIN out_vaccine_map_call b ON a.id = b.AppVaccineId
                                INNER JOIN out_vaccine_appt_call c ON b.CallId = c.Id 
	                            WHERE a.ID=@Id AND b.IsDelete=false";
            return Query<AllVaccineForCall>(sql, new { Id = id })?.FirstOrDefault();
        }

        public List<VaccineApptForUser> GetOutVaccineApptForCall(Out_Vaccine_Appt_Call model)
        {
            var sql = @" SELECT
	                            a.QueueNumber AS Num,
	                            a.Id,
                                b.ID AS FlowId,
	                            a.PAT_ID AS PatId,
	                            a.USER_ID AS UserId,
	                            a.REMAKE AS Remake,
	                            a.CREATE_TIME AS CreateTime,
                                a.ORIGIN AS Origin,
                                a.`STATUS` AS Status,
	                            c.PAT_NAME AS PatName,
	                            c.GENDER AS Gender, 
                                c.BIRTHDAY AS Birthday,
                                c.PHONE_NO AS Phone 
                            FROM
	                            out_vaccine_appt a 
                                 INNER JOIN out_vaccine_appt_flow b ON a.FLOW_ID = b.ID
	                            INNER JOIN pub_pat_info c on a.PAT_ID = c.ID
                            WHERE
	                            a.NewVaccineType = 1 
	                            AND a.VACCINE_ID = 1 
	                            AND a.`STATUS` = 4 ";
            if (model.Origin != 0)
            {
                sql += " AND  (a.ORIGIN = @Origin OR a.ORIGIN = 3 ) ";
            }
            //判断新老用户
            if (model.PatAptType == 1)
            {
                sql += " AND (c.Mrn Is Null OR c.Mrn = '') ";
            }
            else if (model.PatAptType == 2)
            {
                sql += " AND (c.Mrn Is Not NULL AND c.Mrn != '') ";
            }
            //判断是否是小孩
            if (model.PatType == 2)
            {
                sql += " AND c.BIRTHDAY > @ChildDateTime";
            }
            else
            {
                sql += " AND c.BIRTHDAY < @ChildDateTime ";
            }
            sql += "  ORDER BY a.CREATE_TIME ASC  ";
            var result = Query<VaccineApptForUser>(sql, new { Origin = model.Origin, ChildDateTime = DateTime.Now.AddYears(-3) });
            return result.ToList().DeEncrypt();
        }

        public Out_Vaccine_Appt_Call GetVaccineAppCall(int id)
        {
            var sql = @" select * from out_vaccine_appt_call where id = @Id ";
            return Query<Out_Vaccine_Appt_Call>(sql, new { Id = id }).FirstOrDefault();
        }

        public List<Pub_Pat_Info> GetPubPatUserList(int userid, string name)
        {
            var sql = @"SELECT
	                            	b.`ID`,
	                                b.`PAT_ID`,
	                                b.`PAT_MRN`,
	                                b.`LAST_NAME`,
	                                b.`FIRST_NAME`,
	                                b.`PAT_NAME`,
	                                b.`BIRTHDAY`,
	                                b.`GENDER`,
	                                b.`CARD_ID`,
	                                b.`CARD_TYPE`,
	                                b.`PHONE_NO`,
	                                b.`PROVINCE`,
	                                b.`CITY`,
	                                b.`DISTRICT`,
	                                b.`EMAIL`,
	                                b.`NATIONALITY`,
	                                b.`IS_DEAD`,
	                                b.`IS_ACTIVE`,
	                                b.`PAT_SOURCE`,
	                                b.`IS_DELETED`,
	                                b.`MRN_NO`,
	                                b.`PAT_MRN_NUMBER`,
	                                b.`ID_NUMBER`,
	                                b.`GUARDIAN`,
	                                b.`Last_GUARDIAN`,
	                                b.`First_GUARDIAN`,
	                                b.`DOCUMENT_TYPE`,
	                                b.`CERTIFICATE_NUMBER`,
	                                b.`CLINIC_CARD`,
	                                b.`CLINIC_CARDTYPE`,
	                                b.`LAST_SIGN_OFF`,
	                                b.`LAST_SIGN_EpisodeNo`,
	                                b.`LinKingOpenId`,
	                                b.`IsDefault`,
	                                b.`IS_PEDIATRICS_USER`,
	                                b.`Pat_Remark`,
	                                b.`CityId`,
	                                b.`LocalAddress`,
	                                b.`EmergencyName`,
	                                b.`EmergencyPhone`,
	                                b.`EmergencyRelation`,
	                                b.`HowKnow`,
	                                b.`ContactWay` 
                            FROM
	                            Pub_Map_User_Pat a
	                            INNER JOIN pub_pat_info b ON a.PAT_ID = b.ID 
                            WHERE
	                            b.IS_DELETED = FALSE 
	                            AND a.IS_DELETED = FALSE 
	                            AND USER_ID = @UserId
	                           -- AND PAT_NAME = @PatName";
            return Query<Pub_Pat_Info>(sql, new { UserId = userid, PatName = name }).ToList().DeEncrypt();
        }

        public List<Pub_Pat_Info> GetMarkingPat()
        {
            var sql = @"select  pat.`ID`,
	                            pat.`PAT_ID`,
	                            pat.`PAT_MRN`,
	                            pat.`LAST_NAME`,
	                            pat.`FIRST_NAME`,
	                            pat.`PAT_NAME`,
	                            pat.`BIRTHDAY`,
	                            pat.`GENDER`,
	                            pat.`CARD_ID`,
	                            pat.`CARD_TYPE`,
	                            pat.`PHONE_NO`,
	                            pat.`PROVINCE`,
	                            pat.`CITY`,
	                            pat.`DISTRICT`,
	                            pat.`EMAIL`,
	                            pat.`NATIONALITY`,
	                            pat.`IS_DEAD`,
	                            pat.`IS_ACTIVE`,
	                            pat.`PAT_SOURCE`,
	                            pat.`IS_DELETED`,
	                            pat.`MRN_NO`,
	                            pat.`PAT_MRN_NUMBER`,
	                            pat.`ID_NUMBER`,
	                            pat.`GUARDIAN`,
	                            pat.`Last_GUARDIAN`,
	                            pat.`First_GUARDIAN`,
	                            pat.`DOCUMENT_TYPE`,
	                            pat.`CERTIFICATE_NUMBER`,
	                            pat.`CLINIC_CARD`,
	                            pat.`CLINIC_CARDTYPE`,
	                            pat.`LAST_SIGN_OFF`
                        from pub_pat_info pat inner join pub_map_user_pat map on pat.ID = map.PAT_ID where pat.PAT_MRN != '' and pat.PAT_MRN  is not null and map.IS_DELETED=0 and map.CREATE_TIME > '2021-05-17'";
            return Query<Pub_Pat_Info>(sql, null).ToList().DeEncrypt();
        }

        public int UpdatePatInfo(PatUpdateModel model)
        {
            StringBuilder str = new StringBuilder();
            var parms = new Dictionary<string, object>();
            str.Append("update Pub_Pat_Info set ");
            str.Append(@"CARD_TYPE=@CARD_TYPE,
                            CARD_ID=@CARD_ID ");
            if (!string.IsNullOrEmpty(model.Guardian))
            {
                str.Append(@",GUARDIAN=@GUARDIAN");
                parms.Add("@GUARDIAN", model.Guardian);
            }
            if (!string.IsNullOrEmpty(model.FirstGuardian))
            {
                str.Append(@",First_GUARDIAN=@First_GUARDIAN");
                parms.Add("@First_GUARDIAN", model.FirstGuardian);
            }
            if (!string.IsNullOrEmpty(model.LastGuardian))
            {
                str.Append(@",Last_GUARDIAN=@Last_GUARDIAN");
                parms.Add("@Last_GUARDIAN", model.LastGuardian);
            }
            if (model.DocumentType > 0)
            {
                str.Append(@",DOCUMENT_TYPE=@DOCUMENT_TYPE");
                parms.Add("@DOCUMENT_TYPE", model.DocumentType);
            }
            if (!string.IsNullOrEmpty(model.CertificateNumber))
            {
                str.Append(@",CERTIFICATE_NUMBER=@CERTIFICATE_NUMBER");
                parms.Add("@CERTIFICATE_NUMBER", model.CertificateNumber);
            }
            str.Append(@" where ID=@ID");
            parms.Add("@CARD_TYPE", model.CardType);
            parms.Add("@CARD_ID", model.CardId);
            parms.Add("@ID", model.Id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public List<Pub_Map_User_Pat> GetPatIdsByUserId(int userID)
        {
            var sql = @"select PAT_ID from Pub_Map_User_Pat where USER_ID = @USER_ID and IS_DELETED = 0";
            return Query<Pub_Map_User_Pat>(sql, new { USER_ID = userID }).ToList();
        }
        public List<Pub_Map_User_Pat> GetUserPatByPatId(int patId)
        {
            var sql = @"select * from Pub_Map_User_Pat where PAT_ID = @PAT_ID and IS_DELETED = 0";
            return Query<Pub_Map_User_Pat>(sql, new { PAT_ID = patId }).ToList();
        }

        public async Task<Pub_Pat_Info> GetPubPatInfoByIdAsync(int patId)
        {
            const string sql = "select * from pub_pat_info where IS_DELETED = 0 and Id=@patId ";

            var result = await QueryAsync<Pub_Pat_Info>(sql, new { patId });

            return result?.FirstOrDefault()?.DeEncrypt();
        }

        public int UpdateMapUserPatRelation(int userid)
        {
            var sql = @" Update pub_map_user_pat Set RELATION_SHIP=4 Where USER_ID=@UserId And RELATION_SHIP = 8 ";
            return Execute(sql, new { UserId = userid });
        }

        public List<Pub_Pat_Info> GetSignOffPats(string times)
        {
            var sql = @"select `ID`, `PAT_ID`, `PAT_MRN`, `LAST_NAME`, `FIRST_NAME`, `PAT_NAME`, `BIRTHDAY`, `GENDER`, `CARD_ID`, `CARD_TYPE`, `PHONE_NO`, `PROVINCE`, `CITY`, `DISTRICT`, `EMAIL`, `NATIONALITY`, `IS_DEAD`, `IS_ACTIVE`, `PAT_SOURCE`, `IS_DELETED`, `MRN_NO`, `PAT_MRN_NUMBER`, `ID_NUMBER`, `GUARDIAN`, `Last_GUARDIAN`, `First_GUARDIAN`, `DOCUMENT_TYPE`, `CERTIFICATE_NUMBER`, `CLINIC_CARD`, `CLINIC_CARDTYPE`, `LAST_SIGN_OFF`, `LAST_SIGN_EpisodeNo`, `LinKingOpenId`, `IsDefault`, `IS_PEDIATRICS_USER`, `Pat_Remark`, `CityId`, `LocalAddress`, `EmergencyName`, `EmergencyPhone`, `EmergencyRelation`, `HowKnow`, `ContactWay` from pub_pat_info where LAST_SIGN_OFF = @times";
            return Query<Pub_Pat_Info>(sql, new { times = times }).ToList().DeEncrypt();
        }

        public int SavePatMrn(int id, string mrn)
        {
            var sql = @" Update Pub_Pat_Info Set Mrn=@Mrn Where Id=@Id ";
            return Execute(sql, new { Id = id, Mrn = mrn });
        }
        public int SavePatTcInfo(int id, string patId, string patMrn, string mrn)
        {
            var sql = @" Update Pub_Pat_Info Set Mrn=@Mrn,PAT_ID=@PAT_ID,PAT_MRN=@PAT_MRN Where Id=@Id ";
            return Execute(sql, new { Id = id, Mrn = mrn, PAT_ID = patId, PAT_MRN = patMrn });
        }

        /// <summary>
        /// 同步患者mrn信息使用
        /// </summary>
        /// <returns></returns>
        public List<PatTcInfo> GetAllPatForMrn()
        {
            var sql = "select ID,PAT_MRN,PHONE_NO,BIRTHDAY,LAST_NAME,FIRST_NAME from pub_pat_info where (mrn is null or mrn = '') and IS_DELETED = false";
            //var sql = "select ID,PAT_MRN,PHONE_NO,BIRTHDAY,LAST_NAME,FIRST_NAME from pub_pat_info where PAT_NAME like '%蒋%'";
            return Query<PatTcInfo>(sql, null).ToList().DeEncrypt();//032711
        }

        public Out_Vaccine_Map_Call GetUserPatsVaccAptCount(int userID)
        {
            var sql = "select c.* from out_vaccine_appt a INNER JOIN out_vaccine_map_call c on a.ID = c.AppVaccineId where USER_ID = @USER_ID and `STATUS` = 5";
            return Query<Out_Vaccine_Map_Call>(sql, new { USER_ID = userID }).FirstOrDefault();
        }

        public List<Pub_Pat_Info> GetUserPatHasSignOff(int userID)
        {
            var sql = "select * from pub_pat_info	where ID in (select PAT_ID from pub_map_user_pat where USER_ID = @USER_ID and IS_DELETED =0) and IsReadSignOff = 1";
            return Query<Pub_Pat_Info>(sql, new { USER_ID = userID }).ToList();
        }

        public int PatSignOff(int patId)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_pat_info set IsReadSignOff = 1 where id =@id");

            parms.Add("@id", patId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int ReadMyPatReport(int patId)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_pat_info set IsReadSignOff = 0 where id =@id");

            parms.Add("@id", patId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public List<Pub_Pat_Info> GetPatInfo()
        {
            var sql = @" select ID,PAT_MRN from pub_pat_info where PAT_MRN is not NULL AND PAT_MRN !='' and GENDER =1";
            return Query<Pub_Pat_Info>(sql).ToList();
        }

        public int UpdatePatGender(List<int> ls)
        {
            var sql = @"UPDATE pub_pat_info set GENDER = 0 where id in @Id ";
            return Execute(sql, new { Id = ls });
        }

        public List<Pub_Pat_Info> GetSpaiclPats()
        {
            var sql = @"select ID,PAT_NAME from pub_pat_info where FIRST_NAME is null and LAST_NAME is null and BIRTHDAY is not null and PHONE_NO is not null";
            return Query<Pub_Pat_Info>(sql).ToList();
        }

        public int UpdatePatName(int Id, string xing, string ming)
        {
            var sql = @"UPDATE pub_pat_info set LAST_NAME = @LAST_NAME,FIRST_NAME=@FIRST_NAME where id = @Id ";
            return Execute(sql, new { Id = Id, LAST_NAME = xing, FIRST_NAME = ming });
        }

        public List<Pub_Sign_Report> GetPubSignReportByPatId(int patId)
        {
            var sql = @"select * from pub_sign_report where PatId = @PatId";
            return Query<Pub_Sign_Report>(sql, new { PatId = patId }).ToList();
        }

        public async Task<List<Pub_Pat_Info>> GetTempPatAsync()
        {
            const string sql = "select * from pub_pat_info where IS_DELETED=FALSE and Id in (select PAT_ID from pub_map_user_pat WHERE IS_DELETED=FALSE and RELATION_SHIP!=1 ) limit 50";

            var result = await QueryAsync<Pub_Pat_Info>(sql);
            return result.ToList().DeEncrypt();
        }

        public async Task<List<Pub_Pat_Info>> GetByPIdAsync(string pId)
        {
            const string sql = "select * from pub_pat_info where IS_DELETED=false and PAT_MRN =@pId ";
            var result = await QueryAsync<Pub_Pat_Info>(sql, new { pId = pId });

            return result.ToList().DeEncrypt();
        }

        public async Task<List<Pub_Pat_Info>> GetByCardIdAsync(string cardId)
        {
            const string sql = "select * from pub_pat_info where IS_DELETED=false and CARD_ID=@cardId";
            var result = await QueryAsync<Pub_Pat_Info>(sql, new
            {
                cardId = cardId.Encrypt()
            });

            return result.ToList().DeEncrypt();
        }

        public List<Pub_User_Info> GetUsersByPatId(int patId)
        {
            const string sql = @"SELECT
                                 	u.* 
                                 FROM
                                 	pub_map_user_pat AS map
                                 	inner JOIN pub_user_info AS u ON map.USER_ID = u.ID 
                                 WHERE
                                 	map.IS_DELETED = FALSE 
                                 	AND u.IS_DELETED = FALSE 
                                 	AND map.PAT_ID = @patId";

            var parms = new Dictionary<string, object>
            {
                { "@patId", patId }
            };

            var result = Query<Pub_User_Info>(sql, parms);
            return result.ToList();
        }

        /// <summary>
        /// 查询用户绑定的患者
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Pub_Pat_Info> GetPatientsByUserId(int userId)
        {
            const string sql = @"SELECT
                                 	pat.* 
                                 FROM
                                 	pub_map_user_pat AS map
                                 	inner JOIN pub_pat_info AS pat ON map.PAT_ID = pat.ID 
                                 WHERE
                                 	map.IS_DELETED = FALSE 
                                 	AND pat.IS_DELETED = FALSE 
                                 	AND map.USER_ID = @userId";

            var parms = new Dictionary<string, object>
            {
                { "@userId", userId }
            };

            var result = Query<Pub_Pat_Info>(sql, parms);
            return result.ToList();
        }
        public List<Pub_Map_User_Pat> GetMapUserPat(int userid, List<int> patids)
        {
            var sql = @" select * from pub_map_user_pat where USER_ID = @UserId And PAT_ID IN @PatId And IS_DELETED = FALSE ";
            return Query<Pub_Map_User_Pat>(sql, new { UserId = userid, PatId = patids }).ToList();
        }

        /// <summary>
        /// 查询用户所有的绑定关系
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Pub_Map_User_Pat> GetMapsByUserId(int userId)
        {
            const string sql = @"SELECT
                                 	map.* 
                                 FROM
                                 	pub_map_user_pat AS map
                                 	inner JOIN pub_user_info AS u ON map.USER_ID = u.ID 
                                 WHERE
                                 	map.IS_DELETED = FALSE 
                                 	AND u.IS_DELETED = FALSE 
                                 	AND map.USER_ID = @userId";

            var parms = new Dictionary<string, object>
            {
                { "@userId", userId }
            };

            var result = Query<Pub_Map_User_Pat>(sql, parms);
            return result.ToList();
        }
    }
}

