using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
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 AppletGCOrderController : BaseController
    {
        private readonly GuideCarModule guideCarModule = new GuideCarModule();
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();

        #region 订单信息
        /// <summary>
        /// 司导商品结算页面详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletSDGoodsSettlementInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }
            if (!demodel.TripSTime.HasValue)
            {
                return ApiResult.ParamIsNull("请传递预约起始时间");
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            return guideCarModule.GetAppletSDGoodsSettlementInfo(demodel);
        }

        /// <summary>
        /// 获取商品可预约日期列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletSDGoodsTargetDateList()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            string Month = parms.GetStringValue("Month");
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品id");
            }

            var list = guideCarModule.GetAppletSDGoodsTargetDateList(GoodsId, Month);
            return ApiResult.Success("", list);
        }

        #endregion

        #region 订单评论
        /// <summary>
        /// 用户新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGuideCarCommentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            List<RB_Goods_Comment_Extend> list = JsonConvert.DeserializeObject<List<RB_Goods_Comment_Extend>>(req.msg.ToString());
            if (list != null && list.Any())
            {

                if (list.Where(x => (x.GuideId ?? 0) > 0).Count() == 0)
                {
                    return ApiResult.ParamIsNull("请传递导游");
                }
                if (list.Where(x => (x.CarId ?? 0) > 0).Count() == 0)
                {
                    return ApiResult.ParamIsNull("请传递车辆");
                }
            }
            else
            {
                return ApiResult.ParamIsNull("请选择您要评论的信息");
            }
            foreach (var demodel in list)
            {
                if ((demodel.OrderDetailId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递订单明细OrderDetailId");
                }
                if ((demodel.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品");
                }
                if (string.IsNullOrEmpty(demodel.Content))
                {
                    return ApiResult.ParamIsNull("请输入评价内容");
                }
                demodel.CommentImage = "";
                if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
                {
                    demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
                }
                demodel.CommentGrade ??= Common.Enum.Goods.GoodsCommentTypeEnum.Praise;
                demodel.CommentScore ??= 5;
                if (demodel.CommentScore == 3 || demodel.CommentScore == 2)
                {
                    demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Medium;
                }
                else if (demodel.CommentScore == 1)
                {
                    demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Negative;
                }
                demodel.UserPhoto ??= 0;
                demodel.Is_Top ??= 2;
                demodel.Is_Show ??= 1;
                demodel.Is_Anonymity ??= 2;
                demodel.UserId ??= 0;
                demodel.Reply ??= "";
                demodel.TenantId = userInfo.TenantId;
                demodel.MallBaseId = userInfo.MallBaseId;
                demodel.UserId = userInfo.UserId;
                demodel.UserName = userInfo.Name;
                demodel.PlatformSource = userInfo.Source;
                demodel.Status = 0;
                demodel.CreateDate = DateTime.Now;
                demodel.UpdateDate = DateTime.Now;
            }

            bool flag = guideCarModule.SetGoodsCommentInfo(list);
            if (flag)
            {
                var demodel = list.FirstOrDefault();
                var dmodel = guideCarModule.GetOrderDetailInfo(demodel.OrderDetailId ?? 0);
                if (dmodel != null && dmodel.CommentGiveIntegral > 0 && demodel.UserId > 0)
                {
                    Model.Entity.User.RB_Member_Integral memberIntegralModel = new Model.Entity.User.RB_Member_Integral
                    {
                        UserId = demodel.UserId,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        PlatformType = demodel.PlatformSource,
                        Integral = dmodel.CommentGiveIntegral,
                        Description = "评论赠送" + dmodel.CommentGiveIntegral + "积分",
                        TenantId = demodel.TenantId,
                        MallBaseId = demodel.MallBaseId,
                        Remarks = "评论商品" + dmodel.GoodsName + "赠送" + dmodel.CommentGiveIntegral + "积分",
                        CreateDate = demodel.CreateDate,
                        OrderId = dmodel.OrderId
                    };
                    bool integralResult = guideCarModule.AddMemberIntegral(memberIntegralModel);
                    if (integralResult)
                    {
                        return ApiResult.CouponSuccess(ResultCode.Success, 2, "", dmodel.CommentGiveIntegral.ToString());
                    }
                    else
                    {
                        return ApiResult.CouponSuccess(ResultCode.Fail, 2, "", "");
                    }
                }

                return ApiResult.CouponSuccess(ResultCode.Fail, 2, "", "");


            }
            else { return ApiResult.CouponFailed(ResultCode.Fail, 2, "", ""); }
            // if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }



        /// <summary>
        /// 获取司导订单状态枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GuidCarOrderStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(GuidCarOrderStatusEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }



        /// <summary>
        /// 我的订单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsGuidecarOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Recycled = 2;
            if (demodel.OrderStatus == Common.Enum.Goods.OrderStatusEnum.WaitSendGoods)
            {
                demodel.OrderStatusIds = "2,6";//待处理也是待发货状态才有的
                demodel.OrderStatus = 0;
            }
            // demodel.OrderType = 11;//固定变成11，司导订单
            demodel.OrderClassify = 1;
            var list = guideCarModule.GetAppletGoodsMyOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            //获取订阅消息
            var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                template_message_list,
                x.OrderId,
                x.OrderNo,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.CouponMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                DetailList = x.DetailList.Select(y => new
                {
                    y.Id,
                    y.GoodsId,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    y.SpecificationSort,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Unit_Price,
                    y.Number,
                    y.UseDay,
                    y.IsSpell,
                    y.CarNumber,
                    y.LineName,
                    y.IsComment,
                    TripSTime = y.TripSTime.HasValue ? y.TripSTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    TripETime = y.TripETime.HasValue ? y.TripETime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                }),
                x.OrderStatus,
                OrderStatusName = ((GuidCarOrderStatusEnum)x.OrderStatus).GetEnumName(),
                x.GuideName,
                x.GuidePhoto,
                x.GuideTelephone,
                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 GetAppletGuidecarOrderOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            //HK2020-08-08新增
            if (parms.GetInt("NewUserId") > 0)
            {
                userInfo.UserId = parms.GetInt("NewUserId");
            }
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            return guideCarModule.GetAppletMyOrderInfo(OrderId, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        }

        #endregion

    }
}