using Edu.Common.Enum.Course;
using Edu.Model.Entity.BackClass;
using Edu.Model.Entity.EduTask;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.BackClass;
using Edu.Model.ViewModel.Contract;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.Sell;
using Edu.Repository.Contract;
using Edu.Repository.EduTask;
using Edu.Repository.Sell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;
using VT.FW.DB.Dapper;

namespace Edu.Repository.BackClass
{
    /// <summary>
    /// 学员退课单据仓储层
    /// </summary>
    public class RB_Student_BackClassRepository : BaseRepository<RB_Student_BackClass>
    {
        /// <summary>
        /// 订单学员仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 订单仓储层对象
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

        /// <summary>
        /// 订单转班仓储层对象
        /// </summary>
        private readonly RB_Order_ChangeRepository order_ChangeRepository = new RB_Order_ChangeRepository();

        /// <summary>
        /// 退课协议仓储层对象
        /// </summary>
        private readonly RB_BackClass_ProtocolRepository backClass_ProtocolRepository = new RB_BackClass_ProtocolRepository();

        /// <summary>
        /// 获取学员退课单据列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_BackClass_ViewModel> GetStudentBackClassListRepository(RB_Student_BackClass_ViewModel query)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.*,IFNULL(B.GuestName,'') AS GuestName,ec.ContractNo,ec.Id as ContractId,IFNULL(C.SName,'') AS SchoolName,IFNULL(D.ClassName,'') AS ClassName,IFNULL(T.TeacherName,'') AS TeacherName
      ,IFNULL(E.EnterID,0) AS EnterID,IFNULL(F.CourseName,'') AS CourseName,D.ClassNo,B.TotalHours,B.CompleteHours,IFNULL(G.Id,0) AS BackClassProtocolId,IFNULL(G.ProtocolNum,'') AS ProtocolNum
FROM RB_Student_BackClass AS A LEFT JOIN rb_order_guest AS B ON A.GuestId=B.Id
     LEFT JOIN rb_education_contract ec on B.Id = ec.GuestId and ec.Status <>4
     LEFT JOIN rb_class AS D ON A.ClassId=D.ClassId
     LEFT JOIN rb_school AS C ON D.School_Id=C.SId
     LEFT JOIN (SELECT account.Id,teac.TeacherName FROM rb_account AS account INNER JOIN rb_teacher AS teac ON account.AccountId=teac.TId AND account.AccountType=2)
               AS T ON A.TeacherId=T.Id
     LEFT JOIN rb_order AS E ON A.OrderId=E.OrderId
     LEFT JOIN rb_course AS F ON D.CouseId=F.CourseId
     LEFT JOIN rb_backclass_protocol AS G ON A.BackId=G.BackId
WHERE 1=1   ");
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(@" AND A.{0}={1} ", nameof(RB_Student_BackClass_ViewModel.Group_Id), query.Group_Id);
                }
                if (!string.IsNullOrEmpty(query.QBackIds))
                {
                    builder.AppendFormat(@" AND A.{0} IN({1}) ", nameof(RB_Student_BackClass_ViewModel.BackId), query.QBackIds);
                }
            }
            return Get<RB_Student_BackClass_ViewModel>(builder.ToString()).ToList();
        }

        /// <summary>
        /// 获取总退课条数
        /// </summary>
        /// <returns></returns>
        public int GetStudentBackClassNumRepository()
        {
            int result = 0;
            string sql = "SELECT COUNT(1) FROM RB_Student_BackClass ";
            var obj = base.ExecuteScalar(sql);
            if (obj != null)
            {
                Int32.TryParse(obj.ToString(), out result);
            }
            return result + 1;
        }

        /// <summary>
        /// 更新退课相关信息
        /// </summary>
        /// <param name="receiptModel"></param>
        /// <param name="auditModel"></param>
        /// <returns></returns>
        public bool UpdateStudentBackClassRepository(RB_Education_Receipt receiptModel, EduReceiptAudit auditModel)
        {
            var backModel = base.GetEntity(receiptModel.RelationId);
            Dictionary<string, object> backFileds = new Dictionary<string, object>()
            {
               {nameof(RB_Student_BackClass_ViewModel.AuditStatus),auditModel.AuditStatus }
            };
            //退课协议审核状态
            Dictionary<string, object> backprotocolFileds = new Dictionary<string, object>()
            {
               {nameof(RB_BackClass_Protocol_ViewModel.AuditStatus),auditModel.AuditStatus }
            };
            if (!string.IsNullOrEmpty(auditModel.RecipientIds))
            {
                backFileds.Add(nameof(RB_Student_BackClass_ViewModel.RecipientIds), auditModel.RecipientIds);
            }
            //特殊节点更新时间退课金额
            if (auditModel.SpecialNode == 1)
            {
                backFileds.Add(nameof(RB_Student_BackClass_ViewModel.RealityBackMoney), auditModel.BackMoney);
            }
            bool flag = base.Update(backFileds, new WhereHelper(nameof(RB_Student_BackClass_ViewModel.BackId), backModel.BackId));
            if (flag)
            {
                if (auditModel.AuditStatus == 2)
                {
                    //审核通过自动盖章
                    backprotocolFileds.Add(nameof(RB_BackClass_Protocol_ViewModel.IsCompanySeal), 1);
                    backprotocolFileds.Add(nameof(RB_BackClass_Protocol_ViewModel.PartyBSignDate), DateTime.Now);
                }
                //更新退课协议审核状态
                flag = backClass_ProtocolRepository.Update(backprotocolFileds, new WhereHelper(nameof(RB_BackClass_Protocol_ViewModel.BackId), backModel.BackId));
            }
            if (flag)
            {
                var guestList = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { OrderId = backModel.OrderId });
                if (guestList != null && guestList.Where(qitem => qitem.GuestState == GuestStateEnum.DropOut).Count() == guestList.Count())
                {
                    //更新订单为退学状态
                    Dictionary<string, object> orderFileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Order.OrderState),OrderStateEnum.DropOut }
                    };
                    flag = orderRepository.Update(orderFileds, new WhereHelper(nameof(RB_Order.OrderId), backModel.OrderId));
                }
            }
            if (flag)
            {
                int GuestState = 0;
                if (auditModel.AuditStatus == 2)
                {
                    GuestState = 2;
                }
                if (auditModel.AuditStatus == 3)
                {
                    GuestState = 4;
                }
                ///更新学员退课状态
                Dictionary<string, object> guestFileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Order_Guest_ViewModel.GuestState),GuestState }
                };
                flag = order_GuestRepository.Update(guestFileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), backModel.GuestId));
            }
            return flag;
        }


        /// <summary>
        /// 更新退课相关信息
        /// </summary>
        /// <param name="receiptModel"></param>
        /// <param name="auditModel"></param>
        /// <returns></returns>
        public bool UpdateGuestStateRepository(RB_Education_Receipt receiptModel, EduReceiptAudit auditModel)
        {
            bool flag = false;
            var model = order_ChangeRepository.GetEntity(receiptModel.RelationId);
            int GuestState = 0;
            if (auditModel.AuditStatus == 2)
            {
                GuestState = 7;
            }
            if (auditModel.AuditStatus == 3)
            {
                GuestState = 4;
            }
            ///更新学员退课状态
            Dictionary<string, object> guestFileds = new Dictionary<string, object>()
            {
                {nameof(RB_Order_Guest_ViewModel.GuestState),GuestState }
            };
            flag = order_GuestRepository.Update(guestFileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), model.OrderGuestId));
            return flag;
        }


        /// <summary>
        /// 根据学生id获取学生的退课合同信息
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Student_BackClass_ViewModel> GetStudentBackClassInfo(int Student_Id, int Group_Id)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat($@"SELECT sbc.*,bcp.ProtocolNum,bcp.Id as  BackClassProtocolId ,bcp.IsCompanySeal from rb_student_backclass as sbc 
LEFT JOIN rb_backclass_protocol as bcp on sbc.BackId=bcp.BackId
LEFT JOIN rb_student_orderguest as sog on sog.GuestId=sbc.GuestId
where bcp.AuditStatus=2  and sog.Student_Id={Student_Id}  and sbc.Group_Id={Group_Id}");
            return Get<RB_Student_BackClass_ViewModel>(builder.ToString(), parameters).ToList();
        }
    }
}