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

namespace Mall.WebApi.Controllers.Product
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletGuideCarController : ControllerBase
    {
        private readonly GuideCarModule guideCarModule = new GuideCarModule();


        #region 商品详情

        /// <summary>
        /// 小程序分页列表(赞羊)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsPageListForZY(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.GoodsStatus = 1;//只查询销售中的
            demodel.SmallShopsId = parms.SmallShopsId;
            int UserId = parms.UserId;
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            RB_Member_Grade_Extend memberGrade = new RB_Member_Grade_Extend();
            if (UserId > 0)
            {
                userModel = guideCarModule.GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memberGrade = guideCarModule.GetMemberGradeList(new RB_Member_Grade_Extend() { Id = userModel.MemberGrade ?? 0, Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
                if (demodel.SmallShopsId == 0)
                {
                    demodel.SmallShopsId = userModel.SmallShopId;
                }
            }

            if (string.IsNullOrWhiteSpace(demodel.StartTime))
            {
                return ApiResult.Failed("请选择取车时间");
            }
            if (string.IsNullOrWhiteSpace(demodel.EndTime))
            {
                return ApiResult.Failed("请选择还车时间");
            }

            //if (demodel.RegionId == 0)
            //{
            //    return ApiResult.Failed("请选择区信息");
            //}
            //else
            //{

            //}



            DateTime tempStartTime = Convert.ToDateTime(demodel.StartTime);
            DateTime tempEndTime = Convert.ToDateTime(demodel.EndTime);
            if (tempStartTime.ToString("yyyy-MM-dd") == tempEndTime.ToString("yyyy-MM-dd"))//判断使用天数是否是0.5天/1天
            {
                TimeSpan sp = tempEndTime.Subtract(tempStartTime);
                if (sp.Hours > 6)
                {
                    demodel.UseDay = 1;
                }
                else
                {
                    demodel.UseDay = Convert.ToDecimal(0.5);
                }
            }
            else
            {
                TimeSpan sp = tempEndTime.Subtract(tempStartTime);
                demodel.UseDay = sp.Days;
            }



            var list = guideCarModule.GetAppletGuidCarPageListForCar(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            List<object> RList = new List<object>();
            if (list.Any())
            {
                foreach (var model in list)
                {
                    #region 组装价格
                    List<object> priceList = new List<object>();
                    if (model.IsCustomSpecification == 1)
                    {
                        if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                        {
                            foreach (var item in model.SpecificationPriceList)
                            {
                                var ssarr = item.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> attr_list = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    attr_list.Add(new
                                    {
                                        attr_group_name = smodel.Name,
                                        attr_group_id = smodel.Sort,
                                        attr_id = svmodel.Id,
                                        attr_name = svmodel.Name
                                    });
                                }
                                decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                                {
                                    if (model.MemberPriceList.Any())
                                    {
                                        var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                        if (UserId > 0 && userModel.MemberGrade > 0)
                                        {
                                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                            price_member = gmodel.MemberPrice ?? 0;
                                        }
                                    }
                                }
                                else
                                {
                                    if (UserId > 0 && userModel.MemberGrade > 0)
                                    {
                                        price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                                priceList.Add(new
                                {
                                    id = item.Id,
                                    goods_id = model.Id,
                                    sign_id = item.SpecificationSort,
                                    stock = item.InventoryNum,
                                    price = item.SellingPrice,
                                    no = item.GoodsNumbers,
                                    weight = item.GoodsWeight,
                                    pic_url,
                                    is_delete = item.Status,
                                    attr_list,
                                    price_member
                                });
                            }
                        }
                    }
                    else
                    {
                        decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList;
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                            }
                        }
                        else
                        {
                            if (UserId > 0 && userModel.MemberGrade > 0)
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }


                        priceList.Add(new
                        {
                            id = 0,
                            goods_id = model.Id,
                            sign_id = "",
                            stock = model.InventoryNum,
                            price = model.SellingPrice ?? 0,
                            no = model.GoodsNumbers,
                            weight = model.GoodsWeight,
                            pic_url = "",
                            is_delete = 0,
                            attr_list = new
                            {
                                attr_group_name = "规格",
                                attr_group_id = 0,
                                attr_id = 0,
                                attr_name = model.DefaultSpecificationName
                            },
                            price_member
                        });
                    }
                    #endregion

                    #region 会员价格
                    decimal memberprice = model.SellingPrice ?? 0;
                    if (UserId > 0 && userModel.MemberGrade > 0 && model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
                    {
                        memberprice = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    }
                    else if (UserId > 0 && userModel.MemberGrade > 0)
                    {
                        memberprice = memberprice * (memberGrade?.Discount ?? 10) / 10;
                    }
                    #endregion

                    RList.Add(new
                    {
                        id = model.Id,
                        sign = "",
                        name = model.Name,
                        cover_pic = model.CoverImage,
                        video_url = model.VideoAddress,
                        original_price = model.OriginalPrice,
                        unit = model.Unit,
                        page_url = "/pages/goods/goods?id=" + model.Id,
                        is_negotiable = model.IsGoodsNegotiable,
                        is_level = model.EnjoyMember,
                        level_price = memberprice,
                        price = (model.SellingPrice ?? 0).ToString("#0.00"),
                        price_content = "￥" + (model.SellingPrice ?? 0).ToString("#0.00"),
                        is_sales = model.GoodsStatus,
                        sales = "已售" + model.SalesNum + "件",
                        attr_groups = model.SpecificationList.Select(x => new
                        {
                            attr_group_id = x.Sort,
                            attr_group_name = x.Name,
                            attr_list = x.SpecificationValueList.Select(z => new
                            {
                                attr_id = z.Sort,
                                attr_name = z.Name,
                                pic_url = z.ImagePath
                            })
                        }),
                        attr = priceList,
                        goods_stock = model.SurplusNum,
                        goods_num = model.SurplusNum,
                        marketingLogo = model.MarketingLogo,
                        carclass = model.CarClass,//车辆型号
                        carcolorName = model.CarColorName,//车辆颜色
                        guidename = model.GuideName,//导游名称
                        guideworkyears = model.GuideWorkYears,//导游从业年限
                        guidescore = model.GuideScore,//导游评分
                        guidetelephone = model.GuideTelephone,//导游联系电话
                        guidephoto = model.GuidePhoto//导游头像
                    });
                }
            }

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = RList;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletSDGoodsInfo(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            int UserId = req.UserId;

            var Robj = guideCarModule.GetAppletGoodsInfo_V2(GoodsId, UserId, req.SmallShopsId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }


        /// <summary>
        /// 获取车辆分类下拉
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCarClassList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.GuideCar.CarClassEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取服务类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderListExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.GuideCarGoodsTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取车辆搜索模块
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuideCarSearchInfo(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var model = guideCarModule.GetGuideCarSearchInfo(req.uid, req.MallBaseId);
            return ApiResult.Success("", new
            {
                model.ID,
                model.Background,
                model.SearchBackground,
                model.SearchTips,
                model.IsShowDate,
                model.IsShowCity,
                model.IsShowAddress,
                model.IsShowCarpooling,
                model.IsShowGuideCarGoodsType,
                model.IsShowCarClass,
                model.IsShowTravelGuestNum,
                model.Tips,
                model.TipsIco,
                model.SearchIco,
                model.SearchFilletPX,
                model.ButtonFilletPX,
                model.ButtonText,
                model.ButtonColor,
                model.ButtonTextColor
            });
        }

        #endregion

        #region 订单信息
       
        #endregion


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetGuideCarGuideModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_GuideCar_Guide_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = guideCarModule.GetGuideCarGuideOrderInfo(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_GuideCar_Guide_Extend();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuideCarModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_GuideCar_Car_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = guideCarModule.GetGuideCarModel(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_GuideCar_Car_Extend();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }
    }
}