using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Sale;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Module.Course;
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.Course
{
    /// <summary>
    /// 课程报价单控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class CourseOfferController : BaseController
    {
        /// <summary>
        /// 课程报价单处理类对象
        /// </summary>
        private readonly CourseOfferModule courseOfferModule = AOP.AOPHelper.CreateAOPObject<CourseOfferModule>();

        #region 课程报价单管理
        
        /// <summary>
        /// 获取报价单类型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOfferTypeList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(OfferTypeEnum));
             return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取课程报价单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseOfferPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Course_Offer_ViewModel()
            {
                Name = base.ParmJObj.GetStringValue("Name"),
                CreateBy = base.ParmJObj.GetInt("CreateBy"),
                QStart = base.ParmJObj.GetStringValue("QStart"),
                QEnd = base.ParmJObj.GetStringValue("QEnd"),
                CustomerInfo = base.ParmJObj.GetStringValue("CustomerInfo"),
                CustomerSource = (CustomerSourceEnum)base.ParmJObj.GetInt("CustomerSource"),
                CustomerType = (CustomerTypeEnum)base.ParmJObj.GetInt("CustomerType"),
                CustomerStatus = (CustomerStatusEnum)base.ParmJObj.GetInt("CustomerStatus"),
                SerialNum = base.ParmJObj.GetStringValue("SerialNum"),
                IsGetDetails = base.ParmJObj.GetInt("IsGetDetails"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                CustomerTel = base.ParmJObj.GetStringValue("CustomerTel"),
                OfferType = (OfferTypeEnum)base.ParmJObj.GetInt("OfferType"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            query.School_Id = base.UserInfo.School_Id;
            var list = courseOfferModule.GetCourseOfferPageModule(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 ?? "";
                }
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = list.Select(qitem => new
            {
                qitem.Id,
                qitem.SerialNum,
                qitem.Name,
                EffectiveStart = qitem.EffectiveStartStr,
                EffectiveEnd = qitem.EffectiveEndStr,
                qitem.CustomerType,
                qitem.CustomerTypeName,
                qitem.CustomerSource,
                qitem.CustomerSourceName,
                qitem.TotalOriginalPrice,
                qitem.TotalPrice,
                qitem.TotalDiscountPrice,
                qitem.CustomerStatus,
                qitem.CustomerStatusName,
                qitem.CustomerInfo,
                qitem.CreateBy,
                qitem.CreateByName,
                qitem.CreateTimeStr,
                qitem.UpdateBy,
                qitem.UpdateByName,
                qitem.UpdateTimeStr,
                qitem.OfferDetails,
                qitem.CustomerName,
                qitem.CustomerTel,
                qitem.JoinNum,
                qitem.OrderIdList,
                qitem.OfferType,
                qitem.OfferTypeName,
            });
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取课程报价单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseOfferList()
        {
            var query = new RB_Course_Offer_ViewModel()
            {
                Name = base.ParmJObj.GetStringValue("Name"),
                OfferType = (OfferTypeEnum)base.ParmJObj.GetInt("OfferType"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            query.School_Id = base.UserInfo.School_Id;
            var list = courseOfferModule.GetCourseOfferListModule(query);
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 新增修改课程报价单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCourseOffer()
        {
            var extModel = new RB_Course_Offer_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                Name = base.ParmJObj.GetStringValue("Name"),
                EffectiveStart = base.ParmJObj.GetDateTime("EffectiveStart"),
                EffectiveEnd = base.ParmJObj.GetDateTime("EffectiveEnd"),
                CustomerType = (CustomerTypeEnum)base.ParmJObj.GetInt("CustomerType"),
                CustomerSource = (CustomerSourceEnum)base.ParmJObj.GetInt("CustomerSource"),
                TotalOriginalPrice = base.ParmJObj.GetDecimal("TotalOriginalPrice"),
                TotalPrice = base.ParmJObj.GetDecimal("TotalPrice"),
                TotalDiscountPrice = base.ParmJObj.GetDecimal("TotalDiscountPrice"),
                CustomerInfo = base.ParmJObj.GetStringValue("CustomerInfo"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                CustomerTel = base.ParmJObj.GetStringValue("CustomerTel"),
                JoinNum = base.ParmJObj.GetInt("JoinNum"),
                OfferType=(OfferTypeEnum)base.ParmJObj.GetInt("OfferType"),
            };
            try
            {
                extModel.OfferDetails = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Course_OfferDetails_ViewModel>>(base.ParmJObj.GetStringValue("OfferDetails"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetCourseCategory");
            }
            extModel.CustomerStatus = CustomerStatusEnum.NoSure;
            extModel.CreateTime = DateTime.Now;
            extModel.CreateBy = UserInfo.Id;
            extModel.UpdateBy = UserInfo.Id;
            extModel.UpdateTime = DateTime.Now;
            extModel.Group_Id = this.UserInfo.Group_Id;
            extModel.School_Id = this.UserInfo.School_Id;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            bool flag = courseOfferModule.SetCourseOfferModule(extModel);
            return flag ? ApiResult.Success(data: extModel.Id) : ApiResult.Failed();
        }

        /// <summary>
        /// 修改课程报价单价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCourseOfferPrice()
        {
            var extModel = new RB_Course_Offer_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
            };
            try
            {
                extModel.OfferDetails = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Course_OfferDetails_ViewModel>>(base.ParmJObj.GetStringValue("OfferDetails"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetCourseOfferPrice");
            }
            bool flag = courseOfferModule.SetCourseOfferPriceModule(extModel);
            return flag ? ApiResult.Success(data: extModel.Id) : ApiResult.Failed();
        }


        /// <summary>
        /// 获取课程报价单实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseOffer()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var extModel = courseOfferModule.GetCourseOfferModule(Id);

            string CreateByName = "";
            string CreateTel = "";
            string CreateWeChatNo = "";
            if (extModel != null && extModel.CreateBy > 0)
            {
                var user = UserReidsCache.GetUserLoginInfo(extModel.CreateBy);
                CreateByName = user?.AccountName ?? "";
                CreateTel = user?.UserMobile ?? "";
            }
            var obj = new
            {
                extModel?.Id,
                extModel?.Name,
                EffectiveStart = extModel?.EffectiveStartStr,
                EffectiveEnd = extModel?.EffectiveEndStr,
                extModel?.CustomerType,
                extModel?.CustomerTypeName,
                extModel?.CustomerSource,
                extModel?.CustomerSourceName,
                extModel?.TotalOriginalPrice,
                extModel?.TotalPrice,
                extModel?.TotalDiscountPrice,
                extModel?.CustomerInfo,
                extModel?.CustomerStatus,
                extModel?.CustomerStatusName,
                extModel?.CreateBy,
                extModel?.CustomerTel,
                extModel?.CustomerName,
                extModel?.JoinNum,
                extModel?.SerialNum,
                extModel?.ApplyReason,
                OfferDetails = extModel?.OfferDetails ?? new List<RB_Course_OfferDetails_ViewModel>(),
                CreateTime = Common.ConvertHelper.FormatDate2(extModel?.CreateTime),
                CreateByName,
                CreateTel,
                CreateWeChatNo,
                extModel?.OfferType,
                extModel?.OfferTypeName,
            };
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 删除课程报价单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveCourseOffer()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            int Status = base.ParmJObj.GetInt("Status", 0);
            var flag = courseOfferModule.RemoveCourseOfferModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 客户修改课程报价单确认状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCourseOfferCustomerStatus()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            int CustomerStatus = base.ParmJObj.GetInt("CustomerStatus", 0);
            var flag = courseOfferModule.SetCourseOfferCustomerStatusModule(Id, CustomerStatus);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 销售申请修改价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetApplyModifyPrice()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            string ApplyReason = base.ParmJObj.GetStringValue("ApplyReason");
            var flag = courseOfferModule.SetApplyModifyPriceModule(Id, ApplyReason);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取枚举相关列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCustomerEnum()
        {
            var CustomerTypeList = Common.Plugin.EnumHelper.EnumToList(typeof(CustomerTypeEnum));
            var CustomerSourceList = Common.Plugin.EnumHelper.EnumToList(typeof(CustomerSourceEnum));
            var CustomerStatusList = Common.Plugin.EnumHelper.EnumToList(typeof(CustomerStatusEnum));
            var data = new
            {
                CustomerTypeList,
                CustomerSourceList,
                CustomerStatusList,
            };
            return ApiResult.Success(data: data);
        }
        #endregion

        /// <summary>
        /// 报价单转订单
        /// </summary>
        /// <returns></returns>
        public ApiResult OfferTransOrder()
        {
            var offerId = base.ParmJObj.GetInt("OfferId", 0);
            int OfferType = base.ParmJObj.GetInt("OfferType", 0);
            if (offerId <= 0)
            {
                return ApiResult.ParamIsNull("请传递报价单编号!");
            }
            List<RB_Course_OfferDetails_ViewModel> detailsList = new List<RB_Course_OfferDetails_ViewModel>();
            try
            {
                detailsList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Course_OfferDetails_ViewModel>>(base.ParmJObj.GetStringValue("OfferDetails"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "OfferTransOrder");
            }
            if (detailsList == null || (detailsList != null && detailsList.Count == 0))
            {
                return ApiResult.ParamIsNull("请传递报价单详情!");
            }
            string message = "";
            //报价单类型为课程
            if (OfferType == 1)
            {
                foreach (var item in detailsList)
                {
                    if (item.ClassId <= 0)
                    {
                        message += string.Format("、请选择【{0}】的班级", item.CourseName);
                    }
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                return ApiResult.ParamIsNull(message:message[1..]);
            }
            var flag = courseOfferModule.SetOfferCreateOrder(offerId, detailsList);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
    }
}
