using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Online.Param;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Repository.MySql;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{
    public class OnlineAptInfoRepository : BaseRepositoryToASHermed_SinoInterface<Online_Apt_Info>, IOnlineAptInfoRepository
    {
        public int InsertOnlineApt(OnlineAptParam param)
        {
            var sql = @" INSERT INTO online_apt_info(EpisodeId, PatId, HosId, DeptId, DocId, AptTime, AptType, AptProj, Status, InnerStatus, DisposeTime, AptUsrn, Remark, ApplyUserId, CreateTime, UpdateTime, SourceType, MatchCode, PayStatus, PayPrice, Description, DescImage, IsDeleted) value (@EpisodeId, @PatId, @HosId, @DeptId, @DocId, @AptTime, @AptType, @AptProj, @Status, @InnerStatus, @DisposeTime, @AptUsrn, @Remark, @ApplyUserId, @CreateTime, @UpdateTime, @SourceType, @MatchCode, @PayStatus, @PayPrice, @Description, @DescImage, @IsDeleted)";
            return this.Insert(sql, param);
        }

        public AptInfoModel GetAptInfoById(int aptId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.DeptId,d.CN_NAME as DeptName,a.Description,a.DocId,doc.CN_NAME  as DocName,hd.HisDoctorDrugCode as docCode,a.DescImage,AptTime 
                                    from online_apt_info a 
                                    LEFT JOIN dic_dept d on a.DeptId = d.ID 
                                    LEFT JOIN dic_doctor doc on doc.ID=a.DocId 
                                    LEFT JOIN dic_map_his_doctor hd on hd.APT_DOCTOR_ID =a.DocId  
                                    where a.Id = @Id and a.IsDeleted =0");

            parms.Add("@Id", aptId);
            var result = Query<AptInfoModel>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }
        public Online_Apt_Info GetAptInfo(int aptId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_apt_info 
                                    where Id = @Id and IsDeleted =0");

            parms.Add("@Id", aptId);
            var result = Query<Online_Apt_Info>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }
        public int UpdateAptStatus(int aptId, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update online_apt_info set ");
            str.Append(@"Status=@Status");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();
            parms.Add("@Status", status);
            parms.Add("@ID", aptId);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdateAptInnerStatus(int aptId, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update online_apt_info set ");
            str.Append(@"InnerStatus=@InnerStatus");
            str.Append(@" where ID=@ID");
            var parms = new Dictionary<string, object>();
            parms.Add("@InnerStatus", status);
            parms.Add("@ID", aptId);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public List<GetMyOnlineApt> GetMyOnlineApt(int userid, int type, int language)
        {
            StringBuilder str = new StringBuilder();
            str.Append(@"SELECT
	                            a.Id,
	                            a.PatId,
	                            a.AptTime,
	                            a.`Status`,
	                            a.AptType,
                                a.LinKingAptStatus,
	                            b.OrderNo,");
            if (language == 1)
            {
                str.Append(@"c.CN_NAME AS DocName,");
            }
            else
            {
                str.Append(@"c.EN_NAME AS DocName,");
            }
            str.Append(@"c.LIST_IMAGE AS ListImage,
	                            c.DETAIL_IMAGE AS DetailImage,
	                            d.PAT_NAME AS PatName,
	                            d.PAT_MRN AS Mrn,
                                gr.GroupId
                               
                            FROM
                                online_apt_info a
	                            INNER JOIN online_order b ON a.id = b.AptId 
	                            AND ( b.AptType = 1 OR b.AptType = 2 )
	                            LEFT JOIN dic_doctor c ON c.id = a.DocId 
	                            LEFT JOIN pub_pat_info d ON d.ID = a.PatId
                               -- LEFT JOIN pub_map_user_pat up on d.id=up.pat_id and up.IS_DELETED = 0 and up.USER_ID =a.ApplyUserId
                                LEFT JOIN tencent_group_record gr on gr.PatId=a.PatId and gr.DocId = a.DocId and gr.UserId = a.ApplyUserId
                            WHERE
	                            (a.`Status` = 2 OR a.`Status` = 4 OR a.`Status` = 5 OR a.`Status` = 6 OR (a.`Status` = 1 AND b.OrderStatus !=1 ) ) AND a.AptType=@AptType 
	                            and a.ApplyUserId = @UserId AND a.PatId IN ( SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @UserId  and IS_DELETED = 0) ORDER BY a.AptTime desc");
            return Query<GetMyOnlineApt>(str.ToString(), new { UserId = userid, AptType = type }).ToList();
        }

        public List<GetMyOnlineAptNew> GetMyOnlineAptNew(int userid)
        {
            var sql = @"(SELECT
	                    a.ID AS AptId,
	                    a.AptTime AS AptTime,
	                    a.PatId,
	                    a.AptType,
                        a.DocId,
	                    a.`Status`
                        ,(select IsReadByVideo from pub_user_info where Id=@UserId  limit 0,1) IsRead
                    FROM
	                    online_apt_info a
	                    INNER JOIN online_order b ON a.id = b.AptId
	                    WHERE a.`Status` IN (2,4,6)  AND a.AptType = 1
                        AND a.PatId IN ( SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @UserId )
	                    ORDER BY a.TriggerSortTime DESC LIMIT 0,1)
	                    UNION
	                    (SELECT
	                    a.ID AS AptId,
	                    a.AptTime AS AptTime,
	                    a.PatId,
	                    a.AptType,
                        a.DocId,
	                    a.`Status`
                        ,(select IsReadByVisit from pub_user_info where Id=@UserId  limit 0,1) IsRead
                    FROM
	                    online_apt_info a
	                    INNER JOIN online_order b ON a.id = b.AptId
	                    WHERE a.`Status` IN (2,4,6)  AND a.AptType = 2
                        AND a.PatId IN ( SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @UserId )
	                    ORDER BY a.TriggerSortTime DESC LIMIT 0,1)";
            return Query<GetMyOnlineAptNew>(sql, new { UserId = userid }).ToList();
        }

        /// <summary>
        /// 修改用户是否已读
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isRead"></param>
        /// <returns></returns>
        public bool UpdatePubUserInfoIsRead(int userId,bool isRead,int type)
        {
            var stringBuilder = new StringBuilder();
            var parms = new Dictionary<string, object>();
            if (type == 1)  //视频问诊
            {
                stringBuilder.Append(@"update pub_user_info set IsReadByVideo=@IsReadByVideo where ID=@id ");
                parms.Add("@IsReadByVideo", isRead);
            }
            else  //复诊开药
            {
                stringBuilder.Append(@"update pub_user_info set IsReadByVisit=@IsReadByVisit where ID=@id ");
                parms.Add("@IsReadByVisit", isRead);
            }
            parms.Add("@id", userId);
            var result = Execute(stringBuilder.ToString(), parms) > 0 ? true : false;
            return result;
        }

        public List<GetMyOnlineApt> GetMyOnlineVideoApt(int userid, int type, int language)
        {
            StringBuilder str = new StringBuilder();
            str.Append(@"SELECT
	                            a.Id,
	                            a.PatId,
	                            a.AptTime,
	                            a.`Status`,
	                            a.AptType,
	                            b.OrderNo,");
            if (language == 1)
            {
                str.Append(@"c.CN_NAME AS DocName,");
            }
            else
            {
                str.Append(@"c.EN_NAME AS DocName,");
            }
            str.Append(@"c.LIST_IMAGE AS ListImage,
	                            c.DETAIL_IMAGE AS DetailImage,
                                c.ID as DocId,
	                            d.PAT_NAME AS PatName,
	                            d.PAT_MRN AS Mrn,
                                gr.GroupId
                            FROM
                                tencent_group_record gr
	                            LEFT JOIN online_order b ON gr.orderNo = b.orderNo 
                                LEFT JOIN online_apt_info a on a.id=b.aptid
	                            AND ( b.AptType = 1 OR b.AptType = 2 ) and a.ApplyUserId=gr.UserId
	                            LEFT JOIN dic_doctor c ON c.id = a.DocId 
	                            LEFT JOIN pub_pat_info d ON d.ID = a.PatId
                            WHERE
	                            (a.`Status` = 2 OR a.`Status` = 4 OR a.`Status` = 5 OR a.`Status` = 6 OR (a.`Status` = 1 AND b.OrderStatus !=1 ) ) AND a.AptType=@AptType 
                                 and a.ApplyUserId = @UserId AND a.PatId IN ( SELECT PAT_ID FROM pub_map_user_pat WHERE USER_ID = @UserId and IS_DELETED = 0)");
            return Query<GetMyOnlineApt>(str.ToString(), new { UserId = userid, AptType = type }).ToList();
        }

        public string GetAptUsrn(int aptId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select AptUsrn from online_apt_info
                                    where Id = @Id and IsDeleted =0");

            parms.Add("@Id", aptId);
            var result = Query<string>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public List<Online_Apt_Info> GetAptLockUsrnList(int patId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"SELECT
	                                a.*
                                FROM
	                                online_apt_info a 
	                                INNER JOIN online_order b ON a.ID = b.AptId
                                WHERE
	                                b.PatId = @PatId 
	                                AND a.IsDeleted = 0 
	                                AND b.OrderStatus IN ( 1, 2, 3, 9, 10 )");

            parms.Add("@PatId", patId);
            var result = Query<Online_Apt_Info>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        public List<TreatedInfo> GetReadyApt(List<int> patIds, int userid)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.ID,a.`Status`,a.DocId,a.DeptId,o.isenglish,a.AptTime as  SeeDoctorTime,p.PAT_NAME as PatName,o.orderNo,a.AptType, a.LinKingAptStatus 
                                from online_apt_info a left join pub_pat_info p on a.PatId = p.ID
                                left join online_order o on a.ID = o.AptId
                            where a.`status` in (1,2,4,6) and a.PatId in @PatIds and a.ApplyUserId =@userId ");

            parms.Add("@PatIds", patIds);
            parms.Add("@userId", userid);
            var result = Query<TreatedInfo>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        public List<TreatedInfo> GetCignaApt(int userId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.ID,a.`Status`,a.DocId,a.DeptId,o.isenglish,a.AptTime as  SeeDoctorTime,p.PAT_NAME as PatName,o.orderNo,a.AptType, a.LinKingAptStatus 
                                from online_apt_info a left join pub_pat_info p on a.PatId = p.ID
                                left join online_order o on a.ID = o.AptId
                            where o.OrderStatus=10 and a.`Status` in (2,6) and a.PatId in (select PAT_ID from pub_map_user_pat where USER_ID = @userId and IS_DELETED=0)");

            parms.Add("@userId", userId);
            var result = Query<TreatedInfo>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        /// <summary>
        /// job云诊室结束后，24小时，患者禁言
        /// </summary>
        /// <returns></returns>
        public List<Tencent_Group_Record> GetForbiddenGroup()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from tencent_group_record where IsNeedForbidden =1 and  TIMESTAMPDIFF(HOUR, OverTime, now()) > 24 ");
            var result = Query<Tencent_Group_Record>(selectSql.ToString(), parms);
            return result?.ToList();
        }

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


        /// <summary>
        /// job获取预约时间距现在15分钟内的预约单  发短信给患者
        /// </summary>
        /// <returns></returns>
        public List<OnlineAptInfoModel> GetAptTimeCond()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.*,b.IsEnglish,b.orderno,b.IsInsuranceUser from online_apt_info a inner join online_order b on a.Id = b.AptId where (`STATUS` = 4 or `STATUS` = 2) and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) > 0 and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) <= 15");
            var result = Query<OnlineAptInfoModel>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        /// <summary>
        /// job获取预约时间距现在5分钟内的预约单 发短信给医生
        /// </summary>
        /// <returns></returns>
        public List<OnlineAptInfoModel> GetAptTimeForDoc()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.*,b.IsEnglish,b.orderNo,b.IsInsuranceUser from online_apt_info a inner join online_order b on a.Id = b.AptId where (`STATUS` = 4 or `STATUS` = 2) and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) > 4 and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) <= 6 ");
            var result = Query<OnlineAptInfoModel>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        /// <summary>
        /// job就诊时间后5分钟后未接诊 短信提示医生医助
        /// </summary>
        /// <returns></returns>
        public List<OnlineAptInfoModel> GetAptTimeAfertCond()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select a.*,b.IsEnglish,b.orderNo,b.IsInsuranceUser from online_apt_info a inner join online_order b on a.Id = b.AptId where (`STATUS` = 4 or `STATUS` = 2) and TIMESTAMPDIFF(MINUTE, a.AptTime, now()) > 3 and TIMESTAMPDIFF(MINUTE, a.AptTime, now()) <= 5");
            //selectSql.Append(@"select a.*,b.IsEnglish,b.orderNo from online_apt_info a inner join online_order b on a.Id = b.AptId where a.id = 210");
            var result = Query<OnlineAptInfoModel>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        public Pub_User_Info GetUserByPatId(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)  and IS_DELETED = false";
            var result = Query<Pub_User_Info>(selectSql, parms);
            return result?.FirstOrDefault();
        }


        public List<Online_Apt_Info> GetAptInfoForUsrn(string usrn)
        {
            var sql = @" Select * from online_apt_info Where `AptUsrn`=@AptUsrn and `Status` != 3 ";
            return Query<Online_Apt_Info>(sql, new { AptUsrn = usrn }).ToList();
        }

        public int GetTodayAptCountByDept(int deptId, string date)
        {
            var selectSql = new StringBuilder();
            var endDate = Convert.ToDateTime(date).AddDays(1);
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select count(*) from online_apt_info where `STATUS` != 3 and DeptId = @deptId and AptTime > @sDate and AptTime < @endDate");//取所有占号的单子
            parms.Add("@deptId", deptId);
            parms.Add("@sDate", date);
            parms.Add("@endDate", endDate);
            var result = Query<int>(selectSql.ToString(), parms);
            return result.FirstOrDefault();
        }

    }
}
