using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
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();


        /// <summary>
        /// 地区模块处理类
        /// </summary>
        private Module.BaseSetUp.DestinationModule destinationModule = new Module.BaseSetUp.DestinationModule();




        /// <summary>
        /// 根据地区名称获取地区列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetDestinationListByNames(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parm = JObject.Parse(parms.msg.ToString());
            var area = parm.GetStringValue("area");
            var where = Common.Plugin.JsonHelper.DeserializeObject<string[]>(area);
            var list = destinationModule.GetDestinationListByNames(where);
            return ApiResult.Success(data: list.Select(qitem => new { qitem.ID, qitem.Name, qitem.CodeLevel, qitem.ParentID }));
        }





        [HttpPost]
        public ApiResult GetAllList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parm = JObject.Parse(parms.msg.ToString());
            var list = destinationModule.GetAllList();
            var result = list.Where(x => x.CodeLevel == Common.Enum.AreaRegionEnum.CityEnum).Select(x => new { x.ID, x.Name, x.CodeLevel, x.PinYin, x.ParentID });
            return ApiResult.Success("", result);
        }





        #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 (demodel.CarType.HasValue && (demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.JJ || demodel.CarType == Common.Enum.Goods.GuideCarGoodsTypeEnum.SJ))
            {
                demodel.UseDay = 1;
            }
            else {
                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.Date.Subtract(tempStartTime.Date);
                    demodel.UseDay = sp.Days + 1;
                }
            }

            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,
                        guidecartype = model.GuideCarType,
                        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 GetGuideCarInfoForPagePath(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());

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


        /// <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
            });
        }

        /// <summary>
        /// 根据地址获取经纬度
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLngAndLat(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject prams = JObject.Parse(req.msg.ToString());
            string address = prams.GetStringValue("Address");
            var array = Common.Plugin.HttpHelper.GetGeocoderLatitude(address);
            if (array[0] != "" && array[1] != "")
            {
                return ApiResult.Success("", new { lng = array[0], lat = array[1] });
            }
            else
            {
                return ApiResult.Failed("获取地址错误");
            }
        }


        #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;
            if (query.ID == 0)
            {
                return ApiResult.Failed("请传入您要查询的导游ID");
            }
            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 GetSiteRegionList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_GuideCar_SiteRegion_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.SiteType = 1;
            var siteRegionList = guideCarModule.GetListRepository(query);
            if (siteRegionList == null)
            {
                siteRegionList = new List<RB_GuideCar_SiteRegion_Extend>();
            }
            JObject parm = JObject.Parse(parms.msg.ToString());
            var list = destinationModule.GetAllList();
            var result = siteRegionList.Select(x => new
            {
                x.ID,
                x.SiteId,
                x.RegionId,
                x.RegionName
            });
            return ApiResult.Success("", result);
        }


        /// <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;
            if (query.ID == 0)
            {
                return ApiResult.Failed("请传入您要查询的车辆ID");
            }
            var oldLogisticsModel = guideCarModule.GetGuideCarModel(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_GuideCar_Car_Extend();
            }
            if ((int)oldLogisticsModel.CarClass > 0)
            {
                oldLogisticsModel.CarClassStr = EnumHelper.GetEnumName(oldLogisticsModel.CarClass);
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 获取全部车辆品牌
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGuideCarBrandList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_GuideCar_CarBrand_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var list = guideCarModule.GetGuideCarBrandList(query);
            var result = list.Select(x => new { x.ID, x.Name, x.BrandLogo });
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 获取商品评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsCommentPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Is_Show = 1;
            var list = guideCarModule.GetGoodsDetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {

                x.GoodsId,
                x.UserId,
                UserName = x.Is_Anonymity == 1 ? "匿名用户" : x.UserName,
                UserPhotoPath = x.UserPhotoPath ?? "",
                x.CommentGrade,
                CommentGradeName = x.CommentGrade > 0 ? ((Common.Enum.Goods.GoodsCommentTypeEnum)x.CommentGrade).GetEnumName() : "",
                CommentList = x.CommentList.Select(y => new
                {
                    y.CommentScore,
                    y.CommentImgList,
                    y.Content,
                    y.Reply,
                    y.GuideName,
                    y.CarBrandName,
                    y.CarColorName,
                    y.CarName,
                    CreateDate = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    y.CarId,
                    y.GuideId
                })
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取商品评论统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsCommentStatistics(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());

            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);

            return guideCarModule.GetGuideCarCommentStatistics(GoodsId, req.TenantId, req.MallBaseId);
        }


    }
}