using Edu.Common.Enum.User;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Repository.Customer;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;

namespace Edu.Repository.Sell
{
    public class RB_Order_ReturnComissionRepository : BaseRepository<RB_Order_ReturnComission>
    {
        /// <summary>
        /// 员工处理类对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 同业联系人仓储层对象
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();

        /// <summary>
        /// 学员仓储层对象
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();

        /// <summary>
        /// 根据OrderId和StuId查询实体
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="stuid"></param>
        /// <returns></returns>
        public RB_Order_ReturnComission_ViewModel GetModelByOrderIdStuId(int orderid, int stuid)
        {
            var sql = "select * from RB_Order_ReturnComission where OrderId=@oid and StuId=@sid";

            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("oid", orderid);
            parameters.Add("sid", stuid);

            return Get<RB_Order_ReturnComission_ViewModel>(sql, parameters).ToList().FirstOrDefault();
        }

        /// <summary>
        ///   
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetListBySetBatch(int groupId, int type)
        {
            var sql = "select a.* from rb_order_returncomission a left join rb_student_orderguest b on a.OrderId=b.OrderId and a.StuId=b.Student_Id left join rb_order_guest c on b.GuestId=c.Id where (c.CompleteHours/c.TotalHours)>=(a.CommissionReValue/100) and a.`Status`=0 and c.CreateTime<date_add(curdate(),interval -day(curdate())+1 day) and a.GroupId=@gid and a.CommissionType=@type";

            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("gid", groupId);
            parameters.Add("type", type);

            return Get<RB_Order_ReturnComission_ViewModel>(sql, parameters).ToList();
        }

        /// <summary>
        /// 发放佣金，标记主表ID
        /// </summary>
        /// <param name="batchId"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool UpdateModelByBatch(int batchId, string ids)
        {
            var sql = $"update rb_order_returncomission set Status=1,BatchId={batchId} where Id in({ids})";

            return Execute(sql, null) > 0;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetPageList(int pageIndex, int pageSize, out long count, RB_Order_ReturnComission_ViewModel demodel)
        {
            string where = $@" 1=1";

            if (demodel.GroupId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.GroupId)} ={demodel.GroupId}";
            }
            if (demodel.SchoolId >= 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.SchoolId)} ={demodel.SchoolId}";
            }
            if (demodel.BatchId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.BatchId)} ={demodel.BatchId}";
            }
            if (demodel.CommissionType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.CommissionType)} ={demodel.CommissionType}";
            }
            if (demodel.Status > -2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} ={demodel.Status}";
            }
            if (demodel.OrderId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderId)} ={demodel.OrderId}";
            }
            if (demodel.ClassId > 0)
            {
                where += $@" and o.{nameof(RB_Order_ReturnComission_ViewModel.ClassId)} ={demodel.ClassId}";
            }
            if (demodel.OrderSourceType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceType)} ={(int)demodel.OrderSourceType}";
            }
            if (demodel.OrderSourceId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceId)} ={demodel.OrderSourceId}";
            }
            if (demodel.UnionCashOutId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.UnionCashOutId)} ={demodel.UnionCashOutId}";
            }
            if (demodel.Q_SelectNormal == 1)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(0,1,2)";
            }
            else if (demodel.Q_SelectNormal == 2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(1,2)";
            }

            if (demodel.CategoryId > 0)
            {
                where += $@" and cus.{nameof(RB_Order_ReturnComission_ViewModel.CategoryId)}={demodel.CategoryId} ";
            }

            string sql = $@" 
select r.*,b.BatchName,o.ClassId,c.ClassName,c.ClassNo,s.StuName 
from RB_Order_ReturnComission r left join rb_returnmoney_batch b on r.BatchId = b.Id
     left join rb_order o on r.OrderId = o.OrderId
     left join rb_class c on o.ClassId = c.ClassId
     left join rb_student s on s.StuId = r.StuId
     LEFT JOIN rb_customer AS cus ON r.OrderSourceType=2 AND r.OrderSourceId=cus.CustomerId
where {where} order by r.Id desc";
            return GetPage<RB_Order_ReturnComission_ViewModel>(pageIndex, pageSize, out count, sql).ToList();
        }

        /// <summary>
        /// 获取用户返佣列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetCommissionUserList(RB_Order_ReturnComission_ViewModel demodel)
        {
            string where = $@" 1=1";

            if (demodel.GroupId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.GroupId)} ={demodel.GroupId}";
            }
            if (demodel.SchoolId >= 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.SchoolId)} ={demodel.SchoolId}";
            }
            if (demodel.BatchId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.BatchId)} ={demodel.BatchId}";
            }
            if (demodel.CommissionType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.CommissionType)} ={demodel.CommissionType}";
            }
            if (demodel.Status > -2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} ={demodel.Status}";
            }
            if (demodel.OrderId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderId)} ={demodel.OrderId}";
            }
            if (demodel.OrderSourceType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceType)} ={(int)demodel.OrderSourceType}";
            }
            if (demodel.OrderSourceId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceId)} ={demodel.OrderSourceId}";
            }
            if (demodel.Q_SelectNormal == 1)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(0,1,2)";
            }
            else if (demodel.Q_SelectNormal == 2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(1,2)";
            }

            string sql = $@" select r.OrderSourceType,r.OrderSourceId,r.SchoolId,count(0) as StudentCount,sum(r.CommissionMoeny) as CommissionMoeny
from RB_Order_ReturnComission r where {where} group by r.OrderSourceType,r.OrderSourceId,r.SchoolId";
            return Get<RB_Order_ReturnComission_ViewModel>(sql).ToList();
        }

        /// <summary>
        /// 获取累积佣金金额
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetCommissionStatistics(RB_Order_ReturnComission_ViewModel demodel)
        {
            string where = $@" 1=1";

            if (demodel.GroupId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.GroupId)} ={demodel.GroupId}";
            }
            if (demodel.SchoolId >= 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.SchoolId)} ={demodel.SchoolId}";
            }
            if (demodel.BatchId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.BatchId)} ={demodel.BatchId}";
            }
            if (demodel.CommissionType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.CommissionType)} ={demodel.CommissionType}";
            }
            if (demodel.Status > -2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} ={demodel.Status}";
            }
            if (demodel.OrderId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderId)} ={demodel.OrderId}";
            }
            if (demodel.ClassId > 0)
            {
                where += $@" and o.{nameof(RB_Order_ReturnComission_ViewModel.ClassId)} ={demodel.ClassId}";
            }
            if (demodel.OrderSourceType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceType)} ={(int)demodel.OrderSourceType}";
            }
            if (demodel.OrderSourceId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceId)} ={demodel.OrderSourceId}";
            }
            if (demodel.UnionCashOutId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.UnionCashOutId)} ={demodel.UnionCashOutId}";
            }
            if (demodel.Q_SelectNormal == 1)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(0,1,2)";
            }
            else if (demodel.Q_SelectNormal == 2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(1,2)";
            }

            if (demodel.CategoryId > 0)
            {
                where += $@" and cus.{nameof(RB_Order_ReturnComission_ViewModel.CategoryId)} ={demodel.CategoryId}";
            }

            string sql = $@" 
SELECT SUM(r.CommissionMoeny) 
FROM RB_Order_ReturnComission r left join rb_order o on r.OrderId = o.OrderId
     LEFT JOIN rb_customer AS cus ON r.OrderSourceType=2 AND r.OrderSourceId=cus.CustomerId    
WHERE {where}";
            var obj = ExecuteScalar(sql);
            return obj == null ? 0 : Convert.ToDecimal(obj);
        }

        /// <summary>
        /// 更新已提现状态为可提现
        /// </summary>
        /// <param name="group_Id"></param>
        /// <param name="remitId"></param>
        public void UpdateOrderReturnComission(int group_Id, int remitId)
        {
            string sql = $@"update RB_Order_ReturnComission r set r.Status =1
where r.GroupId ={group_Id} and r.UnionCashOutId ={remitId}";
            Execute(sql);
        }

        /// <summary>
        /// 获取订单返佣列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetOrderReturnComissionListRepositpry(RB_Order_ReturnComission_ViewModel query)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.* 
FROM rb_order_returncomission AS A
WHERE 1=1
");
            builder.AppendFormat(" AND A.{0}>=0 ", nameof(RB_Order_ReturnComission_ViewModel.Status));
            if (query != null)
            {
                if (query.OrderId > 0)
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Order_ReturnComission_ViewModel.OrderId), query.OrderId);
                }
                if (!string.IsNullOrEmpty(query.QOrderIds))
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Order_ReturnComission_ViewModel.OrderId), query.QOrderIds);
                }
            }
            var list = Get<RB_Order_ReturnComission_ViewModel>(builder.ToString()).ToList();
            if (list != null && list.Count > 0)
            {
                var employeeIds = string.Join(",", list.Where(qitem => qitem.OrderSourceType == StuCreateTypeEnum.EmployeeInput || qitem.OrderSourceType == StuCreateTypeEnum.InternalIntroduction).Select(qitem => qitem.OrderSourceId));
                var customerIds = string.Join(",", list.Where(qitem => qitem.OrderSourceType == StuCreateTypeEnum.CustomerInput).Select(qitem => qitem.OrderSourceId));
                var stuIds = string.Join(",", list.Where(qitem => qitem.OrderSourceType == StuCreateTypeEnum.TransIntroduction).Select(qitem => qitem.OrderSourceId));
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                List<RB_Customer_Extend> customerList = new List<RB_Customer_Extend>();
                List<RB_Student_ViewModel> stuList = new List<RB_Student_ViewModel>();
                if (!string.IsNullOrEmpty(employeeIds))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = employeeIds });
                }
                if (!string.IsNullOrEmpty(customerIds))
                {
                    customerList = customerRepository.GetCustomerListRepository(new RB_Customer_Extend()
                    {
                        CustomerIds = customerIds
                    });
                }
                if (!string.IsNullOrEmpty(stuIds))
                {
                    stuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel()
                    {
                        StuIds = stuIds
                    });
                }
                foreach (var item in list)
                {
                    switch (item.OrderSourceType)
                    {
                        case StuCreateTypeEnum.EmployeeInput:
                            item.OrderSourceIdName = empList?.FirstOrDefault(qitem => qitem.Id == item.OrderSourceId)?.EmployeeName ?? "";
                            break;
                        case StuCreateTypeEnum.CustomerInput:
                            var tempCustomer = customerList?.FirstOrDefault(qitem => qitem.CustomerId == item.OrderSourceId);
                            string tempStr = tempCustomer?.CustomerName ?? "";
                            if (tempCustomer != null)
                            {
                                if (tempCustomer.CustomerType == Common.Enum.Customer.CatetoryTypeEnum.Other)
                                {
                                    tempStr += string.Format("({0})", tempCustomer?.EnterpriseName ?? "");
                                }
                                else
                                {
                                    tempStr += string.Format("({0})", tempCustomer?.CategoryName ?? "");
                                }
                            }
                            item.OrderSourceIdName = tempStr;
                            break;
                        case StuCreateTypeEnum.InternalIntroduction:
                            item.OrderSourceIdName = empList?.FirstOrDefault(qitem => qitem.Id == item.OrderSourceId)?.EmployeeName ?? "";
                            break;
                        case StuCreateTypeEnum.TransIntroduction:
                            item.OrderSourceIdName = stuList?.FirstOrDefault(qitem => qitem.StuId == item.OrderSourceId)?.StuName ?? "";
                            break;
                    }
                }
            }
            return list;
        }




        /// <summary>
        /// 获取用户返佣列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetCommissionEnterList(RB_Order_ReturnComission_ViewModel demodel)
        {
            string where = $@" 1=1";

            if (demodel.GroupId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.GroupId)} ={demodel.GroupId}";
            }
            if (demodel.SchoolId >= 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.SchoolId)} ={demodel.SchoolId}";
            }
            if (demodel.BatchId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.BatchId)} ={demodel.BatchId}";
            }
            if (demodel.CommissionType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.CommissionType)} ={demodel.CommissionType}";
            }

            if (demodel.EnterID > 0)
            {
                where += $@" and b.EnterID ={demodel.EnterID}";
            }
            if (demodel.Status > -2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} ={demodel.Status}";
            }
            if (demodel.OrderId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderId)} ={demodel.OrderId}";
            }
            if (demodel.UnionCashOutId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.UnionCashOutId)} ={demodel.UnionCashOutId}";
            }
            if (demodel.OrderSourceType > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceType)} ={(int)demodel.OrderSourceType}";
            }
            if (demodel.OrderSourceId > 0)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.OrderSourceId)} ={demodel.OrderSourceId}";
            }
            if (demodel.Q_SelectNormal == 1)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(0,1,2)";
            }
            else if (demodel.Q_SelectNormal == 2)
            {
                where += $@" and r.{nameof(RB_Order_ReturnComission_ViewModel.Status)} in(1,2)";
            }

            string sql = $@"  SELECT r.* from rb_order_returncomission as r LEFT JOIN rb_order as b on r.OrderId=b.OrderId where {where} ";
            return Get<RB_Order_ReturnComission_ViewModel>(sql).ToList();
        }
    }
}
