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.Model;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{
    /// <summary>
	/// 用户表仓储层
	/// 创建人：杨江军
	/// 创建时间：2020/4/7 11:42:16
	/// </summary>
	public class PubUserInfoRepository : BaseRepositoryToASHermed_SinoInterface<Pub_User_Info>, IPubUserInfoRepository
    {
        public int InsertPubUserInfo(Pub_User_Info userInfo)
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"insert into pub_user_info (OPEN_ID,LAST_NAME,FIRST_NAME,NICK_NAME,COUNTRY,PROVINCE,CITY,GENDER,HEADIMG,LANGUAGE,PHONE,EMAIL,REGISTRATION_SOURCE,IS_NEW,IS_REG,BIRTHDAY,IS_DELETED,CREATE_TIME,UPDATE_TIME,TREATMENT_PASSWORD,KEY_TYPE,ANDROID_ID,IOS_ID,IDENTIFIER,APP_LANGUAGE,APP_OPEN_ID,IM_ID,IS_NEW_LOGIN_APP,U_Id,YZOpenId,YZWatchMode) values (@OPEN_ID ,@LAST_NAME,@FIRST_NAME,@NICK_NAME,@COUNTRY,@PROVINCE,@CITY,@GENDER,@HEADIMG,@LANGUAGE,@PHONE,@EMAIL,@REGISTRATION_SOURCE,@IS_NEW,@IS_REG,@BIRTHDAY,@IS_DELETED,@CREATE_TIME,@UPDATE_TIME,@TREATMENT_PASSWORD,@KEY_TYPE,@ANDROID_ID,@IOS_ID,@IDENTIFIER,@APP_LANGUAGE,@APP_OPEN_ID,@IM_ID,@IS_NEW_LOGIN_APP,@U_Id,@YZOpenId,@YZWatchMode)";
            parms.Add("@OPEN_ID", userInfo.Open_ID);
            parms.Add("@LAST_NAME", userInfo.Last_Name);
            parms.Add("@FIRST_NAME", userInfo.First_Name);
            parms.Add("@NICK_NAME", userInfo.Nick_Name);
            parms.Add("@COUNTRY", userInfo.Country);
            parms.Add("@PROVINCE", userInfo.Province);
            parms.Add("@CITY", userInfo.City);
            parms.Add("@GENDER", userInfo.Gender);
            parms.Add("@HEADIMG", userInfo.HeadImg);
            parms.Add("@LANGUAGE", userInfo.Language);
            parms.Add("@PHONE", userInfo.Phone);
            parms.Add("@EMAIL", userInfo.Email);
            parms.Add("@REGISTRATION_SOURCE", userInfo.Registration_Source);
            parms.Add("@IS_NEW", userInfo.Is_New);
            parms.Add("@IS_REG", userInfo.Is_Reg);
            parms.Add("@BIRTHDAY", userInfo.Birthday);
            parms.Add("@IS_DELETED", userInfo.Is_Deleted);
            parms.Add("@CREATE_TIME", userInfo.Create_Time);
            parms.Add("@UPDATE_TIME", userInfo.Update_Time);
            parms.Add("@TREATMENT_PASSWORD", userInfo.Treatment_Password);
            parms.Add("@KEY_TYPE", userInfo.Key_Type);
            parms.Add("@ANDROID_ID", userInfo.Android_ID);
            parms.Add("@IOS_ID", userInfo.IOS_ID);
            parms.Add("@IDENTIFIER", userInfo.Identifier);
            parms.Add("@APP_LANGUAGE", userInfo.APP_Language);
            parms.Add("@APP_OPEN_ID", userInfo.APP_Open_ID);
            parms.Add("@IM_ID", userInfo.IM_ID);
            parms.Add("@IS_NEW_LOGIN_APP", userInfo.Is_New_Login_App);
            parms.Add("@U_Id", userInfo.U_Id);
            parms.Add("@YZOpenId", userInfo.YZOpenId);
            parms.Add("@YZWatchMode", userInfo.YZWatchMode);
            var result = Insert(selectSql, parms);
            return result;
        }

        public int UpdatePubUserInfo(Pub_User_Info userInfo)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"update pub_user_info set
                            OPEN_ID =@OPEN_ID, 
                            LAST_NAME=@LAST_NAME,
                            FIRST_NAME=@FIRST_NAME,
                            NICK_NAME=@NICK_NAME,
                            COUNTRY=@COUNTRY,
                            PROVINCE=@PROVINCE,
                            CITY=@CITY,
                            GENDER=@GENDER,
                            HEADIMG=@HEADIMG,
                            LANGUAGE=@LANGUAGE,
                            PHONE=@PHONE,
                            EMAIL=@EMAIL,
                            REGISTRATION_SOURCE=@REGISTRATION_SOURCE,
                            IS_NEW=@IS_NEW,
                            IS_REG=@IS_REG,
                            BIRTHDAY=@BIRTHDAY,
                            IS_DELETED=@IS_DELETED,
                            CREATE_TIME=@CREATE_TIME,
                            UPDATE_TIME=@UPDATE_TIME,
                            TREATMENT_PASSWORD=@TREATMENT_PASSWORD,
                            KEY_TYPE=@KEY_TYPE,
                            ANDROID_ID=@ANDROID_ID,
                            IOS_ID=@IOS_ID,
                            IDENTIFIER=@IDENTIFIER,
                            APP_LANGUAGE=@APP_LANGUAGE,
                            APP_OPEN_ID=@APP_OPEN_ID,
                            IM_ID=@IM_ID,
                            IS_NEW_LOGIN_APP=@IS_NEW_LOGIN_APP
                            where ID=@ID
                            ");
            parms.Add("@OPEN_ID", userInfo.Open_ID);
            parms.Add("@LAST_NAME", userInfo.Last_Name);
            parms.Add("@FIRST_NAME", userInfo.First_Name);
            parms.Add("@NICK_NAME", userInfo.Nick_Name);
            parms.Add("@COUNTRY", userInfo.Country);
            parms.Add("@PROVINCE", userInfo.Province);
            parms.Add("@CITY", userInfo.City);
            parms.Add("@GENDER", userInfo.Gender);
            parms.Add("@HEADIMG", userInfo.HeadImg);
            parms.Add("@LANGUAGE", userInfo.Language);
            parms.Add("@PHONE", userInfo.Phone);
            parms.Add("@EMAIL", userInfo.Email);
            parms.Add("@REGISTRATION_SOURCE", userInfo.Registration_Source);
            parms.Add("@IS_NEW", userInfo.Is_New);
            parms.Add("@IS_REG", userInfo.Is_Reg);
            parms.Add("@BIRTHDAY", userInfo.Birthday);
            parms.Add("@IS_DELETED", userInfo.Is_Deleted);
            parms.Add("@CREATE_TIME", userInfo.Create_Time);
            parms.Add("@UPDATE_TIME", DateTime.Now);
            parms.Add("@TREATMENT_PASSWORD", userInfo.Treatment_Password);
            parms.Add("@KEY_TYPE", userInfo.Key_Type);
            parms.Add("@ANDROID_ID", userInfo.Android_ID);
            parms.Add("@IOS_ID", userInfo.IOS_ID);
            parms.Add("@IDENTIFIER", userInfo.Identifier);
            parms.Add("@APP_LANGUAGE", userInfo.APP_Language);
            parms.Add("@APP_OPEN_ID", userInfo.APP_Open_ID);
            parms.Add("@IM_ID", userInfo.IM_ID);
            parms.Add("@IS_NEW_LOGIN_APP", userInfo.Is_New_Login_App);
            parms.Add("@ID", userInfo.ID);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public Pub_User_Info SelectByIdentifier(string identifier)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@identifier", identifier);
            var selectSql = @" SELECT * FROM pub_user_info
                                        WHERE IS_DELETED = 0
                                          and IDENTIFIER = @identifier";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public async Task<User> GetUser(int id)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", id);
            var selectSql = $@" select id,Name from User where id=@Id";
            var result = await QueryAsync<User>(selectSql, parms);
            return result?.FirstOrDefault();
        }
        public Pub_User_Info SelectByPhone(string acc)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@phone", acc);
            var selectSql = @"select *
                                    from pub_user_info
                                    where PHONE = @phone
                                      AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public string GetMHelper(string role)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@TITLE", role);
            var selectSql = @"select OPENID from dic_message_tab_info where TITLE = @TITLE";
            var result = Query<string>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectByLinKinOpenId(string linKingOpenId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@LinKingOpenId", linKingOpenId);
            var selectSql = @"select *
                                    from pub_user_info
                                    where LinKingOpenId = @LinKingOpenId
                                      AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectByEmail(string acc)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@email", acc);
            var selectSql = @"select *
                                        from pub_user_info
                                        where EMAIL = @email 
                                          AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_Map_User_Type SelectUserTypeByPhone(string phone)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@phone", phone);
            var selectSql = @"select ID, PHONE_NO, USER_TYPE, AVAILABLE_COUPON
                                    from pub_map_user_type
                                    where PHONE_NO = @phone";
            var result = Query<Pub_Map_User_Type>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectByAppOpenId(string openId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@appOpenId", openId);
            var selectSql = @"select *
                                        from pub_user_info
                                        where APP_OPEN_ID = @appOpenId
                                          AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectByPrimaryKey(int userId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@ID", userId);
            var selectSql = @"select *
                                        from pub_user_info
                                        where ID = @ID
                                          AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info GetUserByUid(string uid)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@U_ID", uid);
            var selectSql = @"select *
                                        from pub_user_info
                                        where U_ID = @U_ID
                                          AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectByPatId(int pid)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@patId", pid);
            var selectSql = @"select u.*
                        from pub_user_info u
                                 join pub_map_user_pat up on up.USER_ID = u.ID
                        where u.IS_DELETED = 0
                          and up.IS_DELETED = 0
                          and up.PAT_ID = @patId
                        LIMIT 0,1";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public List<Pub_User_Info> GetAllUser()
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"select id,BIRTHDAY,GENDER
                                        from pub_user_info
                                        where IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.ToList();
        }

        public Pub_User_Info SelectByAppOpenIdWithPhone(string openId, string account)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@appOpenId", openId);
            parms.Add("@phone", account);
            var selectSql = @"select *
                                    from pub_user_info
                                    where APP_OPEN_ID = @appOpenId
                                      AND PHONE = @phone
                                      AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info GetUserByPhone(string phone)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@phone", phone);
            var selectSql = @"select *
                                    from pub_user_info
                                    where  PHONE = @phone
                                      AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public int UserComformInformed(int userId)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"update pub_user_info set
                            IS_READ_INFORMED=@IS_READ_INFORMED
                            where ID=@ID
                            ");

            parms.Add("@IS_READ_INFORMED", true);
            parms.Add("@ID", userId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int UpdateTreatment(int userId, string md5PassWord)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_user_info
                            SET TREATMENT_PASSWORD = @Password
                            WHERE ID = @ID");

            parms.Add("@Password", md5PassWord);
            parms.Add("@ID", userId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public Pub_User_Info SelectByTreatment(int userId, string md5PassWord)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", userId);
            parms.Add("@Password", md5PassWord);
            var selectSql = @"SELECT ID
                                FROM pub_user_info
                         WHERE ID = @Id
                AND TREATMENT_PASSWORD = @Password";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Pub_User_Info SelectById(int userId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", userId);
            var selectSql = @"SELECT *
                                FROM pub_user_info
                         WHERE ID = @Id ";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public List<Pub_User_Info> SelectByIds(List<int> userIds)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", userIds);
            var selectSql = @"SELECT *
                                FROM pub_user_info
                         WHERE ID IN @Id ";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result.ToList();
        }

        public List<PubUserModel> SelectUserWithDocByImid(string aiteId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Id", aiteId);
            var selectSql = @"select ID,
               NICK_NAME as nickName,
               GENDER    as gender,
               HEADIMG   as headImg,
               PHONE     as phone,
               IM_ID     as imId,
               1         as userType
        from pub_user_info
        where IS_DELETED = 0
          and (IM_ID = @Id or ID = @Id)
        UNION
        select ID,
               NICKNAME as nickName,
               Sex    as gender,
               UserImg   as headImg,
               PHONE     as phone,
               IMID     as imId,
               2         as userType
        from sys_user
        where `STATUS` = 1
          and (IMID = @Id or ID = @Id)";
            var result = Query<PubUserModel>(selectSql, parms);
            return result?.ToList();
        }

        public int CignaPerfectUserInfo(CignaUserInfo model)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_user_info SET LANGUAGE=@LANGUAGE ");
            if (!string.IsNullOrEmpty(model.Birthday))
            {
                str.Append(@",BIRTHDAY = @BIRTHDAY");
                parms.Add("@BIRTHDAY", model.Birthday);
            }
            if (!string.IsNullOrEmpty(model.FirstName))
            {
                str.Append(@",FIRST_NAME = @FIRST_NAME");
                parms.Add("@FIRST_NAME", model.FirstName);
            }
            if (!string.IsNullOrEmpty(model.HeadImg))
            {
                str.Append(@",HEADIMG = @HEADIMG");
                parms.Add("@HEADIMG", model.HeadImg);
            }
            if (!string.IsNullOrEmpty(model.LastName))
            {
                str.Append(@",LAST_NAME = @LAST_NAME");
                parms.Add("@LAST_NAME", model.LastName);
            }
            if (!string.IsNullOrEmpty(model.PatName))
            {
                str.Append(@",NICK_NAME = @NICK_NAME");
                parms.Add("@NICK_NAME", model.PatName);
            }
            if (model.Sex != null)
            {
                str.Append(@",GENDER = @GENDER");
                parms.Add("@GENDER", model.Sex);
            }
            str.Append(@"  WHERE ID = @ID");
            parms.Add("@LANGUAGE", 2);
            parms.Add("@ID", model.Id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public PatUserInfoResp SelectByImId(int userId, string imId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@docId", userId);
            parms.Add("@imId", imId);
            var selectSql = @"select a.id,
               a.GENDER,
               a.NICK_NAME as NICKNAME,
               a.HEADIMG,
               a.IM_ID as IMID,
               b.REMARKS,
               1 as USERTYPE,
               b.IS_STAR as ISSTAR,
               TIMESTAMPDIFF(YEAR, a.BIRTHDAY, CURDATE()) AS AGE,
               a.BIRTHDAY,
               b.DESCRIPTION
        from pub_user_info a
                 left join out_map_doc_pat b on b.PAT_ID = a.ID and b.DOCTOR_ID = @docId and b.STATUS = 1
        where a.IS_DELETED = false
          and (a.IM_ID = @imId or a.ID = @imId)
        union
        select a.id,
               a.Sex as GENDER,
               a.NICKNAME,
               a.UserImg as HEADIMG,
               a.IMID,
               null  as REMARKS,
               2   as USERTYPE,
               null   as ISSTAR,
               0 AS AGE,
               '' as BIRTHDAY,
               null  as DESCRIPTION
        from sys_user a
        where a.status = 1
          and (a.IMID = @imId or a.ID = @imId)";
            var result = Query<PatUserInfoResp>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public async Task<List<Pub_Relationship>> GetRelationship()
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"select * from pub_relationship WHERE `Status` =1";
            var result = await QueryAsync<Pub_Relationship>(selectSql, parms);
            return result?.ToList();
        }
        public async Task<List<Pub_Contactway>> GetContactway()
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"select * from pub_contactway WHERE `Status` =1";
            var result = await QueryAsync<Pub_Contactway>(selectSql, parms);
            return result?.ToList();
        }
        public async Task<List<Pub_Howknow>> GetHowknow()
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"select * from pub_howknow WHERE `Status` =1";
            var result = await QueryAsync<Pub_Howknow>(selectSql, parms);
            return result?.ToList();
        }

        public int UserSignOff(int patId)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_user_info set IsReadSignOff = 1 where id in (select USER_ID from Pub_Map_User_Pat where PAT_ID = @PAT_ID )");

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

        public List<Pub_User_Info> GetAllUserInfo()
        {
            var sql = @" select ID,OPEN_ID,NICK_NAME,PHONE from pub_user_info  where OPEN_ID is not NULL or OPEN_ID !='' ";
            return Query<Pub_User_Info>(sql).ToList();
        }
        public List<Pub_User_Info> GetIsRegNotHasImIdUser()
        {
            var sql = @" SELECT ID from pub_user_info where (IM_ID is null or IM_ID = '')  and IS_REG = 1 ";
            return Query<Pub_User_Info>(sql).ToList();
        }

        public Sys_User GetReceptionInfoByAcc(string account, string password)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Account", account);
            parms.Add("@Password", password);
            var selectSql = @"select * from sys_user where Account = @Account and `Password`=@Password and `STATUS` = 1";
            var result = Query<Sys_User>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public Sys_User GetReceptionInfoByPhone(string phone)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@phone", phone);
            var selectSql = @"select * from sys_user where phone = @phone and RoleId = 0 and `STATUS` = 1";
            var result = Query<Sys_User>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public int UpdateUserVersion(int id, string vers)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_user_info
                            SET VersionNumber = @VersionNumber,
                                VersionUpdateTime = @VersionUpdateTime
                            WHERE ID = @ID");

            parms.Add("@VersionNumber", vers);
            parms.Add("@VersionUpdateTime", DateTime.Now);
            parms.Add("@ID", id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int InsertReceptionCode(string code)
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"insert into pub_receptioncode (`Code`,`IsUse`) values (@Code ,@IsUse)";
            parms.Add("@Code", code);
            parms.Add("@IsUse", false);
            var result = Insert(selectSql, parms);
            return result;
        }

        public Pub_ReceptionCode GetPubReceptionCode(string code)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@Code", code);
            var selectSql = @"select * from pub_receptioncode where Code = @Code";
            var result = Query<Pub_ReceptionCode>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public int InvalidReceptionCode(string code)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_receptioncode
                            SET IsUse = true
                            WHERE code = @code");

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

        public int InsertPubComplaint(Pub_Complaint userComplaintInfo)
        {
            var parms = new Dictionary<string, object>();
            var selectSql = @"insert into pub_complaint (UserIMID,DocIMID,ComplaintContent) values (@UserIMID ,@DocIMID,@ComplaintContent)";
            parms.Add("@UserIMID", userComplaintInfo.UserIMID);
            parms.Add("@DocIMID", userComplaintInfo.DocIMID);
            parms.Add("@ComplaintContent", userComplaintInfo.ComplaintContent);
            var result = Insert(selectSql, parms);
            return result;
        }

        public Pub_Sms_Survey GetSmsSurvey(string pid)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@pid", pid);
            var selectSql = @"select *
                                from pub_sms_survey
                                where PID = @pid";
            var result = Query<Pub_Sms_Survey>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public int UpdateSmsSurvey(Pub_Sms_Survey ent)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_sms_survey
                            SET PID = @PID,
                                PHONE = @PHONE,
                                NAME = @NAME,
                                APT_TIME = @APT_TIME,
                                CONTENT = @CONTENT,
                                HOS_ID = @HOS_ID,
                                PAT_MRN = @PAT_MRN
                            WHERE ID = @ID");

            parms.Add("@PID", ent.Pid);
            parms.Add("@PHONE", ent.Phone);
            parms.Add("@NAME", ent.Name);
            parms.Add("@APT_TIME", ent.Apt_Time);
            parms.Add("@CONTENT", ent.Content);
            parms.Add("@HOS_ID", ent.Hos_Id);
            parms.Add("@PAT_MRN", ent.Pat_Mrn);
            parms.Add("@ID", ent.Id);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public async Task<int> YouZanMatchUserOpenId(int userID, string openId)
        {
            var parms = new Dictionary<string, object>();
            StringBuilder str = new StringBuilder();
            str.Append(@"UPDATE pub_user_info
                            SET YZOpenId = @YZOpenId
                            WHERE ID = @ID");

            parms.Add("@YZOpenId", openId);
            parms.Add("@ID", userID);
            var result = await ExecuteAsync(str.ToString(), parms);
            return result;
        }

        /// <summary>
        /// 标记有赞付费用户
        /// </summary>
        /// <param name="userId"></param> 
        /// <param name="watchMode"></param>
        /// <returns></returns> 
        public int YouZanRecordWatchMode(int userId, int watchMode)
        {
            const string sql = "update pub_user_info set YZWatchMode=@watchMode where ID=@userId ";
            var parms = new Dictionary<string, object>
            {
                {"@watchMode",watchMode},
                {"@userId", userId}
            };

            var result = Execute(sql, parms);

            return result;
        }

        public Pub_User_Info GetUserByYZOpenId(string openId)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@YZOpenId", openId);
            var selectSql = @"select *
                                    from pub_user_info
                                    where  YZOpenId = @YZOpenId
                                      AND IS_DELETED = FALSE";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        public UserDetail SelectDetailByPhone(string sharingPhone)
        {
            var parms = new Dictionary<string, object>();
            parms.Add("@phone", sharingPhone);
            var selectSql = @"select a.ID,
               a.OPEN_ID OpenId,
               a.NICK_NAME NickName,
               LAST_NAME LastName,
               FIRST_NAME FirstName,
               a.COUNTRY Country,
               a.PROVINCE Province,
               a.CITY City,
               a.GENDER,
               a.LANGUAGE,
               a.PHONE,
               a.EMAIL,
               a.IS_REG IsReg,
               a.BIRTHDAY,
               a.IS_DELETED IsDeleted,
               a.CREATE_TIME CreateTime,
               a.UPDATE_TIME UpdateTime,
               a.HEADIMG HeadImg,
               a.APP_LANGUAGE APPLanguage,
               a.IS_NEW_LOGIN_APP IsNewLoginApp,
               b.USER_TYPE userType,
               (select SUM(c.CHANGED_INTEGRAL)
                from pub_integral_flow c
                where c.PHONE_NO = a.PHONE
                  and c.`STATUS` != 1) as
                   TOTAL_INTEGRAL,
               a.REGISTRATION_SOURCE RegistrationSource,
               a.IS_NEW IsNew,
               a.KEY_TYPE KeyType,
               a.ANDROID_ID AndroidId,
               a.IOS_ID IOSId,
               a.IM_ID IMId
        from pub_user_info a
                 left join pub_map_user_type b on b.PHONE_NO = a.PHONE
        where a.IS_DELETED = FALSE
          and a.PHONE = @phone";
            var result = Query<UserDetail>(selectSql, parms);
            return result?.FirstOrDefault();
        }

        /// <summary>
        /// 查询家庭成员列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<PatientModel>> GetFamilyListByUserIdAsync(int userId)
        {
            const string sql = @"SELECT
                                	u.Id AS UserId,
	                                pat.Id AS PatId,
                                    pat.PAT_MRN as PId,
                                    pat.PAT_ID as TcRowId,
	                                pat.FIRST_NAME AS FirstName,
	                                pat.LAST_NAME AS LastName,
	                                pat.PAT_NAME AS `Name`,
	                                pat.GENDER AS Gender,
	                                pat.BIRTHDAY AS Birthday,
	                                TIMESTAMPDIFF(
	                                	YEAR,
	                                	pat.BIRTHDAY,
	                                CURDATE()) AS Age,
                                    pat.PHONE_NO as PhoneNo,
                                    pat.EMAIL As Email,
	                                pat.CARD_ID AS CardId,
	                                pat.CARD_TYPE AS CardType,
	                                pat.Mrn AS Mrn,
									pat.GuardianPhone,
									pat.Last_GUARDIAN as LastGuardian,
									pat.First_GUARDIAN as FirstGuardian,
									pat.DOCUMENT_TYPE as DocumentType,
									pat.CERTIFICATE_NUMBER CertificateNumber,
									pat.NATIONALITY as Nationality,
									pat.PROVINCE as Province,
									pat.CITY as City,
									pat.CityId,
									pat.LocalAddress,
									pat.EmergencyName,
									pat.EmergencyPhone,
									pat.EmergencyRelation,
									pat.HowKnow,
									pat.ContactWay,
									pat.ContactValue AS Chat,
									pat.PayType,
                                    pat.InsuranceCardUrl,
	                                map.Ties,
                                IF
                                	( PAYTYPE IS NULL OR EmergencyName IS NULL, 0, 1 ) AS IsPerfect,
                                IF
                                	( pat.GUARDIAN IS NULL OR pat.GuardianPhone IS NULL OR pat.CERTIFICATE_NUMBER IS NULL, 0, 1 ) AS IsPerfectGuardian 
                                FROM
                                	pub_user_info AS u
                                	INNER JOIN pub_map_user_pat AS map ON map.USER_ID = u.Id
                                	INNER JOIN pub_pat_info AS pat ON pat.Id = map.PAT_ID 
                                WHERE
                                	u.IS_DELETED = FALSE 
                                	AND map.IS_DELETED = FALSE 
                                    AND (map.RELATION_SHIP = 1 or map.RELATION_SHIP = 2)
                                	AND pat.IS_DELETED = FALSE 
                                	AND u.Id = @userId
                                ORDER BY map.CREATE_TIME DESC
                                ";

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

            var result = await QueryAsync<PatientModel>(sql, parms);

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

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="patientId"></param>
        /// <returns></returns>
        public async Task<PatientModel> GetPatientInfoByIdAsync(int userId, int patientId)
        {
            const string sql = @"SELECT
                                	u.Id AS UserId,
	                                pat.Id AS PatId,
                                    pat.PAT_MRN as PId,
                                    pat.PAT_ID as TcRowId,
	                                pat.FIRST_NAME AS FirstName,
	                                pat.LAST_NAME AS LastName,
	                                pat.PAT_NAME AS `Name`,
	                                pat.GENDER AS Gender,
	                                pat.BIRTHDAY AS Birthday,
	                                TIMESTAMPDIFF(
	                                	YEAR,
	                                	pat.BIRTHDAY,
	                                CURDATE()) AS Age,
                                    pat.PHONE_NO as PhoneNo,
                                    pat.EMAIL As Email,
	                                pat.CARD_ID AS CardId,
	                                pat.CARD_TYPE AS CardType,
	                                pat.Mrn AS Mrn,
									pat.GuardianPhone,
									pat.Last_GUARDIAN as LastGuardian,
									pat.First_GUARDIAN as FirstGuardian,
									pat.DOCUMENT_TYPE as DocumentType,
									pat.CERTIFICATE_NUMBER CertificateNumber,
									pat.NATIONALITY as Nationality,
									pat.PROVINCE as Province,
									pat.CITY as City,
									pat.CityId,
									pat.LocalAddress,
									pat.EmergencyName,
									pat.EmergencyPhone,
									pat.EmergencyRelation,
									pat.HowKnow,
									pat.ContactWay,
									pat.ContactValue AS Chat,
									pat.PayType,
                                    pat.InsuranceCardUrl,
	                                map.Ties,
                                IF
                                	( PAYTYPE IS NULL OR EmergencyName IS NULL, 0, 1 ) AS IsPerfect,
                                IF
                                	( pat.GUARDIAN IS NULL OR pat.GuardianPhone IS NULL OR pat.CERTIFICATE_NUMBER IS NULL, 0, 1 ) AS IsPerfectGuardian 
                                FROM
                                	pub_user_info AS u
                                	INNER JOIN pub_map_user_pat AS map ON map.USER_ID = u.Id
                                	INNER JOIN pub_pat_info AS pat ON pat.Id = map.PAT_ID 
                                WHERE
                                	u.IS_DELETED = FALSE 
                                    AND u.Id=@userId
                                	AND map.IS_DELETED = FALSE 
                                	AND pat.IS_DELETED = FALSE 
                                	AND pat.Id = @patientId
                                ORDER BY pat.CreateTime DESC
                                ";

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

            var result = await QueryAsync<PatientModel>(sql, parms);

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

        /// <summary>
        /// 获取已绑定的家庭成员数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<int> GetFamilyCountAsync(int userId)
        {
            const string sql = @"SELECT
                                 	count(1) 
                                 FROM
                                 	pub_pat_info AS pat
                                 	INNER JOIN pub_map_user_pat AS map ON map.PAT_ID = pat.Id AND (map.RELATION_SHIP = 1 or map.RELATION_SHIP = 2)
                                 WHERE
                                 	USER_ID = @userId 
                                    AND (map.RELATION_SHIP = 1 or map.RELATION_SHIP = 2)
                                 	AND map.IS_DELETED = FALSE 
                                 	AND pat.IS_DELETED = FALSE";

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

            var result = await QueryAsync<int>(sql, parms);
            return result.FirstOrDefault();
        }

        /// <summary>
        /// 家庭成员是否绑定了本人
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> IsBandMyselfAsync(int userId)
        {
            const string sql = @"SELECT
                                 	count( 1 ) 
                                 FROM
                                 	pub_user_info AS u
                                 	INNER JOIN pub_map_user_pat AS map ON u.Id = map.USER_ID 
                                 WHERE
                                 	u.IS_DELETED = FALSE 
                                    AND (map.RELATION_SHIP = 1 or map.RELATION_SHIP = 2)
                                 	AND map.IS_DELETED = FALSE 
                                 	AND map.Ties = 1 
                                 	AND u.Id = @userId";

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

            var result = await QueryAsync<int>(sql, parms);

            return result.FirstOrDefault() > 0;
        }

        /// <summary>
        /// 删除家庭成员
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="patientId"></param>
        /// <returns></returns>
        public async Task DeletePatientAsync(int userId, int patientId)
        {
            const string updateMapSql = "update pub_map_user_pat set IS_DELETED = true, UPDATE_TIME=@updateTime where PAT_ID=@patientId AND USER_ID=@userId and IS_DELETED=false";

            var parms = new Dictionary<string, object>
            {
                {"@userId",userId},
                {"@patientId",patientId},
                {"@updateTime",DateTime.Now}
            };

            await ExecuteAsync(updateMapSql, parms);
        }

    }
}
