using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Customer;
using Edu.Repository.Finance;
using Edu.Repository.Grade;
using Edu.Repository.Log;
using Edu.Repository.Sell;
using Edu.Repository.StudyAbroad;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 返佣存折处理类
    /// </summary>
    public class CustomerCommissionModule
    {
        /// <summary>
        /// 返佣周期
        /// </summary>
        private readonly RB_ReturnMoney_BatchRepository returnMoney_BatchRepository = new RB_ReturnMoney_BatchRepository();
        /// <summary>
        /// 返佣明细
        /// </summary>
        private readonly RB_Order_ReturnComissionRepository order_ReturnComissionRepository = new RB_Order_ReturnComissionRepository();
        /// <summary>
        /// 用户返佣
        /// </summary>
        private readonly RB_User_ReturnComissionRepository user_ReturnComissionRepository = new RB_User_ReturnComissionRepository();
        /// <summary>
        /// 同行
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();
        /// <summary>
        /// 学生
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();
        /// <summary>
        /// 订单学生
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();
        /// <summary>
        /// 签到
        /// </summary>
        private readonly RB_Class_CheckRepository class_CheckRepository = new RB_Class_CheckRepository();
        /// <summary>
        /// 班级
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();
        /// <summary>
        /// 课程
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();
        /// <summary>
        /// 班级类型
        /// </summary>
        private readonly RB_Class_TypeRepository class_TypeRepository = new RB_Class_TypeRepository();
        /// <summary>
        /// 账户
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 部门
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 校区
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();
        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();

        private readonly RB_Customer_RemitRepository customer_RemitRepository = new RB_Customer_RemitRepository();
        #region 首页返佣
        /// <summary>
        /// 获取首页返佣同级
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetCenterCommissionStatistics(UserInfo userInfo)
        {
            var model = user_ReturnComissionRepository.GetCenterCommissionStatistics(userInfo.Group_Id, userInfo.Id);
            return new
            {
                model?.UnSettlementMoney,
                model?.SttlementMoney,
                model?.CashOutMoney,
                model?.CanCashOutMoney
            };
        }
        #endregion

        #region 返佣存折列表
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_ReturnMoney_Batch_ViewModel> GetCommissionPeriodsList(RB_ReturnMoney_Batch_ViewModel dmodel)
        {
            return returnMoney_BatchRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取佣金期数分页类别
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_ReturnMoney_Batch_ViewModel> GetCommissionPeriodsPageList(int pageIndex, int pageSize, out long count, RB_ReturnMoney_Batch_ViewModel dmodel)
        {
            var list = returnMoney_BatchRepository.GetPageList(pageIndex, pageSize, out count, dmodel.CommissionType, dmodel.Month, dmodel.GroupId);
            return list;
        }

        /// <summary>
        /// 获取用户提成列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetCommissionUserList(RB_Order_ReturnComission_ViewModel dmodel)
        {
            var list = order_ReturnComissionRepository.GetCommissionUserList(dmodel);
            if (list.Any())
            {
                //分成三个部门  内部人员  同行  学员
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput || x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.InternalIntroduction).Select(x => x.OrderSourceId).Distinct());
                string customerIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.CustomerInput).Select(x => x.OrderSourceId).Distinct());
                string stuIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.TransIntroduction).Select(x => x.OrderSourceId).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.SchoolId).Distinct());
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.GroupId, QSIds = schoolIds });
                List<Employee_ViewModel> ulist = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(userIds))
                {
                    ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.GroupId, QIds = userIds });
                }
                List<RB_Customer_Extend> clist = new List<RB_Customer_Extend>();
                if (!string.IsNullOrEmpty(customerIds))
                {
                    clist = customerRepository.GetCustomerListRepository(new RB_Customer_Extend() { Group_Id = dmodel.GroupId, CustomerIds = customerIds });
                }
                List<RB_Student_ViewModel> stulist = new List<RB_Student_ViewModel>();
                if (!string.IsNullOrEmpty(stuIds))
                {
                    stulist = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = dmodel.GroupId, StuIds = stuIds });
                }

                foreach (var item in list)
                {
                    item.SchoolName = slist.Where(x => x.SId == item.SchoolId).FirstOrDefault()?.SName ?? "";
                    if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput || item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.InternalIntroduction)
                    {
                        var umodel = ulist.Where(x => x.Id == item.OrderSourceId).FirstOrDefault();
                        item.UserDept = umodel.Dept_Id;
                        item.UserDeptName = umodel.DeptName;
                        item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    }
                    else if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.CustomerInput)
                    {
                        item.UserName = clist.Where(x => x.CustomerId == item.OrderSourceId).FirstOrDefault()?.CustomerName ?? "";
                    }
                    else if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.TransIntroduction)
                    {
                        item.UserName = stulist.Where(x => x.StuId == item.OrderSourceId).FirstOrDefault()?.StuName ?? "";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取返佣统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetCommissionStatisticsPageList(int pageIndex, int pageSize, out long count, RB_Order_ReturnComission_ViewModel dmodel)
        {
            var list = order_ReturnComissionRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput || x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.InternalIntroduction).Select(x => x.OrderSourceId).Distinct());
                string customerIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.CustomerInput).Select(x => x.OrderSourceId).Distinct());
                string stuIds = string.Join(",", list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.TransIntroduction).Select(x => x.OrderSourceId).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.SchoolId).Distinct());
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.GroupId, QSIds = schoolIds });
                List<Employee_ViewModel> ulist = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(userIds))
                {
                    ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.GroupId, QIds = userIds });
                }
                List<RB_Customer_Extend> clist = new List<RB_Customer_Extend>();
                if (!string.IsNullOrEmpty(customerIds))
                {
                    clist = customerRepository.GetCustomerListRepository(new RB_Customer_Extend() { Group_Id = dmodel.GroupId, CustomerIds = customerIds });
                }
                List<RB_Student_ViewModel> stulist = new List<RB_Student_ViewModel>();
                if (!string.IsNullOrEmpty(stuIds))
                {
                    stulist = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = dmodel.GroupId, StuIds = stuIds });
                }

                foreach (var item in list)
                {
                    item.SchoolName = slist.Where(x => x.SId == item.SchoolId).FirstOrDefault()?.SName ?? "";
                    if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput || item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.InternalIntroduction)
                    {
                        var umodel = ulist.Where(x => x.Id == item.OrderSourceId).FirstOrDefault();
                        item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    }
                    else if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.CustomerInput)
                    {
                        item.UserName = clist.Where(x => x.CustomerId == item.OrderSourceId).FirstOrDefault()?.CustomerName ?? "";
                    }
                    else if (item.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.TransIntroduction)
                    {
                        item.UserName = stulist.Where(x => x.StuId == item.OrderSourceId).FirstOrDefault()?.StuName ?? "";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 累计佣金金额统计
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetCommissionStatistics(RB_Order_ReturnComission_ViewModel dmodel)
        {
            return order_ReturnComissionRepository.GetCommissionStatistics(dmodel);
        }

        /// <summary>
        /// 获取返佣/存折统计
        /// </summary>
        /// <param name="orderSourceType"></param>
        /// <param name="orderSourceId"></param>
        /// <param name="commissionType"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetCustomerCommissionStat(int orderSourceType, int orderSourceId, int CategoryId, int commissionType, UserInfo userInfo)
        {
            var model = user_ReturnComissionRepository.GetCustomerCommissionStat(userInfo.Group_Id, orderSourceType, orderSourceId, CategoryId, commissionType);
            return new
            {
                model?.UnSettlementMoney,
                model?.SttlementMoney,
                model?.CashOutMoney,
                model?.CanCashOutMoney
            };
        }
        #endregion


        #region 更新返佣财务单据
        /// <summary>
        /// 更新返佣财务单据
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public bool UdateReturnMoneyModule(object FinanceIds, int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
              {nameof(RB_ReturnMoney_Batch.FinanceIds),FinanceIds},
            };
            var flag = returnMoney_BatchRepository.Update(fileds, new WhereHelper(nameof(RB_ReturnMoney_Batch.Id), Id));
            return flag;
        }
        #endregion


        #region 员工提现申请获取提现金额校验
        /// <summary>
        /// 获取首页返佣同级
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public RB_User_ReturnComission_ViewModel GetWithdrawal(UserInfo userInfo)
        {
            var model = user_ReturnComissionRepository.GetCenterCommissionStatistics(userInfo.Group_Id, userInfo.Id);
            return model;
        }



        /// <summary>
        /// 获取用户返佣列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_ReturnComission_ViewModel> GetCommissionEnterList(RB_Order_ReturnComission_ViewModel demodel)
        {
            return order_ReturnComissionRepository.GetCommissionEnterList(demodel);
        }

        /// <summary>
        /// 获取首页返佣同级
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetWithdrawalInfo(RB_Customer_Remit_Extend model, decimal afterRemit)
        {
            bool flag = false;
            //更新提现表数据
            Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_User_ReturnComission_ViewModel.CanCashOutMoney),0 },
                    {nameof(RB_User_ReturnComission_ViewModel.CashOutMoney),afterRemit},
                };
            flag = user_ReturnComissionRepository.Update(fileds, new WhereHelper(nameof(RB_User_ReturnComission_ViewModel.Id), model.CustomerId));
            //新增提现申请
            if (flag)
            {
                flag = customer_RemitRepository.Insert(model);
                if (flag)
                {

                }
            }

            return flag;
        }

        #endregion
    }
}
