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;
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(req.msg.ToString());
            if ((demodel.OrderDetailId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细OrderDetailId");
            }
            if ((demodel.GoodsId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品");
            }

            if ((demodel.GuideId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递导游");
            }
            if ((demodel.CarId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递车辆");
            }
            if ((demodel.GuideScore ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请您对导游评分");
            }
            if ((demodel.CarScore ?? 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(demodel);
            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 GetAppletGoodsMyOrderPageList()
        {
            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;
            }
            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.Number,
                    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 = x.OrderStatus.GetEnumName(),
                x.TenantId,
                x.MallBaseId,
                x.PresentFXGrade,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

    }
}