using System;
using System.Collections.Generic;
using System.Linq;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Course
{
    /// <summary>
    /// 学员相关
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class StuController : BaseController
    {
        /// <summary>
        /// 学员单据处理类对象
        /// </summary>
        private readonly StudentBillModule studentBillModule = AOP.AOPHelper.CreateAOPObject<StudentBillModule>();

        /// <summary>
        /// 订单处理类对象
        /// </summary>
        private readonly OrderModule orderModule = AOP.AOPHelper.CreateAOPObject<OrderModule>();

        /// <summary>
        /// 获取学员退课单据分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStudentBackClassPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取退款单据审核信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetBackBillAduit()
        {
            //退课单据号
            var BackId = base.ParmJObj.GetInt("BackId");
            //审核状态
            var AuditStatus = base.ParmJObj.GetInt("AuditStatus");
            //审核备注
            string Description = base.ParmJObj.GetStringValue("Description");
            //退课金额
            decimal BackMoney = base.ParmJObj.GetDecimal("BackMoney");
            //是否是特殊节点
            var SpecialNode = base.ParmJObj.GetInt("SpecialNode");
            //抄送人
            string RecipientIds = base.ParmJObj.GetStringValue("RecipientIds");
            return ApiResult.Failed();
        }

        /// <summary>
        /// 获取学员预计退课金额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBackBillMoney()
        {
            //退课单据号
            var BackId = base.ParmJObj.GetInt("BackId");
            var data = studentBillModule.GetBackBillMoneyModule(BackId);
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 退学  一键生成财务单据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetStudentBackFinance()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int BackClassId = parms.GetInt("BackClassId", 0);
            int ClientId = parms.GetInt("ClientId", 0);
            if (BackClassId <= 0)
            {
                return ApiResult.ParamIsNull(message: "请传递退课编号!");
            }
            if (ClientId <= 0)
            {
                return ApiResult.ParamIsNull(message: "请传递客户编号!");
            }
            string msg = studentBillModule.SetStudentBackFinance(BackClassId, ClientId, userInfo);
            return string.IsNullOrEmpty(msg) ? ApiResult.Success() : ApiResult.Failed(msg);
        }

        /// <summary>
        /// 学员续费订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RenewOrder()
        {
            //订单编号
            int OrderId = base.ParmJObj.GetInt("OrderId");
            //学员编号
            int guestId = base.ParmJObj.GetInt("GuestId");
            var oldOrderModel = orderModule.GetClassOrderInfoModule(OrderId);
            var orderModel = new RB_Order_ViewModel()
            {
                OrderId = 0,
                ClassId = base.ParmJObj.GetInt("ClassId"),//班级编号
                GuestNum = 1,
                OrderSource = oldOrderModel.OrderSource,
                OrderType = oldOrderModel.OrderType,
                Class_Price = base.ParmJObj.GetDecimal("Class_Price"),//单价
                Unit_Price = base.ParmJObj.GetDecimal("Class_Price"),//成交单价
                PreferPrice = base.ParmJObj.GetDecimal("PreferPrice"),//应收，
                Income = 0,
                HelpEnterId = oldOrderModel.HelpEnterId,
                GeneralOccupation = "",
                EduOccupation = "",
                SaleRemark = base.ParmJObj.GetStringValue("SaleRemark"),//销售备注
                SourceId = 0,
                IsLessPrice = 0,
                LessPrice = 0,
                PerLessMoney=0,
                DiscountMoney=0,
                PerDiscountMoney=0,
                OrderNature = oldOrderModel.OrderNature,
                OldPreferPrice = base.ParmJObj.GetDecimal("PreferPrice"),//应收，
                CourseId = 0,
                StartClassHours = 0,
                UpOrderId = 0,
                VisitorReserveId = 0,
                IsRenewOrder = 1,
                JoinType = Common.Enum.Sale.OrderJoinTypeEnum.RenewOrder,
                TargetJoinType = Common.Enum.Sale.OrderJoinTypeEnum.Normal,
            };
            orderModel.RenewOrderId = OrderId;
            orderModel.SourceOrderId = OrderId;
            orderModel.Group_Id = base.UserInfo.Group_Id;
            orderModel.School_Id = base.UserInfo.School_Id;
            orderModel.Dept_Id = base.UserInfo.DeptId;
            orderModel.OrderForm = OrderFormEnum.Computer;
            orderModel.EnterID = base.UserInfo.Id;
            orderModel.OrderState = OrderStateEnum.Normal;
            orderModel.TradeWay = TradeWayEnum.OnLine;
            orderModel.CreateBy = base.UserInfo.Id;
            orderModel.CreateTime = DateTime.Now;
            orderModel.UpdateBy = base.UserInfo.Id;
            orderModel.UpdateTime = DateTime.Now;
            orderModel.OldGuestId = guestId;
  
            bool flag = orderModule.SetClassOrderModule(orderModel, base.UserInfo, base.CheckUserActionAuth("Edit_Order"), out string message);
            if (flag)
            {
                flag = orderModule.UpdateOrderJoinTypeModule(OrderId, orderModel.OrderId, Common.Enum.Sale.OrderJoinTypeEnum.RenewOrder);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 获取续费班级列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetRenewClass()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Class_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                //School_Id = base.ParmJObj.GetInt("School_Id"),
                ClassType = base.ParmJObj.GetInt("ClassType"),
                StartTime = base.ParmJObj.GetStringValue("StartTime"),
                EndTime = base.ParmJObj.GetStringValue("EndTime"),
                TeacherName = base.ParmJObj.GetStringValue("TeacherName"),
                CouseId = base.ParmJObj.GetInt("CouseId"),
                OldClassId = base.ParmJObj.GetInt("ClassId"),
                QClassStatus = "1,2"
            };
            var obj = studentBillModule.GetRenewClassModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.Count = Convert.ToInt32(rowsCount);
            pageModel.PageData = obj;
            return ApiResult.Success(data: pageModel);
        }

        #region 出勤管理
        /// <summary>
        /// 获取学生的当日出勤情况
        /// </summary>
        /// <returns></returns>
        public ApiResult GetStudentAttendanceDayStatistics()
        {
            var userInfo = base.UserInfo;
            RB_Class_Check_ViewModel demodel = new RB_Class_Check_ViewModel()
            {
                CheckStatus = base.ParmJObj.GetInt("CheckStatus"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                CouseId=base.ParmJObj.GetInt("CouseId"),
                GuestName=base.ParmJObj.GetStringValue("GuestName"),
                OrderGuestId=base.ParmJObj.GetInt("OrderGuestId"),
                StartDate=base.ParmJObj.GetStringValue("StartDate"),
            };
            demodel.School_Id = -1;
            var School_Id = base.ParmJObj.GetStringValue("School_Id");
            if (!string.IsNullOrEmpty(School_Id))
            {
                demodel.School_Id = base.ParmJObj.GetInt("School_Id");
            }
            demodel.Group_Id = userInfo.Group_Id;
            if (string.IsNullOrEmpty(demodel.StartDate))
            {
                return ApiResult.ParamIsNull("请传递日期");
            }

            var RObj = studentBillModule.GetStudentAttendanceDayStatistics(demodel);
            return ApiResult.Success("", RObj);
        }

        /// <summary>
        /// 获取学生的当日出勤情况  Excel导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult GetStudentAttendanceDayStatisticsToExcel()
        {
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value:"班号"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"班级"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"课程"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"老师"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"上课日期"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"上课时间"){CellWidth=25,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"学员姓名"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"学习课时"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER },
                    new ExcelColumn(value:"出勤状态"){CellWidth=15,HAlignmentEnum= HAlignmentEnum.CENTER,VAlignmentEnum= VAlignmentEnum.CENTER }
                }
            };
            slist.Add(header);
            string ExcelName = "学员出勤统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";



            var userInfo = base.UserInfo;
            RB_Class_Check_ViewModel demodel = JsonHelper.DeserializeObject<RB_Class_Check_ViewModel>(RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            if (string.IsNullOrEmpty(demodel.StartDate))
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

            try
            {
                List<ExcelDataSource> RDate = studentBillModule.GetStudentAttendanceDayStatisticsToExcel(demodel);
                slist.AddRange(RDate);

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "OutToExcelOrderStudentClassHoursList");
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        #endregion


        #region 学员管理
        /// <summary>
        /// 获取学员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllStudentPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var model = new RB_Order_Guest_Extend
            {
                CourseId = base.ParmJObj.GetInt("CourseId", 0),
                ClassId = base.ParmJObj.GetInt("ClassId", 0),
                GuestName = base.ParmJObj.GetStringValue("GuestName"),
                ClassNo = base.ParmJObj.GetStringValue("ClassNo"),
                OrderId = base.ParmJObj.GetInt("OrderId", 0),
                EnterID = base.ParmJObj.GetInt("EnterID", 0),
                JoinType = base.ParmJObj.GetInt("JoinType", 0),
                EarlyWarning = (Common.Enum.Course.GuestClassHoursEarlyWarningEnum)base.ParmJObj.GetInt("EarlyWarning", 0),
                GuestState=(GuestStateEnum)base.ParmJObj.GetInt("GuestState"),
                StuChannelId = base.ParmJObj.GetInt("StuChannelId", 0),
                CreateType = (Common.Enum.User.StuCreateTypeEnum)base.ParmJObj.GetInt("CreateType", 0),
                StuSourceId = base.ParmJObj.GetInt("StuSourceId", 0),
            };
            model.School_Id = -1;
            var schoolId = base.ParmJObj.GetStringValue("School_Id");
            if (!string.IsNullOrEmpty(schoolId))
            {
                model.School_Id = base.ParmJObj.GetInt("School_Id");
            }
            try
            {
                string OrderTime = base.ParmJObj.GetStringValue("OrderTime");
                if (!string.IsNullOrWhiteSpace(OrderTime))
                {
                    model.OrderTime = Convert.ToDateTime(OrderTime);
                }
                string EffectStatus = base.ParmJObj.GetStringValue("EffectStatus");
                if (!string.IsNullOrWhiteSpace(EffectStatus))
                {
                    model.EffectStatus = Convert.ToInt32(EffectStatus);
                }
                string EndOrderTime = base.ParmJObj.GetStringValue("EndOrderTime");
                if (!string.IsNullOrWhiteSpace(EndOrderTime))
                {
                    model.EndOrderTime = Convert.ToDateTime(EndOrderTime);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetAllStudentPage");
            }

            model.Group_Id = base.UserInfo.Group_Id;
            var list = studentBillModule.GetAllStudentPage(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, model);
            List<object> result = new List<object>();

            foreach (var item in list)
            {
                if (item.EnterID > 0)
                {
                    item.EnterName = UserReidsCache.GetUserLoginInfo(item.EnterID)?.AccountName ?? "";
                }
                if (item.EnterID <= 0 && item.CreateBy > 0)
                {
                    item.EnterName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                if (item.StuCreateBy > 0)
                {
                    item.StuCreateByName = UserReidsCache.GetUserLoginInfo(item.StuCreateBy)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.Id,
                    item.GuestName,
                    Mobile = item.StuRealMobile,
                    item.ContractId,
                    item.ContractNo,
                    item.ClassId,
                    item.ClassName,
                    item.CourseId,
                    item.CourseName,
                    item.Teacher_Id,
                    item.TeacherName,
                    item.OrderId,
                    OrderTime = Common.ConvertHelper.FormatTime(item.OrderTime),
                    item.EnterID,
                    item.EnterName,
                    item.PreferPrice,
                    item.Income,
                    item.Refund,
                    item.TotalHours,
                    item.ValidClassHours,
                    item.CompleteHours,
                    item.SurplusHours,
                    item.MakeUpHours,
                    item.AbsenceNum,
                    item.LeaveNum,
                    item.EventlogNum,
                    item.GuestState,
                    item.GuestStateStr,
                    GraduationTime = Common.ConvertHelper.FormatDate(item.GraduationTime),
                    item.School_Id,
                    item.JoinType,
                    item.JoinTypeStr,
                    item.Student_Id,
                    item.CourseRate,
                    CourseRateName = item.CourseRate.ToName().Replace("课程", ""),
                    item.StuCreateBy,
                    item.StuCreateByName,
                    AssistList = item.AssistList.Select(qitem => new
                    {
                        qitem.Id,
                        qitem.StuId,
                        qitem.AssistId,
                        qitem.AssistName,
                        qitem.AssistType,
                        AssistTypeName = qitem.AssistType.ToName()
                    }),
                    item.StuChannelId,
                    item.StuChannelName,
                    item.CreateType,
                    CreateTypeName = item.CreateType.ToName(),
                    item.StuSourceId,
                    item.StuSourceIdName,
                    item.EnterpriseName
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取预警枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuestClassHoursEarlyWarningEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(GuestClassHoursEarlyWarningEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }


        /// <summary>
        /// 获取类型枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderJoinTypeEnumEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(Common.Enum.Sale.OrderJoinTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }




        /// <summary>
        /// 获取学员签到信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassCheckPageList()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Class_Check_ViewModel()
            {
                OrderGuestId = base.ParmJObj.GetInt("OrderGuestId"),
                CheckStatus = base.ParmJObj.GetInt("CheckStatus", 0),
                MakeUpStatus = base.ParmJObj.GetInt("MakeUpStatus", 0)
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = studentBillModule.GetClassCheckPageList(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                result.Add(new
                {
                    item.ClassId,
                    item.ClassName,
                    item.ClassNo,
                    item.CouseId,
                    item.CourseName,
                    item.ClassRoomId,
                    item.RoomName,
                    item.School_Id,
                    item.TeacherId,
                    item.TeacherName,
                    item.GuestName,
                    ClassDate = item.ClassDate.ToString("yyyy-MM-dd"),
                    item.TimeBucket,
                    CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        #region 学员事件记录

        /// <summary>
        /// 获取学员事件记录分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStudentEventLogPageList()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Student_EventLog_ViewModel()
            {
                StuId = base.ParmJObj.GetInt("StuId"),
                EventType = base.ParmJObj.GetInt("EventType")
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = studentBillModule.GetStudentEventLogPageList(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                if (item.UpdateBy > 0)
                {
                    item.UpdateByName = UserReidsCache.GetUserLoginInfo(item.UpdateBy)?.AccountName ?? "";
                }

                if (!string.IsNullOrWhiteSpace(item.EventPic))
                {
                    item.EventPicList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.EventPic);
                }
                else
                {
                    item.EventPicList = new List<string>();
                }
                result.Add(new
                {
                    item.EventPicList,
                    item.EventPic,
                    item.Id,
                    item.EventType,
                    item.CreateByName,
                    item.EventContent,
                    item.Title,
                    CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增学员事件记录
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSetStudentEventLog()
        {
            var query = new RB_Student_EventLog_ViewModel()
            {
                StuId = base.ParmJObj.GetInt("StuId"),
                Id = base.ParmJObj.GetInt("Id"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
                EventType = base.ParmJObj.GetInt("EventType"),
                EventContent = base.ParmJObj.GetStringValue("EventContent"),
                Title = base.ParmJObj.GetStringValue("Title"),
            };
            try
            {
                query.EventPicList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("EventPicList"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetSetStudentEventLog");
            }
            if (query.EventPicList != null && query.EventPicList.Any())
            {
                query.EventPic = Common.Plugin.JsonHelper.Serialize(query.EventPicList);
            }
            else
            {
                query.EventPic = "";
            }
            if (string.IsNullOrWhiteSpace(query.Title))
            {
                return ApiResult.Failed("学员事件记录标题不能为空");
            }
            if (string.IsNullOrWhiteSpace(query.EventContent))
            {
                return ApiResult.Failed("学员事件记录内容不能为空");
            }
            if (query.EventType != 1 && query.EventType != 2)
            {
                return ApiResult.Failed("学员事件记录类型错误");
            }
            query.Group_Id = base.UserInfo.Group_Id;
            query.Status = Common.Enum.DateStateEnum.Normal;
            if (query.Id == 0)
            {
                query.CreateBy = base.UserInfo.Id;
                query.CreateTime = System.DateTime.Now;
            }
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            var result = studentBillModule.SetStudentEventLog(query);
            return result ? ApiResult.Success("添加学员事件记录成功") : ApiResult.Failed("添加学员事件记录失败");
        }

        /// <summary>
        /// 删除学员事件记录
        /// </summary>
        /// <returns></returns>
        public ApiResult GetDelStudentEventLog()
        {
            int Id = base.ParmJObj.GetInt("Id");
            var result = studentBillModule.DelStudentEventLog(Id, base.UserInfo.Id);
            return result ? ApiResult.Success("删除学员事件记录成功") : ApiResult.Failed("删除学员事件记录失败");
        }

        #endregion 


        #endregion
    }
}
