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

namespace Mall.WebApi.Controllers.MarketingCenter
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletCouponController : BaseController
    {
        private CouponModule couponModule = new CouponModule();
        private ProductModule productModule = new ProductModule();

        /// <summary>
        /// 获取用户未使用的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoUseCouponList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            //if (userInfo == null)
            //{
            //    userInfo.TenantId = 1;
            //    userInfo.MallBaseId = 1;
            //    userInfo.UserId = 3;
            //}
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            var list = couponModule.GetNoUseCouponList(query);

            //获取优惠券对应的商品，或者分类
            List<RB_Product_Category_Extend> categotyList = new List<RB_Product_Category_Extend>();

            List<RB_DiscountCoupon_Product_Extend> productList = new List<RB_DiscountCoupon_Product_Extend>();

            string Ids = "";
            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
            {
                productList.AddRange(item.ProductList);
                item.CategoryIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                categotyList = productModule.GetCategoryListModule(new Model.Extend.Product.RB_Product_Category_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CategoryIds = Ids });
            }

            if (categotyList == null || !categotyList.Any())
            {
                categotyList = new List<RB_Product_Category_Extend>();
            }



            List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();

            productList = new List<RB_DiscountCoupon_Product_Extend>();

            Ids = "";

            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
            {
                productList.AddRange(item.ProductList);
                item.GoodsIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }

            if (!string.IsNullOrWhiteSpace(Ids))
            {
                goodsList = productModule.GetProductGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, GoodsIds = Ids });
            }
            if (goodsList == null || !goodsList.Any())
            {
                goodsList = new List<RB_Goods_Extend>();
            }
            var result = list.Select(x => new
            {
                id = x.MemberCouponId,
                mall_id = userInfo.MallBaseId,
                user_id = userInfo.UserId,
                coupon_id = x.ID,
                sub_price = x.DiscountsPrice,
                discount = x.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount ? x.DiscountsPrice : 10,
                coupon_min_price = x.MinConsumePrice,
                type = (int)x.CouponType,
                start_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                is_use = 0,
                is_delete = 0,
                created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                deleted_at = "0000-00-00 00:00:00",
                receive_type = "",
                discount_limit = x.MaxDiscountsPrice,
                coupon_data = new
                {
                    id = x.ID,
                    mall_id = userInfo.MallBaseId,
                    name = x.Name,
                    type = (int)x.CouponType,
                    discount = x.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount ? x.DiscountsPrice : 10,
                    pic_url = "",
                    desc = "",
                    min_price = x.MinConsumePrice,
                    sub_price = x.DiscountsPrice,
                    total_count = x.TotalNum + x.ReceiveNum,
                    sort = x.Sort,
                    expire_type = x.IndateType,
                    expire_day = x.IndateDay,
                    begin_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    appoint_type = (int)x.UseType,
                    rule = x.Describe,
                    is_member = x.OnlyMember,
                    is_delete = 0,
                    deleted_at = "0000-00-00 00:00:00",
                    created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    discount_limit = x.MaxDiscountsPrice,
                    car = categotyList.Where(y => x.CategoryIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        mch_id = 0,
                        parent_id = y.ParentId,
                        name = y.Name,
                        pic_url = y.AdvertisingImagePath,
                        sort = y.Sort,
                        big_pic_url = y.BigIconPath,
                        advert_pic = y.AdvertisingImage,
                        advert_url = y.AdvertisingImagePath,
                        status = y.Status,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                        is_show = y.IsShow,
                        advert_open_type = "",
                        advert_params = ""
                    }),
                    goods = goodsList.Where(y => x.GoodsIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        name = y.Name,
                        original_price = y.OriginalPrice,
                        cost_price = y.CostPrice,
                        detail = y.GoodsDetails,
                        cover_pic = y.CoverImage,
                        pic_url = "",
                        video_url = y.VideoAddress,
                        unit = y.Unit,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                    }),
                },
                x.Name,
                x.Describe,
                x.MinConsumePrice,
                x.CouponType,
                x.MaxDiscountsPrice,
                x.UseType
            });
            return ApiResult.Success("", result);

        }
    }
}