using System;
using System.Collections.Generic;
using System.Linq;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Finance;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Finance;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Finance;
using Edu.Repository.StudyAbroad;
using Edu.Repository.User;
using VT.FW.DB;

namespace Edu.Module.Finance
{
    /// <summary>
    /// 活动处理类
    /// </summary>
    public class ActivityModule
    {
        /// <summary>
        /// 活动配置
        /// </summary>
        private readonly RB_Activity_ConfigRepository activity_ConfigRepository = new RB_Activity_ConfigRepository();
        /// <summary>
        /// 提成期数
        /// </summary>
        private readonly RB_Activity_PeriodsRepository activity_PeriodsRepository = new RB_Activity_PeriodsRepository();
        /// <summary>
        /// 提成期数明细
        /// </summary>
        private readonly RB_Activity_PeriodsDetailRepository activity_PeriodsDetailRepository = new RB_Activity_PeriodsDetailRepository();
        /// <summary>
        /// 财务
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();
        /// <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();


        #region 活动配置
        /// <summary>
        /// 获取活动配置列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RB_Activity_Config_ViewModel GetActivityConfigModel(RB_Activity_Config_ViewModel model)
        {
            var dmodel = activity_ConfigRepository.GetList(model).FirstOrDefault();
            if (dmodel == null) { dmodel = new RB_Activity_Config_ViewModel(); }
            return dmodel;
        }

        /// <summary>
        /// 新增/修改活动配置
        /// </summary>
        /// <param name="demdoel"></param>
        /// <returns></returns>
        public string SetActivityConfig(RB_Activity_Config_ViewModel demdoel)
        {
            if (demdoel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Activity_Config_ViewModel.Type),demdoel.Type},
                    { nameof(RB_Activity_Config_ViewModel.CommissionMoney),demdoel.CommissionMoney},
                    { nameof(RB_Activity_Config_ViewModel.UpdateBy),demdoel.UpdateBy},
                    { nameof(RB_Activity_Config_ViewModel.UpdateTime),demdoel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Activity_Config_ViewModel.Id),
                          FiledValue=demdoel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = activity_ConfigRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                bool flag = activity_ConfigRepository.Insert(demdoel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        #endregion

        #region 活动提成

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Activity_Periods_ViewModel> GetActivityCommissionPeriodsList(RB_Activity_Periods_ViewModel dmodel)
        {
            return activity_PeriodsRepository.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_Activity_Periods_ViewModel> GetActivityCommissionPeriodsPageList(int pageIndex, int pageSize, out long count, RB_Activity_Periods_ViewModel dmodel)
        {
            var list = activity_PeriodsRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询财务单据
                string periodsIds = string.Join(",", list.Select(x => x.Id));
                var financeList = financeRepository.GetListSingle(new RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, OtherType = 42, ReFinanceIds = periodsIds, IsSelectNormal = 1 });
                foreach (var item in list)
                {
                    var flist = financeList.Where(x => x.ReFinanceId == item.Id).Select(x => x.FrID);
                    if (flist.Any())
                    {
                        item.Financials = string.Join(",", flist);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户提成列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Activity_PeriodsDetail_ViewModel> GetActivityCommissionUserList(RB_Activity_PeriodsDetail_ViewModel dmodel)
        {
            var list = activity_PeriodsDetailRepository.GetActivityCommissionUserList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户提成明细列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Activity_PeriodsDetail_ViewModel> GetActivityCommissionUserDetailList(RB_Activity_PeriodsDetail_ViewModel dmodel)
        {
            var list = activity_PeriodsDetailRepository.GetList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取未发放提成用户列表 + 提成金额
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetActivityCommissionSendEmployeeList(int periodId, UserInfo userInfo)
        {
            var model = activity_PeriodsRepository.GetEntity(periodId);
            if (model == null) { return "周期不存在"; }
            List<int> EmpIdList = new List<int>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
            }
            var list = GetActivityCommissionUserList(new RB_Activity_PeriodsDetail_ViewModel() { Group_Id = userInfo.Group_Id, PeriodId = periodId });
            return ApiResult.Success("", list.Select(x => new
            {
                x.UserId,
                x.UserName,
                x.CommissionMoney,
                IsGiveOut = EmpIdList.Contains(x.UserId) ? 1 : 2
            }));
        }

        /// <summary>
        /// 设置发放提成
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="empIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetActivityCommissionSendEmployee(int periodId, string empIds, UserInfo userInfo)
        {
            var model = activity_PeriodsRepository.GetEntity(periodId);
            if (model == null) { return "周期不存在"; }
            if (model.Group_Id != userInfo.Group_Id) { return "集团不正确"; }
            List<int> EmpIdList = new List<int>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
            }
            List<int> NewIdList = JsonHelper.DeserializeObject<List<int>>("[" + empIds + "]");
            foreach (var item in NewIdList)
            {
                if (EmpIdList.Contains(item))
                {
                    return "用户ID" + item + "已发放了提成，无法重复发放";
                }
            }
            EmpIdList.AddRange(NewIdList);
            string empids2 = string.Join(",", EmpIdList);
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Activity_Periods_ViewModel.EmpIds),empids2}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName= nameof(RB_Activity_Periods_ViewModel.Id),
                      FiledValue=periodId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = activity_PeriodsRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取提成统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Activity_PeriodsDetail_ViewModel> GetActivityCommissionStatisticsPageList(int pageIndex, int pageSize, out long count, RB_Activity_PeriodsDetail_ViewModel dmodel)
        {
            var list = activity_PeriodsDetailRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 累计提成金额统计
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetActivityCommissionStatistics(RB_Activity_PeriodsDetail_ViewModel dmodel)
        {
            return activity_PeriodsDetailRepository.GetSellCommissionStatistics(dmodel);
        }

        #endregion
    }
}
