using RFrameGenerate.BLL;
using RFrameGenerate.BLL.Logistics;
using RFrameGenerate.BLL.Marketing;
using RFrameGenerate.BLL.Products;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace jiouosdp.Controllers.WX
{

    public class CartController : BaseWeiXinController
    {
        //
        // GET: /Cart/

        public ActionResult Index()
        {
            //var member = GetCurrentMember();
            //Response.Write(Request.Url.ToString()+"<br/>");
            //Response.Write(OpenID + "<br/>");
            //Response.Write(RFrameGenerate.Common.CurrentManage.MerchantGuid + "<br/>");
            return View();
        }

        public JsonResult RemoveFavor(string data, int stateCode = 0)
        {
            var result = FavoritesManage.RemoveFavor(data, stateCode);
            if (result.State == true)
            {
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }

        public ActionResult OrderConfirm(Guid? addid)
        {
            ViewBag.IsCoupons = true;
            var mentity = DistributionManage.GetStoreInfo();
            RFrameGenerate.Model.T_BAS_RecieverAddress address = null;
            if (addid != null)
            {
                address = RFrameGenerate.BLL.RecieverAddressManage.GetSelectAddress(addid.Value);
            }
            else
            {
                address = RFrameGenerate.BLL.RecieverAddressManage.GetDefaultAddress(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            }
            var list = Session[SessionKeys.COOKIE_CartConfirm] as List<OrderConfirm>;

            var isVirtual = false;
            List<T_ST_MemberCoupons> coupons = null;
            T_BAS_Products product = null;
            if (list.Count == 1)
            {
                product = ProductsManage.GetEntity(list.First().id);

                if (product == null) return Content("不存在商品！");


                ViewBag.Product = product;
                isVirtual = product != null && product.ProductClassify == 2 ? true : false;
            }

            PriceResult freight = null;
            if (isVirtual)
            {
                freight = new PriceResult(true, 0.0m);
            }
            else
            {
                freight = TemplatesManage.CalculationFreight(list, address);
            }
            if (!freight.State)
            {
                return Content(freight.Msg);
            }
            var level = RFrameGenerate.BLL.Member.MemberLevelManage.CurrentMemberLevel();

            list.ForEach(m =>
            {
                var discount = RFrameGenerate.BLL.Member.ProductDiscountManage.CurrentDiscount(level, m.id);

                if (discount != null && (discount.Value * m.price) >= 0.01m) { m.discountPrice = discount.Value; }

                else { m.discountPrice = 1; }
            });

            var totalAmount = list.Sum(a => a.price * a.discountPrice * a.quantity);

            if (ViewBag.Product == null || ViewBag.Product.ProductClassify != 3)
                coupons = ActivityDetailManage.GetAvailableCoupons(totalAmount + freight.Price, CurrentUser.GetCurrUserGuid());
            ViewBag.Coupons = coupons;
            ViewBag.Level = level;
            ViewBag.Freight = freight.Price;
            ViewBag.StoreTitle = mentity.SotreTitle;
            ViewBag.StoreLogo = mentity.Logo;
            ViewBag.OrderConfirmData = list;
            ViewBag.Address = address;
            var member = RFrameGenerate.BLL.MemberManage.GetMemberByGuid(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            ViewBag.totalIntegral = member.Integral ?? 0;

            return View();
        }

        public JsonResult ProductCheck(string data)
        {
            JavaScriptSerializer script = new JavaScriptSerializer();
            var list = script.Deserialize<List<OrderConfirm>>(data);
            var result = OrderManage.DealProduct(ref list);
            if (result.State == true)
            {
                Session[SessionKeys.COOKIE_CartConfirm] = list;
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }

        public JsonResult SubmitOrder(Guid addid, string remark, Guid? couponsGuid, bool isVirtual, bool hasIntegral, int? IntegralTe, decimal? integralMoney, int? PresentExp)
        {
            var list = Session[SessionKeys.COOKIE_CartConfirm] as List<OrderConfirm>;
            var result = OrderManage.DealProduct(ref list);
            if (result.State == true)
            {
                string orderNo = string.Empty;
                result = OrderManage.SubmitOrder(addid, remark, couponsGuid, isVirtual, hasIntegral, IntegralTe, integralMoney, PresentExp, list, out orderNo);
                if (result.State == true)
                {
                    return Json(new { Result = "OK", OrderNo = orderNo });
                }
                else
                    return Json(new { Result = "NO", Msg = result.Msg });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }

        public JsonResult GetSkuGroup(Guid guid)
        {
            string tips = "";
            var result = ProductSKUManage.GetSkuGroup(guid, ref tips);
            if (result.State == true)
            {
                return Json(new { Result = "OK", Tips = tips });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }


        public JsonResult GetIntegralTranData(int totalIntegral, decimal totalPrice)
        {
            return Json(IntegralRulesManage.GetIntegraltranData(totalPrice, totalIntegral, IntegralRulesManage.GetIntegralRuleByMerchant(CurrentManage.MerchantGuid)), JsonRequestBehavior.AllowGet);
        }
    }
}
