using Edu.Common.Enum;
using Edu.Model.Entity.Duty;
using Edu.Model.Entity.Reserve;
using Edu.Model.ViewModel.Duty;
using Edu.Model.ViewModel.Reserve;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;

namespace Edu.Repository.Reserve
{
    /// <summary>
    /// 访客约课仓储层
    /// </summary>
    public class RB_Visitor_ReserveRepository : BaseRepository<RB_Visitor_Reserve>
    {
        /// <summary>
        /// 获取访客约课分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReservePageRepository(int pageIndex, int pageSize, out long rowsCount, RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            var parameters = new DynamicParameters();
            builder.Append(@"
SELECT A.*,IFNULL(B.StuName,'') AS VisitorName,C.ClassDate,C.ClassTime,C.EndTime,C.ClassContent,IFNULL(D.TeacherName,'') AS TeacherName,IFNULL(E.RoomName,'') AS RoomName
       ,IFNULL(B.StuTel,'') AS StuTel,IFNULL(F.LessonName,'') AS LessonName,IFNULL(B.QQ,'') AS QQ,IFNULL(B.WeChatNo,'') AS WeChatNo
FROM RB_Visitor_Reserve AS A LEFT JOIN rb_student AS B ON A.Visitor_Id=B.StuId
     LEFT JOIN rb_reserve_class AS C ON A.ReserveClassId=C.ReserveClassId
     LEFT JOIN rb_teacher AS D ON C.TeacherId=D.TId
     LEFT JOIN rb_class_room AS E ON C.ClassRoomId=E.RoomId
	 LEFT JOIN rb_triallesson AS F ON C.TrialLessonId=F.Id
WHERE 1=1 
");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Status), (int)DateStateEnum.Normal);
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Group_Id), query.Group_Id);
                }
                if (!string.IsNullOrEmpty(query.StartClassDate))
                {
                    builder.AppendFormat(" AND C.{0}>='{1}' ", nameof(RB_Visitor_Reserve_Extend.ClassDate), query.StartClassDate);
                }
                if (!string.IsNullOrEmpty(query.EndClassDate))
                {
                    builder.AppendFormat(" AND C.{0}<='{1} 23:59:59' ", nameof(RB_Visitor_Reserve_Extend.ClassDate), query.EndClassDate);
                }
                if (query.TeacherId > 0)
                {
                    builder.AppendFormat(" AND C.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.TeacherId), query.TeacherId);
                }
                if (query.ClassRoomId > 0)
                {
                    builder.AppendFormat(" AND C.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.ClassRoomId), query.ClassRoomId);
                }
                if (!string.IsNullOrEmpty(query.Q_ReserveStatus))
                {
                    Int32.TryParse(query.Q_ReserveStatus, out int result);
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.ReserveStatus), result);
                }
                if (!string.IsNullOrEmpty(query.VisitorName))
                {
                    builder.AppendFormat(" AND B.{0} LIKE @VisitorName ", nameof(RB_Visitor.Name));
                    parameters.Add("VisitorName", "%" + query.VisitorName.Trim() + "%");
                }
                if (query.Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Id), query.Id);
                }
                if (query.CreateBy > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.CreateBy), query.CreateBy);
                }
                if (query.Visitor_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Visitor_Id), query.Visitor_Id);
                }
                if (query.ReserveClassId > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.ReserveClassId), query.ReserveClassId);
                }
            }
            builder.AppendFormat(" ORDER BY A.{0} DESC ", nameof(RB_Visitor_Reserve_Extend.Id));
            return GetPage<RB_Visitor_Reserve_Extend>(pageIndex, pageSize, out rowsCount, builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 获取访客约课列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReserveListRepository(RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            var parameters = new DynamicParameters();
            builder.Append(@"
SELECT A.*,IFNULL(B.StuName,'') AS VisitorName,C.ClassDate,C.ClassTime,C.EndTime,C.ClassContent,IFNULL(D.TeacherName,'') AS TeacherName,IFNULL(E.RoomName,'') AS RoomName
       ,IFNULL(B.StuTel,'') AS StuTel,IFNULL(F.LessonName,'') AS LessonName
FROM RB_Visitor_Reserve AS A LEFT JOIN rb_student AS B ON A.Visitor_Id=B.StuId
     LEFT JOIN rb_reserve_class AS C ON A.ReserveClassId=C.ReserveClassId
     LEFT JOIN rb_teacher AS D ON C.TeacherId=D.TId
     LEFT JOIN rb_class_room AS E ON C.ClassRoomId=E.RoomId
	 LEFT JOIN rb_triallesson AS F ON C.TrialLessonId=F.Id
WHERE 1=1 
");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Status), (int)DateStateEnum.Normal);
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Group_Id), query.Group_Id);
                }
                if (!string.IsNullOrEmpty(query.StartClassDate))
                {
                    builder.AppendFormat(" AND C.{0}>='{1}' ", nameof(RB_Visitor_Reserve_Extend.ClassDate), query.StartClassDate);
                }
                if (!string.IsNullOrEmpty(query.EndClassDate))
                {
                    builder.AppendFormat(" AND C.{0}<='{1} 23:59:59' ", nameof(RB_Visitor_Reserve_Extend.ClassDate), query.EndClassDate);
                }
                if (query.TeacherId > 0)
                {
                    builder.AppendFormat(" AND C.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.TeacherId), query.TeacherId);
                }
                if (query.ClassRoomId > 0)
                {
                    builder.AppendFormat(" AND C.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.ClassRoomId), query.ClassRoomId);
                }
                if (!string.IsNullOrEmpty(query.Q_ReserveStatus))
                {
                    Int32.TryParse(query.Q_ReserveStatus, out int result);
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.ReserveStatus), result);
                }
                if (!string.IsNullOrEmpty(query.StuName))
                {
                    builder.AppendFormat(" AND B.{0} LIKE @StuName ", nameof(RB_Visitor_Reserve_Extend.StuName));
                    parameters.Add("StuName", "%" + query.StuName.Trim() + "%");
                }
            }
            return Get<RB_Visitor_Reserve_Extend>(builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 统计访客约课列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReserveStaticsListRepository(RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            var parameters = new DynamicParameters();
            builder.AppendFormat(" AND A.ReserveStatus!=3 AND A.Status=0 ");
            if (!string.IsNullOrEmpty(query.Q_ReserveClassIds))
            {
                builder.AppendFormat(@" AND A.{0} IN ({1}) ", nameof(RB_Visitor_Reserve_Extend.ReserveClassId), query.Q_ReserveClassIds);
            }
            string sql = string.Format(@"
SELECT A.*,IFNULL(B.StuName,'') AS VisitorName
FROM RB_Visitor_Reserve AS A LEFT JOIN rb_student AS B ON A.Visitor_Id=B.StuId
WHERE 1=1  {0}
", builder.ToString());
            return Get<RB_Visitor_Reserve_Extend>(sql, parameters).ToList();
        }

        /// <summary>
        /// 根据约课信息获取访客列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_ViewModel> GetVisitorRepository(RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            var parameters = new DynamicParameters();
            builder.Append(@"
SELECT B.*
FROM RB_Visitor_Reserve AS A INNER JOIN rb_visitor AS B ON A.Visitor_Id=B.Id
WHERE 1=1 
");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Status), (int)DateStateEnum.Normal);
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Group_Id), query.Group_Id);
                }
                if (query.Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}>='{1}' ", nameof(RB_Visitor_Reserve_Extend.Id), query.Id);
                }
            }
            return Get<RB_Visitor_ViewModel>(builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 检查是否存在此访客的约课信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public bool ExistsVisitorReserveRepository(RB_Visitor_Reserve_Extend query)
        {
            int result = 0;
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT 1
FROM RB_Visitor_Reserve AS A
WHERE 1=1 AND A.Status=0
 ");
            if (query.Visitor_Id > 0)
            {
                builder.AppendFormat(" AND A.Visitor_Id={0} ", query.Visitor_Id);
            }
            if (query.ReserveClassId > 0)
            {
                builder.AppendFormat(" AND A.ReserveClassId={0} ", query.ReserveClassId);
            }
            if (query.Id > 0)
            {
                builder.AppendFormat(" AND A.Id<>{0} ", query.Id);
            }
            var obj = base.ExecuteScalar(builder.ToString());
            if (obj != null)
            {
                Int32.TryParse(obj.ToString(), out result);
            }
            return result > 0;
        }

        /// <summary>
        /// 统计学员约课次数列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetStuReserveStaticsListRepository(RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            var parameters = new DynamicParameters();
            builder.AppendFormat(@"
SELECT A.Visitor_Id,COUNT(1) AS TrialLessonCount
FROM RB_Visitor_Reserve AS A LEFT JOIN rb_student AS B ON A.Visitor_Id=B.StuId
WHERE 1=1 
");
            if (query != null)
            {
                if (!string.IsNullOrEmpty(query.QVisitor_Ids))
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Visitor_Reserve_Extend.Visitor_Id), query.QVisitor_Ids);
                }
            }
            builder.AppendFormat(" GROUP BY A.Visitor_Id ");
 
            return Get<RB_Visitor_Reserve_Extend>(builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 试听课统计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReserveStaticRepository(RB_Visitor_Reserve_Extend query)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.CreateBy,COUNT(1) AS TrialLessonCount,DATE_FORMAT(A.CreateTime,'%Y-%m-%d') AS CreateTime
FROM RB_Visitor_Reserve AS A 
WHERE 1=1
");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Status), (int)DateStateEnum.Normal);
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.Group_Id), query.Group_Id);
                }
                if (query.CreateBy > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Visitor_Reserve_Extend.CreateBy), query.CreateBy);
                }
                if (!string.IsNullOrEmpty(query.QCreateByIds))
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Visitor_Reserve_Extend.CreateBy), query.QCreateByIds);
                }
                if (!string.IsNullOrEmpty(query.QDate))
                {
                    //指定日期的试听课数量
                    builder.AppendFormat(" AND DATE_FORMAT(A.{0},'%y/%m/%d')= DATE_FORMAT('{1}','%y/%m/%d') ", nameof(RB_Visitor_Reserve_Extend.CreateTime), query.QDate);
                }
                if (!string.IsNullOrEmpty(query.StartClassDate))
                {
                    builder.AppendFormat(" AND A.{0}>='{1}' ", nameof(RB_Visitor_Reserve_Extend.CreateTime), query.StartClassDate);
                }
                if (!string.IsNullOrEmpty(query.EndClassDate))
                {
                    builder.AppendFormat(" AND A.{0}<='{1} 23:59:59' ", nameof(RB_Visitor_Reserve_Extend.CreateTime), query.EndClassDate);
                }
            }
            builder.AppendFormat(@" GROUP BY A.CreateBy,DATE_FORMAT(A.CreateTime,'%Y/%m/%d') ");
            builder.AppendFormat(@" ORDER BY A.CreateBy,DATE_FORMAT(A.CreateTime,'%Y/%m/%d') ");
            return Get<RB_Visitor_Reserve_Extend>(builder.ToString()).ToList();
        }

        /// <summary>
        /// 市场课程顾问部统计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public Dictionary<string, List<RB_Visitor_Reserve_Extend>> GetVisitorStaticRepository(RB_Visitor_Reserve_Extend query)
        {
            Dictionary<string, List<RB_Visitor_Reserve_Extend>> dicList = new Dictionary<string, List<RB_Visitor_Reserve_Extend>>();
            string sql = @"
SELECT A.CreateBy,COUNT(1) AS TrialLessonCount
FROM RB_Visitor_Reserve AS A 
WHERE 1=1 AND A.Status=0 {0}
";
            if (query.CreateBy > 0)
            {
                sql += string.Format(@" AND A.CreateBy={0} ", query.CreateBy);
            }
            sql += " GROUP BY A.CreateBy ";
            string todayWhere = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                todayWhere += string.Format(" AND to_days(A.CreateTime)=to_days('{0}') ", query.StartClassDate);
            }
            else
            {
                todayWhere += string.Format(" AND to_days(A.CreateTime)=to_days(now()) ");
            }

            //今日
            var todayList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql.ToString(), todayWhere)).ToList();
            dicList.Add("today", todayList);

            //昨日
            string yesWhere = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                yesWhere += string.Format(" AND TO_DAYS('{0}')-TO_DAYS(A.CreateTime)=1 ", query.StartClassDate);
            }
            else
            {
                yesWhere += string.Format(" AND TO_DAYS(now())-TO_DAYS(A.CreateTime)=1 ");
            }
            var yesList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql, yesWhere)).ToList();
            dicList.Add("yestoday", yesList);

            //本周
            string curWeek = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                curWeek += string.Format(" AND YEARWEEK(date_format(A.CreateTime,'%Y-%m-%d' )) = YEARWEEK('{0}') ", query.StartClassDate);
            }
            else
            {
                curWeek += string.Format(" AND YEARWEEK(date_format(A.CreateTime,'%Y-%m-%d')) = YEARWEEK(now()) ");
            }
            var curWeekList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql, curWeek)).ToList();
            dicList.Add("currentWeek", curWeekList);

            //上周
            string lastWeek = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                lastWeek += string.Format(" AND YEARWEEK(date_format(A.CreateTime,'%Y-%m-%d')) = YEARWEEK('{0}')-1 ", query.StartClassDate);
            }
            else
            {
                lastWeek += string.Format(" AND YEARWEEK(date_format(A.CreateTime,'%Y-%m-%d')) = YEARWEEK(now())-1 ");
            }
            var lastWeekList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql, lastWeek)).ToList();
            dicList.Add("lastWeek", lastWeekList);

            //本月
            string curMonth = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                curMonth += string.Format(" AND DATE_FORMAT(A.CreateTime,'%Y%m')=DATE_FORMAT('{0}','%Y%m') ", query.StartClassDate);
            }
            else
            {
                curMonth += string.Format(" AND DATE_FORMAT(A.CreateTime,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m') ");
            }
            var curMonthList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql, curMonth)).ToList();
            dicList.Add("curMonth", curMonthList);

            //上月
            string lastMonth = "";
            if (!string.IsNullOrEmpty(query.StartClassDate))
            {
                lastMonth += string.Format(" AND PERIOD_DIFF(date_format('{0}','%Y%m'),date_format(A.CreateTime,'%Y%m')) =1 ", query.StartClassDate);
            }
            else
            {
                lastMonth += string.Format(" AND PERIOD_DIFF(date_format(now(),'%Y%m'),date_format(A.CreateTime,'%Y%m')) =1 ");
            }
            var lastMonthList = Get<RB_Visitor_Reserve_Extend>(string.Format(sql, lastMonth)).ToList();
            dicList.Add("lastMonth", lastMonthList);
            return dicList;
        }
    }
}
