using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ASHermed.AdminInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.App.Model;
using ASHermed.SinoInterface.Api.ContractModel.Quest;
using ASHermed.SinoInterface.Api.IRepository.Quest;
using ASHermed.SinoInterface.Repository.MySql;
using ASHermed.SinoInterface.Tools;

namespace ASHermed.SinoInterface.Api.MySqlRepository.Quest
{
    public class PubQuestInfoRepository : BaseRepositoryToASHermed_SinoInterface<Pub_Quest_Info>, IPubQuestInfoRepository
    {
        /// <summary>
        /// 新增一条，返回id
        /// </summary>
        /// <param name="questInfo"></param>
        /// <returns></returns>
        public async Task<int> InsertAnReturnIdAsync(Pub_Quest_Info questInfo)
        {
            const string sql = @"INSERT INTO pub_quest_info (
                                	`Name`,
                                	NameEN,
                                	NameGE,
                                	`Describe`,
                                	DescribeEN,
                                	DescribeGE,
                                	`Explain`,
                                	ExplainEN,
                                	ExplainGE,
                                	IsDelete,
                                    CreateTime,
                                    CreateUser,
                                    Config, UpdateTime, UpdateUser , Version 
                                )
                                VALUES
                                	(
                                		@Name,
                                		@NameEN,
                                		@NameGE,
                                		@DESCRIBE,
                                		@DescribeEN,
                                		@DescribeGE,
                                		@EXPLAIN,
                                		@ExplainEN,
                                		@ExplainGE,
                                		@IsDelete,
                                        @CreateTime,
                                        @CreateUser,
                                        @Config ,@UpdateTime, @UpdateUser , @Version 
                                	)";

            return await InsertAsync(sql, questInfo);
        }

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Pub_Quest_Info> GetByIdAsync(int id)
        {
            var sqlQueryBuilder = new StringBuilder();
            sqlQueryBuilder.Append("select * from pub_quest_info where IsDelete=false and Id=@id ");

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

            var sql = sqlQueryBuilder.ToString();
            var result = await QueryAsync<Pub_Quest_Info>(sql, parms);

            return result?.FirstOrDefault();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<Pub_Quest_Info>> GetAllListAsync()
        {
            var sqlQueryBuilder = new StringBuilder();
            sqlQueryBuilder.Append("select * from pub_quest_info where IsDelete=false ");

            //TODO:添加查询条件和参数
            //sqlQueryBuilder.Append("  ");
            //var parms = new Dictionary<string, object>
            //{

            //};

            var sql = sqlQueryBuilder.ToString();
            var result = await QueryAsync<Pub_Quest_Info>(sql/*,parms*/);

            return result?.ToList();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageListModel<Pub_Quest_Info>> GetPageListAsync(int pageIndex, int pageSize)
        {
            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append("select SQL_CALC_FOUND_ROWS * from pub_quest_info where 1=1 ");

            //TODO:添加查询条件

            sqlBuilder.Append(" LIMIT @pageIndex,@pageSize ");

            var parms = new Dictionary<string, object>
            {
                {"@pageIndex", (pageIndex-1)*pageSize},
                {"@pageSize", pageSize},
                //TODO:添加查询条件参数
            };

            var (data, count) = await QueryPageListAsync<Pub_Quest_Info>(sqlBuilder.ToString(), "select FOUND_ROWS() AS Count", parms);

            return new PageListModel<Pub_Quest_Info>
            {
                TotalCount = (int)count,
                PageList = data?.ToList()
            };
        }

        public async Task<int> InsertConfig(Pub_Quest_Config config)
        {
            var sql = @" INSERT INTO pub_quest_config ( HosId,HosName,DeptId,DeptName,InfoId )
                                VALUES
                                	(@HosId,@HosName,@DeptId,@DeptName,@InfoId ) ";
            return await InsertAsync(sql, config);
        }

        public async Task<Pub_Quest_Config> GetConfig(int infoId)
        {
            var sql = @" select * from pub_quest_config where InfoId = @InfoId ";
            var result = await QueryAsync<Pub_Quest_Config>(sql, new { InfoId = infoId });
            return result.FirstOrDefault();
        }

        public async Task<List<QuestPat>> GetQuestPat(string phone)
        {
            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`,
	                            a.Id AS OutAptId , 
                                a.Id AS OutAptId 
                            FROM
	                            out_apt_info a
	                            INNER JOIN pub_pat_info b ON a.PAT_ID = b.ID 
                            WHERE
	                            Service = 'CON75' AND a.APT_TIME > @AptTime
	                            AND (b.PHONE_NO = @Phone OR b.PHONE_NO = @PhoneEnc ) 
	                            AND b.PAT_MRN IS NOT NULL 
	                            AND b.PAT_MRN != '' ";
            var result = await QueryAsync<QuestPat>(sql, new { AptTime = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd") + " 00:00:01"), Phone = phone, PhoneEnc = phone.Encrypt() });
            return result.ToList().DeEncrypt();
        }

        public async Task<int> UpdateInfo(Pub_Quest_Info info)
        {
            var sql = @" UPDATE `pub_quest_info` SET `Name` = @Name, `NameEN` = @NameEN, `NameGE` = @NameGE, `Describe` = @Describe, `DescribeEN` = @DescribeEN, `DescribeGE` = @DescribeGE, `Explain` = @Explain, `ExplainEN` = @ExplainEN, `ExplainGE` = @ExplainGE, `IsDelete` = @IsDelete, `CreateTime` = @CreateTime, `CreateUser` = @CreateUser, `Config` = @Config, `UpdateTime` = @UpdateTime, `UpdateUser` = @UpdateUser, `Version` = @Version WHERE `Id` = @Id ";
            return Execute(sql, info);
        }
    }
}
