using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.AOP;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.Module.User;
using Edu.Repository.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class UserInfoController : BaseController
    {
        /// <summary>
        /// 账户相关处理类对象
        /// </summary>
        private readonly AccountModule accountModule = AOPHelper.CreateAOPObject<AccountModule>();
        /// <summary>
        /// 员工处理类对象
        /// </summary>
        private readonly EmployeeModule employeeModule = new EmployeeModule();

        /// <summary>
        /// 教务奖励处理类对象
        /// </summary>
        private readonly SellCommissionModule sellCommissionModule = new SellCommissionModule();

        /// <summary>
        /// 教师奖励明细
        /// </summary>
        private readonly TeachingRewardsModule teachingRewardsModule = new TeachingRewardsModule();

        /// <summary>
        /// 订单处理类对象
        /// </summary>
        private readonly OrderModule orderModule = new OrderModule();
        
        #region 个人资料-密码修改
        /// <summary>
        /// 重置用户密码信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateUserPassword()
        {
            var OldPassWord = base.ParmJObj.GetStringValue("OldPassWord");
            var NewPassWord = base.ParmJObj.GetStringValue("NewPassWord");
            var NewSurePassWord = base.ParmJObj.GetStringValue("NewSurePassWord");
            if (string.IsNullOrWhiteSpace(OldPassWord) || string.IsNullOrWhiteSpace(NewPassWord) || string.IsNullOrWhiteSpace(NewSurePassWord))
            {
                return ApiResult.Failed(message: "请输入密码");
            }
            if (OldPassWord.Equals(NewPassWord))
            {
                return ApiResult.Failed(message: "新密码与旧密码不能一致");
            }
            else
            {
                var extModel = employeeModule.GetEmployeeModule(base.UserInfo.Id, base.UserInfo.AccountId, (int)base.UserInfo.AccountType);
                if (extModel == null)
                {
                    return ApiResult.Failed(message: "员工信息不存在");
                }
                if (extModel.Password != Common.DES.Encrypt(OldPassWord))
                {
                    return ApiResult.Failed(message: "旧密码输入错误");
                }
                if (extModel.Password == Common.DES.Encrypt(NewSurePassWord))
                {
                    return ApiResult.Failed(message: "新密码与旧密码不能一致");
                }

                if (!NewSurePassWord.Equals(NewPassWord))
                {
                    return ApiResult.Failed(message: "新密码输入不一致");
                }


                List<RB_Account_ViewModel> list = new List<RB_Account_ViewModel>
                {
                    new RB_Account_ViewModel
                    {
                        Id = base.UserInfo.Id,
                        AccountId = base.UserInfo.AccountId,
                        AccountType = base.UserInfo.AccountType,
                        Group_Id = base.UserInfo.Group_Id
                    }
                };
                bool result = accountModule.SetBatchResetPassword(list, NewPassWord);
                if (result)
                {
                    return ApiResult.Success(message: "更新密码成功");
                }
                else
                {
                    return ApiResult.Failed(message: "更新密码失败");
                }
            }
        }

        #endregion


        #region 个人资料-账户资料
        /// <summary>
        /// 添加修改管理者 SetManager
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEmployeeBaseInfo()
        {
            var extModel = new Employee_ViewModel()
            {
                EmployeeName = base.ParmJObj.GetStringValue("EmployeeName"),
                EmployeeTel = base.ParmJObj.GetStringValue("EmployeeTel"),
                UserIcon = base.ParmJObj.GetStringValue("UserIcon"),
                Email = base.ParmJObj.GetStringValue("Email"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
            };

            var updateModel = employeeModule.GetEmployeeModule(base.UserInfo.Id, base.UserInfo.AccountId, (int)base.UserInfo.AccountType);
            updateModel.EmployeeName = extModel.EmployeeName;
            updateModel.EmployeeTel = extModel.EmployeeTel;
            updateModel.UserIcon = extModel.UserIcon;
            updateModel.Email = extModel.Email;
            updateModel.School_Id = extModel.School_Id;
            updateModel.UpdateBy = base.UserInfo.Id;
            updateModel.UpdateTime = DateTime.Now;
            bool flag = employeeModule.SetEmployeeModule(updateModel);
            if (flag)
            {
                UserReidsCache.ClearUserLoginCache(base.UserInfo.Id);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion


        #region 个人中心
        [HttpPost]
        public ApiResult GetUserCenterInfo()
        {
            #region 新同事
            var employeeList = employeeModule.GetEmployeeListModule(new Employee_ViewModel
            {
                StartEntryTime = System.DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"),
                EndEntryTime = System.DateTime.Now.ToString("yyyy-MM-dd"),
                Group_Id = base.UserInfo.Group_Id
            });
            var employeeListResult = employeeList.Select(x => new
            {
                x.EmployeeName,
                x.DeptName,
                x.PostName,
                x.AccountRemark,
                x.AccountId,
                x.AccountType,
                x.School_Id,
                x.Id
            });
            #endregion

            #region 提成情况
            //未完成的订单数
            var orderList = orderModule.GetOrderNoComplete(new RB_Order_ViewModel
            {
                OrderState = Common.Enum.Course.OrderStateEnum.Normal,
                Group_Id = base.UserInfo.Group_Id,
                EnterID = base.UserInfo.Id
            });
            //课程进度未达标<15%
            var guestList = orderModule.GetOrderGuestListByEnterID(new RB_Order_Guest_ViewModel
            {
                Group_Id = base.UserInfo.Group_Id,
                EnterID = base.UserInfo.Id
            });

            //本月提成
            decimal totalCommiommission = 0;
            int sureStatus = -1;//本月提成确认状态，-1未生成提成，0-未确认，1-已确认
            int commissionId = 0;//当月提成的id
            #region 我的提成（销售）
            var extModel = new RB_Sell_Commission_Details_ViewModel()
            {
                PeriodsTime = System.DateTime.Now.ToString("yyyy-MM-01"),
                UserId = base.UserInfo.Id,
                Group_Id = base.UserInfo.Group_Id
            };
            var userList = sellCommissionModule.GetSellCommissionByUser(extModel);
            if (userList != null && userList.Any())
            {
                totalCommiommission = userList.Sum(x => x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney);
                sureStatus = userList.FirstOrDefault().SureStatus;
                commissionId = userList.FirstOrDefault().Id;
            }
            else
            {
                userList = sellCommissionModule.GetEstimateSellCommissionInfo(System.DateTime.Now.ToString("yyyy-MM-01"), base.UserInfo);
                if (userList != null && userList.Any())
                {
                    totalCommiommission = userList.Sum(x => x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney);

                }
            }
            #endregion
            #endregion


            #region 奖金情况

            //本月提成
            decimal totalTCommiommission = 0;
            int sureTStatus = -1;//本月提成确认状态，-1未生成提成，0-未确认，1-已确认
            int commissionTId = 0;//当月提成的id
            #region 我的提成（销售）
            var tExtModel = new RB_Teaching_BonusDetail_ViewModel()
            {
                Month = System.DateTime.Now.ToString("yyyy-MM-01"),
                TeacherId = base.UserInfo.AccountId,
                Group_Id = base.UserInfo.Group_Id
            };
            var teacherList = teachingRewardsModule.GetListByTeacherId(tExtModel);
            if (teacherList != null && teacherList.Any())
            {
                totalTCommiommission = teacherList.Sum(x => x.Money);
                sureTStatus = teacherList.FirstOrDefault().SureStatus;
                commissionTId = teacherList.FirstOrDefault().Id;
            }
            else
            {
                teacherList = teachingRewardsModule.GetEstimateTeachingBonusAdd(new RB_Teaching_Bonus_ViewModel { Month = System.DateTime.Now.ToString("yyyy-MM"), TeacherIds = base.UserInfo.Id.ToString() }, base.UserInfo);
                if (teacherList != null && teacherList.Any())
                {
                    totalTCommiommission = teacherList.Sum(x => x.Money);

                }
            }
            #endregion
            #endregion

            return ApiResult.Success("", new
            {
                EmployeeListResult = employeeListResult,
                OrderNoCompleteNum = orderList.Count(),
                CourseNum = guestList.Count(),
                TotalCommiommission = totalCommiommission,
                CommissionId = commissionId,
                SureStatus = sureStatus,
                TotalTCommiommission = totalTCommiommission,
                CommissionTId = commissionTId,
                SureTStatus = sureTStatus,
            });
        }

        /// <summary>
        /// 首页个人中心，-我的提成
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserSellCommission()
        {
            string periodsTime = base.ParmJObj.GetStringValue("PeriodsTime");
            if (string.IsNullOrWhiteSpace(periodsTime))
            {
                periodsTime = System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-01");
            }
            var extModel = new RB_Sell_Commission_Details_ViewModel()
            {
                PeriodsTime = periodsTime,
                UserId = base.UserInfo.Id,
                Group_Id = base.UserInfo.Group_Id
            };

            #region 我的提成（销售）
            var userList = sellCommissionModule.GetSellCommissionByUser(extModel);
            #endregion
            /// List<RB_Teaching_BonusDetail_ViewModel> teacherList = new List<RB_Teaching_BonusDetail_ViewModel>();
            //if (base.UserInfo.AccountType == Common.Enum.User.AccountTypeEnum.Teacher)
            //{
            //    #region 我的提成（老师课时费）
            //    var tExtModel = new RB_Teaching_BonusDetail_ViewModel()
            //    {
            //        Month = base.ParmJObj.GetStringValue("PeriodsTime"),
            //        TeacherId = base.UserInfo.AccountId,
            //        Group_Id = base.UserInfo.Group_Id
            //    };
            //    teacherList = teachingRewardsModule.GetListByTeacherId(tExtModel);
            //    #endregion
            //}
            DateTime startTime = Convert.ToDateTime(periodsTime);
            DateTime endTime = System.DateTime.Now;
            List<object> commiommissionList = new List<object>();
            for (DateTime dt = startTime; dt <= endTime; dt = dt.AddMonths(1))
            {
                decimal totalCommiommission = userList.Where(x => x.PeriodsTime == dt.ToString("yyyy-MM")).Sum(x => x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney);
                //if (teacherList != null && teacherList.Any())
                //{
                //    totalCommiommission += teacherList.Where(x => x.Month == startTime.ToString("yyyy-MM")).Sum(x => x.Money);
                //}
                commiommissionList.Add(new
                {
                    YearStr = dt.Year,
                    MonthStr = dt.Month,
                    TotalCommiommission = totalCommiommission
                });
            }
            return ApiResult.Success("", commiommissionList);
        }

        /// <summary>
        /// 首页个人中心，-我的奖金
        /// </summary>
        /// <returns></returns>
        public ApiResult GetTeacherSellCommission()
        {
            string periodsTime = base.ParmJObj.GetStringValue("PeriodsTime");
            if (string.IsNullOrWhiteSpace(periodsTime))
            {
                periodsTime = System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-01");
            }

            List<RB_Teaching_BonusDetail_ViewModel> teacherList = new List<RB_Teaching_BonusDetail_ViewModel>();
            if (base.UserInfo.AccountType == Common.Enum.User.AccountTypeEnum.Teacher)
            {
                #region 我的提成（老师课时费）
                var tExtModel = new RB_Teaching_BonusDetail_ViewModel()
                {
                    Month = base.ParmJObj.GetStringValue("PeriodsTime"),
                    TeacherId = base.UserInfo.AccountId,
                    Group_Id = base.UserInfo.Group_Id
                };
                teacherList = teachingRewardsModule.GetListByTeacherId(tExtModel);
                #endregion
            }
            DateTime startTime = Convert.ToDateTime(periodsTime);
            DateTime endTime = System.DateTime.Now;
            List<object> commiommissionList = new List<object>();
            for (DateTime dt = startTime; dt <= endTime; dt = dt.AddMonths(1))
            {
                decimal totalCommiommission = 0;
                if (teacherList != null && teacherList.Any())
                {
                    totalCommiommission += teacherList.Where(x => x.Month == startTime.ToString("yyyy-MM")).Sum(x => x.Money);
                }
                commiommissionList.Add(new
                {
                    YearStr = dt.Year,
                    MonthStr = dt.Month,
                    TotalCommiommission = totalCommiommission
                });
            }
            return ApiResult.Success("", commiommissionList);
        }


        /// <summary>
        /// 确认销售提成
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateSureTeachingBonusDetail()
        {
            int Id = base.ParmJObj.GetInt("Id");
            int UserId = base.UserInfo.AccountId;
            bool retult = teachingRewardsModule.UpdateSureTeachingBonusDetail(UserId, Id);
            return retult ? ApiResult.Success("") : ApiResult.Failed("确认失败");
        }

        /// <summary>
        /// 确认销售提成
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdatSureSellCommission()
        {
            int Id = base.ParmJObj.GetInt("Id");
            int UserId = base.UserInfo.Id;
            bool retult = sellCommissionModule.UpdateSureSellCommission(UserId, Id);
            return retult ? ApiResult.Success("") : ApiResult.Failed("确认失败");
        }


        #endregion
    }
}
