using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.Sell;
using Edu.Module.Course;
using Edu.Module.EduTask;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Edu.WebApi.Controllers.EduTask
{
    /// <summary>
    /// 订单转班、分拆控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class OrderChangeController : BaseController
    {
        /// <summary>
        /// 订单转班、分拆处理类对象
        /// </summary>
        private readonly OrderChangeModule orderChangeModule = AOP.AOPHelper.CreateAOPObject<OrderChangeModule>();

        /// <summary>
        /// 班级处理类对象
        /// </summary>
        private readonly ClassModule classModule = AOP.AOPHelper.CreateAOPObject<ClassModule>();

        /// <summary>
        /// 订单处理类对象
        /// </summary>
        private readonly OrderModule orderModule = new OrderModule();

        /// <summary>
        /// 新增订单转班申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderChange()
        {
            var model = new RB_Order_Change_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                SourceOrderId = base.ParmJObj.GetInt("SourceOrderId"),
                ChangeType = base.ParmJObj.GetInt("ChangeType"),
                NewClassId = base.ParmJObj.GetInt("NewClassId"),
                NewCourseId = base.ParmJObj.GetInt("NewCourseId"),
                EffectiveDate = base.ParmJObj.GetDateTime("EffectiveDate"),
                Remarks = base.ParmJObj.GetStringValue("Remarks"),
                OrderGuestId=base.ParmJObj.GetInt("OrderGuestId"),
                OutTime=base.ParmJObj.GetDateTime("OutTime"),
            };
            string receiptFile = string.Empty;
            try
            {
                List<string> receiptFileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("ReceiptFileList"));
                if (receiptFileList == null || !receiptFileList.Any())
                {
                    return ApiResult.Failed("附件必须上传");
                }
                else
                {
                    receiptFile = JsonHelper.Serialize(receiptFileList);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetOrderChange");
            }
            if (Convert.ToDateTime(Common.ConvertHelper.FormatDate(model.OutTime)) < Convert.ToDateTime(Common.ConvertHelper.FormatDate(DateTime.Now)) )
            {
                return ApiResult.ParamIsNull(message: "转出本班日期必须大于今天!");
            }
            if (Convert.ToDateTime(Common.ConvertHelper.FormatDate(model.OutTime)) > Convert.ToDateTime(Common.ConvertHelper.FormatDate(model.EffectiveDate)))
            {
                return ApiResult.ParamIsNull(message: "新订单生效日期必须大于或等于转出本班日期!");
            }
            var oldOrderModel = orderModule.GetClassOrderInfoModule(model.SourceOrderId);
            if (oldOrderModel == null)
            {
                return ApiResult.ParamIsNull(message: "原订单号不存在!");
            }
            if (oldOrderModel.PreferPrice != (oldOrderModel.Income +oldOrderModel.DiscountMoney+ oldOrderModel.PlatformTax - oldOrderModel.Refund))
            {
                return ApiResult.ParamIsNull(message: "原订单款未收齐，不能转班!");
            }
            var classModel = classModule.GetClassModule(model.NewClassId);
            if (oldOrderModel.CourseId != model.NewCourseId)
            {
                return ApiResult.ParamIsNull(message: "原订单号课程和新班级课程不一致，请核实!");
            }
            var guestModel = classModule.GetOrderGuestListModule(new RB_Order_Guest_ViewModel()
            {
                OrderId = model.SourceOrderId,
                QEffectStatus = 1,
                OrderGuestIds = model.OrderGuestId.ToString()
            })?.FirstOrDefault();
            if (guestModel != null && guestModel.Id > 0)
            {
                var surplusHours= orderChangeModule.GetClassPlanTimeHoursModule(oldOrderModel.ClassId,
                    Common.ConvertHelper.FormatDate(DateTime.Now), 
                    Common.ConvertHelper.FormatDate(model.EffectiveDate)
                  );
                if (guestModel.ValidClassHours - surplusHours <= 0)
                {
                    return ApiResult.ParamIsNull(message: "当前学员预计没有足够转班的有效课时，请注意核对!");
                }
            }
            else
            {
                return ApiResult.ParamIsNull(message: "学员新增状态不正确,请核实!");
            }
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.Group_Id = base.UserInfo.Group_Id;
            model.School_Id = classModel.School_Id;
            model.UpdateBy = base.UserInfo.Id;
            model.UpdateTime = DateTime.Now;
            bool flag = orderChangeModule.SetOrderChangeModule(model, receiptFile, out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 订单拆分申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderSplit()
        {
            var model = new RB_Order_Change_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                SourceOrderId = base.ParmJObj.GetInt("SourceOrderId"),
                ChangeType = base.ParmJObj.GetInt("ChangeType"),
                NewClassId = base.ParmJObj.GetInt("NewClassId"),
                NewCourseId = base.ParmJObj.GetInt("NewCourseId"),
                EffectiveDate = base.ParmJObj.GetDateTime("EffectiveDate"),
                Remarks = base.ParmJObj.GetStringValue("Remarks"),
                OrderGuestId = base.ParmJObj.GetInt("OrderGuestId"),
                OutTime = base.ParmJObj.GetDateTime("OutTime"),
            };
            string receiptFile = string.Empty;
            try
            {
                List<string> receiptFileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("ReceiptFileList"));
                if (receiptFileList == null || !receiptFileList.Any())
                {
                    return ApiResult.Failed("附件必须上传");
                }
                else
                {
                    receiptFile = JsonHelper.Serialize(receiptFileList);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetOrderSplit");
            }
            var oldOrderModel = orderModule.GetClassOrderInfoModule(model.SourceOrderId);
            if (oldOrderModel == null)
            {
                return ApiResult.ParamIsNull(message: "原订单号不存在!");
            }
            if (oldOrderModel.PreferPrice != (oldOrderModel.Income +oldOrderModel.DiscountMoney+ oldOrderModel.PlatformTax - oldOrderModel.Refund))
            {
                return ApiResult.ParamIsNull(message: "原订单款未收齐，不能转班!");
            }
            var classModel = classModule.GetClassModule(model.NewClassId);

            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.Group_Id = base.UserInfo.Group_Id;
            model.School_Id = classModel.School_Id;
            model.UpdateBy = base.UserInfo.Id;
            model.UpdateTime = DateTime.Now;
            bool flag = orderChangeModule.SetOrderSplitModule(model, receiptFile, out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 订单拆分申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult TestUpdateOrderSplit()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var Type = base.ParmJObj.GetInt("Type");
            bool flag = orderChangeModule.TestUpdateOrderSplitModule(Id, Type);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 回归原班
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RegressSourceClass()
        {
            var OrderId = base.ParmJObj.GetInt("OrderId");
            bool flag = orderChangeModule.RegressSourceClassModule(OrderId,out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }
    }
}
