using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Model.Extend.Product;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using Mall.Common.Enum.User;
using Mall.CacheManager.User;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.Module.Product;
using Mall.AOP;
using Mall.Model.Extend.GuideCar;

namespace Mall.WebApi.Controllers.MallBase
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class GuideCarController : BaseController
    {

        private readonly GuideCarModule guideCarModule = new GuideCarModule();

        #region 基础配置
        /// <summary>
        /// 获取司导专区基础配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuideCarInfo() {
            var req = RequestParm;

            var model = guideCarModule.GetGuideCarInfo(req.TenantId, req.MallBaseId);
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 保存司导专区配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetGuideCarInfo() {
            var req = RequestParm;
            RB_GuideCar_Base_Extend demodel = JsonConvert.DeserializeObject<RB_GuideCar_Base_Extend>(req.msg.ToString());

            if (string.IsNullOrEmpty(demodel.PagePath)) {
                return ApiResult.ParamIsNull("请输入详情页面链接地址");
            }

            demodel.OrderStateJson = "";
            if (demodel.OrderStateList != null && demodel.OrderStateList.Any()) {
                demodel.OrderStateJson = JsonConvert.SerializeObject(demodel.OrderStateList);
            }
            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.UpdateBy = req.EmpId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = guideCarModule.SetGuideCarInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }
        #endregion

        #region 商品管理

        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(RequestParm.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Name = parameters.GetStringValue("Name"),
                GoodsStatus = parameters.GetInt("GoodsStatus"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy")
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = guideCarModule.GetProductGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.CoverImage,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName }),
                x.SellingPrice,
                x.GoodsBuyNum,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsInfo()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = guideCarModule.GetProductGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", new
            {
                model?.Id,
                model?.Name,
                model?.CarouselImageList,
                model?.VideoAddress,
                model?.CustomShareTitles,
                model?.CustomShareImage,
                model?.GoodsStatus,
                model?.Sort,
                model?.SellingPrice,
                model?.OriginalPrice,
                model?.CostPrice,
                model?.IsAreaBuy,
                model?.IntegralPresent,
                model?.IntegralPresentType,
                model?.PointsDeduction,
                model?.PointsDeductionType,
                model?.IsMultipleDeduction,
                model?.GoodsDetails,
                model?.SeparateDistribution,
                model?.SeparateDistributionType,
                model?.SeparateDistributionMoneyType,
                model?.EnjoyMember,
                model?.SeparateSetMember,
                model?.SupplierId,
                model?.Commission,
                model?.IsLiveGoods,
                CategoryList = model?.CategoryList.Select(x => new
                {
                    x.Id,
                    x.CategoryId,
                    x.CategoryName
                }),
                AreaList = model?.AreaList.Select(x => new
                {
                    x.Id,
                    x.AreaId,
                    x.AreaName,
                    x.AreaType
                }),
                DistributionCommissionList = model?.DistributionCommissionList.Select(x => new
                {
                    x.Id,
                    x.DistributorGrade,
                    x.OneCommission,
                    x.SpecificationSort,
                    x.ThreeCommission,
                    x.TwoCommission
                }),
                DistributionCommissionTreeList = model?.DistributionCommissionTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradeCommissionList = x.GradeCommissionList.Select(y => new
                    {
                        y.DistributorGrade,
                        y.OneCommission,
                        y.ThreeCommission,
                        y.TwoCommission
                    })
                }),
                MemberPriceList = model?.MemberPriceList.Select(x => new
                {
                    x.Id,
                    x.MemberGrade,
                    x.MemberPrice,
                    x.SpecificationSort
                }),
                MemberPriceTreeList = model?.MemberPriceTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradePriceList = x.GradePriceList.Select(y => new
                    {
                        y.MemberGrade,
                        y.MemberPrice
                    })
                }),
                model?.Advertising,
                model?.SubName,
                model?.MarketingLogo,
                model?.SiteId,
                model?.GuideId,
                model?.CarId,
                model?.CarColorId,
                model?.CarNumber,
                model?.CarBuyYear,
                model?.CarType,
                CarTypeName = model?.CarType.GetEnumName(),
                model?.UserDay,
                model?.LineName,
                model?.LineDescriptionList,
                model?.IsSpell,
                model?.RideNum,
                model?.AdvanceDay,
                model?.TargetDateList
            });
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsInfo()
        {
            var parms = RequestParm;
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;

            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入商品名称");
            }
            if (demodel.CarouselImageList == null || !demodel.CarouselImageList.Any())
            {
                return ApiResult.ParamIsNull("请添加商品轮播图");
            }
            demodel.CarouselImage = JsonConvert.SerializeObject(demodel.CarouselImageList.Select(x => x.Path));
            if ((demodel.SellingPrice ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入售价");
            }
            if ((demodel.OriginalPrice ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入原价");
            }
            #region 司导项验证
            if ((demodel.SiteId ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请选择站点");
            }
            if ((demodel.GuideId ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请选择导游");
            }
            if ((demodel.CarId ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请选择车辆信息");
            }
            if ((demodel.CarColorId ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请选择车辆颜色");
            }
            if (string.IsNullOrEmpty(demodel.CarNumber)) {
                return ApiResult.ParamIsNull("请输入车牌号");
            }
            if (string.IsNullOrEmpty(demodel.CarBuyYear)) {
                return ApiResult.ParamIsNull("请输入车辆购买年限");
            }
            if ((demodel.CarType ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请选择服务类型");
            }
            if (demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.SQ || demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.ZB || demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.Line) {
                if ((demodel.UserDay ?? 0) <= 0) {
                    return ApiResult.ParamIsNull("请输入使用时间");
                }
                if (demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.Line) {
                    if (string.IsNullOrEmpty(demodel.LineName)) {
                        return ApiResult.ParamIsNull("请输入线路名称");
                    }
                    demodel.LineDescription = "";
                    if (demodel.LineDescriptionList != null && demodel.LineDescriptionList.Any()) {
                        demodel.LineDescription = JsonConvert.SerializeObject(demodel.LineDescriptionList);
                    }
                }
            }
            if ((demodel.RideNum ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请输入可乘坐人数");
            }

            demodel.IsSpell ??= 1;
            demodel.AdvanceDay ??= 0;
            #endregion

            demodel.IsCustomSpecification ??= 2;
            demodel.InventoryNum ??= 0;
            List<Model.Extend.User.RB_Distributor_Grade_Extend> DGradeList = null;
            List<Model.Extend.User.RB_Member_Grade_Extend> MGradeList = null;

            #region 默认值
            demodel.VideoAddress ??= "";
            demodel.CustomShareTitles ??= "";
            demodel.CustomShareImage ??= "";
            demodel.GoodsStatus ??= 2;
            demodel.DefaultSpecificationName ??= "";
            demodel.Sort ??= 0;
            demodel.CostPrice ??= 0;
            demodel.IsGoodsNegotiable ??= 2;
            demodel.SalesNum ??= 0;
            demodel.GoodsNumbers ??= "";
            demodel.GoodsWeight ??= 0;
            demodel.IsDefaultService ??= 1;
            if (demodel.IsDefaultService == 2)
            {
                if (demodel.ServiceList == null || !demodel.ServiceList.Any())
                {
                    return ApiResult.ParamIsNull("请选择商品服务");
                }
                demodel.GoodsService = JsonConvert.SerializeObject(demodel.ServiceList.Select(x => x.Id));
            }
            else
            {
                demodel.GoodsService = "[]";
            }
            demodel.FreightId ??= 0;
            demodel.FormsId ??= 0;
            demodel.LimitBuyGoodsNum ??= -1;
            demodel.LimitBuyOrderNum ??= -1;
            demodel.FullNumPinkage ??= 0;
            demodel.FullMoneyPinkage ??= 0;

            demodel.IsAreaBuy ??= 2;
            if (demodel.IsAreaBuy == 1)
            {
                if (demodel.AreaList == null || !demodel.AreaList.Any())
                {
                    return ApiResult.ParamIsNull("请选择区域");
                }
            }
            demodel.IntegralPresent ??= 0;
            demodel.IntegralPresentType ??= 1;
            demodel.PointsDeduction ??= 0;
            demodel.PointsDeductionType ??= 1;
            demodel.IsMultipleDeduction ??= 2;

            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            #endregion
            demodel.SeparateDistribution ??= 2;
            demodel.SeparateDistributionType ??= 1;
            if (demodel.SeparateDistribution == 1)
            {
                //获取所有分销商等级
                if (DGradeList == null)
                {
                    DGradeList = guideCarModule.GetDistributorGradeList(new Model.Extend.User.RB_Distributor_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    DGradeList.Add(new Model.Extend.User.RB_Distributor_Grade_Extend()
                    {
                        Grade = 0,
                        Name = "默认等级",
                        Id = 0
                    });
                }
                if (demodel.SeparateDistributionType == 1)
                {
                    if (demodel.DistributionCommissionList == null || !demodel.DistributionCommissionList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递分销佣金列表");
                    }
                    //普通设置  直接根据等级验证数量
                    if (DGradeList.Count() != demodel.DistributionCommissionList.Count())
                    {
                        return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                    }
                    foreach (var item in DGradeList)
                    {
                        var defaultModel = demodel.DistributionCommissionList.Where(x => x.DistributorGrade == item.Id).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("分销佣金" + item.Name + "不存在");
                        }
                        defaultModel.OneCommission ??= 0;
                        defaultModel.TwoCommission ??= 0;
                        defaultModel.ThreeCommission ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
                else
                {
                    if (demodel.IsCustomSpecification != 1)
                    {
                        return ApiResult.ParamIsNull("无法开启详细设置");
                    }
                }
            }
            demodel.SeparateDistributionMoneyType ??= 1;
            demodel.EnjoyMember ??= 2;
            demodel.SeparateSetMember ??= 2;
            if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
            {
                //获取所有会员等级
                if (MGradeList == null)
                {
                    MGradeList = guideCarModule.GetMemberGradeList(new Model.Extend.User.RB_Member_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                if (!MGradeList.Any())
                {
                    return ApiResult.ParamIsNull("单独设置会员价需先添加会员等级");
                }
                if (demodel.IsCustomSpecification == 2)
                {
                    if (demodel.MemberPriceList == null || !demodel.MemberPriceList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递会员价格列表");
                    }
                    if (MGradeList.Count() != demodel.MemberPriceList.Count())
                    {
                        return ApiResult.ParamIsNull("会员价格列表数量不正确");
                    }
                    foreach (var item in MGradeList)
                    {
                        var defaultModel = demodel.MemberPriceList.Where(x => x.MemberGrade == item.Id).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("会员价格" + item.Name + "不存在");
                        }
                        defaultModel.MemberPrice ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
            }
            demodel.IsQuickBuy ??= 2;
            demodel.IsSellWell ??= 2;
            demodel.GoodsType ??= Common.Enum.Goods.OrderTypeEnum.Mall;
            demodel.GoodsStatus ??= 2;

            demodel.IsProxy ??= 2;
            demodel.ProxyType ??= 1;
            demodel.ProxyRises ??= 0;
            demodel.ProxyMoney ??= 0;
            demodel.IsProcurement = 2;//新增时

            demodel.PresentFXGrade ??= 0;//赠送粉象等级
            demodel.PresentFXMonth ??= 0;

            demodel.Advertising ??= "";//广告词
            demodel.SubName ??= "";//副标题
            demodel.IsLiveGoods ??= 2;//是否直播商品  1是  2否
            demodel.SendArea ??= "";//发货地

            bool flag = guideCarModule.SetProductGoodsInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = guideCarModule.DelProcudtGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 上下架商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsStatusInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = guideCarModule.SetGoodsStatusInfo(GoodsId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion



        #region 站点配置
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuideCarSiteList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_GuideCar_Site_Extend demodel = JsonConvert.DeserializeObject<RB_GuideCar_Site_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.RulesType =1;
            var list = guideCarModule.GetGuideCarSiteList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.SiteName,
                RegionList = x.RegionList.Select(x => x.RegionName)
            });
            return ApiResult.Success("", pagelist);
        }



        public ApiResult DelGuideCarSiteInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = guideCarModule.DelGuideCarSiteInfo(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetGuideCarSiteModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_GuideCar_Site_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.RulesType =1;
            var oldLogisticsModel = guideCarModule.GetGuideCarSiteModel(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_GuideCar_Site_Extend();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存司导站点信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateGuideCarSite()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_GuideCar_Site_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.RulesType = 1;
            if (query == null)
            {
                return ApiResult.Failed("请传入站点信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.SiteName))
                {
                    return ApiResult.Failed("请输入站点名称");
                }
                
                if (query.RegionList == null || !query.RegionList.Any())
                {
                    return ApiResult.Failed("请选择地区");
                }
                query.TenantId = UserInfo.TenantId;
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = guideCarModule.AddOrUpdateGuideCarSite(query);
                if (result)
                {
                    return ApiResult.Success("站点信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("站点信息保存失败");
                }
            }
        }
        #endregion
    }
}