using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RFrameGenerate.BLL;
using RFrameGenerate.BLL.Products;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using System.IO;
using System.Collections;
using LitJson;
using System.Text.RegularExpressions;
using RFrameGenerate.Model.PageModel;

namespace jiouosdp.Controllers.WX
{
    public class WxShopController : BaseWeiXinController
    {
        //
        // GET: /WxShop/

        public ActionResult Index(string did)
        {
            if (CurrentManage.IsDistribution == true && CurrentUser.GetDistributionGuid() != null)
                did = CurrentUser.GetDistributionGuid().ToString();

            if (CurrentManage.MerchantUserID == "nxhtqtjt")
            {
                return RedirectToAction("NxhtqtjtIndex", new { did = did });
            }
            else
            {
                var page = RFrameGenerate.BLL.DIVShop.WinportPageManage.CurrentPage();

                if (page != null && page.WinportPageGuid != Guid.Empty) return RedirectToAction("Index", "DiyShop", new { pageGuid = page.WinportPageGuid });

                #region 分享
                var param = RFrameGenerate.BLL.ParameterManage.GetShareParameter();
                var share = new Share(Request.Url.ToString())
                {
                    title = param.ParameterValue,
                    desc = param.ParameterDescription,
                };
                if (string.IsNullOrEmpty(did) == true)
                {
                    var memeber = GetCurrentMember();
                    if (memeber != null)
                    {
                        share.imgUrl = memeber.HeadImgUrl;
                    }
                    else
                    {
                        var mlist = DistributionManage.GetStoreInfo();
                        share.imgUrl = mlist.Logo;
                    }
                    share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/Index" + "?inviter=" + OpenID;
                }
                else
                {
                    var mentity = DistributionManage.GetStoreInfo();
                    share.imgUrl = mentity.Logo;
                    share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/Index?did=" + did + "&inviter=" + OpenID;
                }
                ViewBag.sharejs = share.CreateShareToHtml();

                #endregion

                ViewBag.PageNum = MerchantManage.GetPageProductNum();
                return View();
            }
        }

        #region 定制
        #region 牛宝林商贸商城
        public ActionResult NxhtqtjtIndex(string did)
        {
            #region 分享
            var param = RFrameGenerate.BLL.ParameterManage.GetShareParameter();
            var share = new Share(Request.Url.ToString())
            {
                title = param.ParameterValue,
                desc = param.ParameterDescription,
            };
            if (string.IsNullOrEmpty(did) == true)
            {
                var memeber = GetCurrentMember();
                if (memeber != null)
                {
                    share.imgUrl = memeber.HeadImgUrl;
                }
                else
                {
                    var mlist = DistributionManage.GetStoreInfo();
                    share.imgUrl = mlist.Logo;
                }
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/NxhtqtjtIndex" + "?inviter=" + OpenID;
            }
            else
            {
                var mentity = DistributionManage.GetStoreInfo();
                share.imgUrl = mentity.Logo;
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/NxhtqtjtIndex?did=" + did + "&inviter=" + OpenID;
            }
            ViewBag.sharejs = share.CreateShareToHtml();

            #endregion
            ViewBag.PageNum = MerchantManage.GetPageProductNum();
            return View();
        }
        #endregion
        /// <summary>
        /// 商品详情页
        /// </summary>
        /// <returns></returns>
        /// 
        #endregion

        public ActionResult ProductInfo(Guid productsGuid, Guid? did = null)
        {

            var product = ProductsManage.GetProductByGuidPutaway(productsGuid);

            if (product == null)
                return new ErrorResult("没找到商品或您绑定其它商家无法查看.");
            if (product.IsPutaway != true)
                return new ErrorResult("商品已经下架");

            ViewBag.product = product;

            var share = new Share(Request.Url.ToString())
            {
                title = product.ProductName,
                desc = "快来抢购吧!",
                imgUrl = CurrentManage.CurrentDomainWx + product.ProductImage
            };
            if (CurrentManage.IsDistribution == true)
            {//是分销商分销分享自己的店铺
                var prop = DistributionManage.GetDistributionProp(CurrentUser.GetCurrUserGuid());
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/productinfo?did=" + prop.DistributionPropGuid + "&productsguid=" + productsGuid + "&inviter=" + OpenID;
            }
            else
            {
                if (did == null)
                {
                    string did2 = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                    share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/productinfo?did=" + did2 + "&productsguid=" + productsGuid + "&inviter=" + OpenID;
                }
                else
                {
                    share.shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/productinfo?did=" + did + "&productsguid=" + productsGuid + "&inviter=" + OpenID;
                }
            }
            ViewBag.sharejs = share.CreateShareToHtml();

            var mlist = DistributionManage.GetStoreInfo();
            ViewBag.StoreName = mlist.SotreTitle;
            ViewBag.HeadImg = mlist.Logo;
            ViewBag.Name = product.ProductName;
            ViewBag.Guid = productsGuid;
            ViewBag.PriceLable = MerchantManage.GetPriceLable();
            ViewBag.IsStandards = product.IsStandards;
            ViewBag.MarketPrice = product.MarketPrice;
            ViewBag.Price = product.Price;
            ViewBag.Inventory = product.Inventory;

            //补充赠送积分 Bing 151218
            int Integral;
            var IntegraEntity = IntegralRulesManage.GetIntegralRuleByMerchant(CurrentManage.MerchantGuid, null);
            IntegralRulesManage.GetIntegral(ViewBag.Price, IntegraEntity, out Integral);
            ViewBag.Integral = Integral;


            //if (product.IsStandards)
            //{
            //    decimal minPrice = ProductSKUManage.GetSKUPrice(productsGuid, 0);
            //    decimal maxPrice = ProductSKUManage.GetSKUPrice(productsGuid, 1);
            //    ViewBag.Price = minPrice.ToString("f2") + "-" + maxPrice.ToString("f2");

            //    //var sku = Utils.GetCookie("cookie_sku_" + product.ProductGuid.ToString());
            //    //if (!string.IsNullOrEmpty(sku))
            //    //{
            //    //    var arr_sku = sku.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');
            //    //    decimal price = string.IsNullOrEmpty(arr_sku[0]) ? 0M : decimal.Parse(arr_sku[0]);
            //    //    ViewBag.Price = price;
            //    //    ViewBag.Inventory = string.IsNullOrEmpty(arr_sku[1]) ? 0 : int.Parse(arr_sku[1]);
            //    //    ViewBag.GroupGuid = arr_sku[2];
            //    //}
            //    //else
            //    //{

            //    //}
            //}
            //else
            //{

            //}
            return View();
        }

        /// <summary>
        /// 收藏
        /// </summary>
        /// <returns></returns>
        public ActionResult Collect()
        {
            return View();
        }
        /// <summary>
        /// 店铺已关闭
        /// </summary>
        /// <returns></returns>
        public ActionResult StoreClosed()
        {
            return View();
        }

        public ActionResult Follow(Guid weChatGuid)
        {
            if (weChatGuid != Guid.Empty)
            {
                ViewBag.WeChat = WeChatManage.GetWeChatByMearchantID(weChatGuid);
            }
            return View();
        }

        public ActionResult StoreInfo(string title, string logo, Guid did)
        {
            ViewBag.Guid = did;
            ViewBag.StoreTitle = title;
            ViewBag.Logo = logo;
            var model = DistributionManage.GetStoreInfo(did);
            if (model != null)
            {
                ViewBag.DistributionName = model.DistributionName;
                ViewBag.DistributionTelphone = model.DistributionTelphone;
            }
            return View();
        }
        /// <summary>
        /// 我要分销
        /// </summary>
        /// <returns></returns>
        public ActionResult WantToResell(Guid productsGuid, Guid did)
        {
            var mentity = DistributionManage.GetStoreInfo();
            ViewBag.StoreTitle = mentity.SotreTitle;
            ViewBag.StoreLogo = mentity.Logo;

            var product = ProductsManage.GetProductByGuid(productsGuid);
            var share = new Share(Request.Url.ToString())
            {
                title = product.ProductName,
                desc = "快来抢购吧!",
                imgUrl = CurrentManage.CurrentDomainWx + product.ProductImage,
                shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/productinfo?did=" + did + "&productsguid=" + productsGuid + "&inviter=" + OpenID
            };
            ViewBag.sharejs = share.CreateShareToHtml();
            ViewBag.Product = product;
            ViewBag.Guid = productsGuid;

            return View();
        }

        public ActionResult AllProduct(string productName)
        {
            string didstr = CookieManage.GetCookie(SessionKeys.ShareDistribution);
            Guid? did = null;
            if (string.IsNullOrEmpty(didstr) != true)
                did = Guid.Parse(didstr);

            var mentity = DistributionManage.GetStoreInfo();
            var param = ParameterManage.GetShareParameter();
            var share = new Share(Request.Url.ToString())
            {
                title = param.ParameterValue,
                desc = param.ParameterDescription,
                imgUrl = mentity.Logo,
                shareOpenUrl = CurrentManage.CurrentDomainWx + "WxShop/Index?did=" + did.ToString() + "&inviter=" + OpenID
            };

            ViewBag.sharejs = share.CreateShareToHtml();

            ViewBag.StoreShareType = ParameterMagage.GetStoreShareType();

            if (!string.IsNullOrEmpty(productName))
            {
                ViewBag.SearchKey = productName;
            }
            return View();
        }
        public JsonResult GetProductsList()
        {
            var productList = ProductsManage.GetList();
            return Json(productList);
        }

        public JsonResult GetProductInfo(Guid productsGuid, Guid did)
        {
            var product = ProductsManage.GetShareProducts(productsGuid, did, OpenID);

            if (product == null) return Json(new { Result = "NO" });

            return Json(product);
        }

        public JsonResult GetFavoriteList(Guid productsGuid)
        {
            var length = FavoritesManage.GetFavoriteList(productsGuid).Count;
            if (length > 0)
            {
                return Json(new { Result = "OK", Data = 1 });
            }
            return Json(new { Result = "NO", Data = 0 });
        }

        public JsonResult GetProductByPage(string searchKey, string categoty, int pageIndex = 1, string tabName = DictionaryConst.ProductTab.NewProduct)
        {
            string orderKey = "";
            switch (tabName)
            {
                case DictionaryConst.ProductTab.Price:
                    orderKey = "Price";
                    break;
                case DictionaryConst.ProductTab.SalesVolume:
                    orderKey = "SalesVolume";
                    break;
                default:
                    orderKey = "NewProduct";
                    break;
            }
            searchKey = searchKey ?? String.Empty;
            var list = ProductsManage.GetProductByPages(pageIndex, categoty, searchKey, orderKey);
            return Json(list);
        }
        public JsonResult GetCategoryList()
        {
            return Json(ProductCategorysManage.GetProductCategory());
        }

        public JsonResult AgainAppltBecome(T_BAS_ApplyDistributionRecords entity)
        {
            var result = ApplyDistributionRecordsManage.UpdateApplyStateByMember(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid(), entity, RFrameGenerate.BLL.DictionaryConst.Apply.Waiting);
            return Json(result.State ? new { Result = "OK", Msg = result.Msg } : new { Result = "NO", Msg = result.Msg });
        }

        /// <summary>
        /// is apply become distribution
        /// </summary>
        /// <returns></returns>
        public JsonResult GetApplyState()
        {
            var state = ApplyDistributionRecordsManage.GetApplyState();

            return Json(new { State = state });
        }

        public JsonResult ShowQrCodeImg()
        {
            var qr = DistributionManage.ShowQRCode(OpenID);
            return Json(qr != null ? new { Result = "OK", Msg = qr } : new { Result = "NO", Msg = (string)null });
        }

        public JsonResult GetMerchantInfo()
        {
            return Json(MerchantManage.GetEntity(RFrameGenerate.Common.CurrentManage.MerchantGuid));
        }

        public JsonResult GetName()
        {
            var name = DistributionManage.GetName();
            return Json(new { Result = "OK", Data = name });
        }

        public JsonResult SaveStoreInfo(T_BAS_DistributionProp entity)
        {
            var result = DistributionManage.SaveStoreInfo(entity);
            if (result.State)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ActionResult EditDistribution()
        {
            return View();
        }

        public JsonResult SaveDistriInfo(T_BAS_DistributionProp entity)
        {
            var result = DistributionManage.SaveDistriInfo(entity.DistributionName, entity.DistributionTelphone);
            if (result.State)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        #region 上传图片

        [HttpPost]
        public void Upload()
        {
            string returnstr = string.Empty;
            string relativePath = string.Empty;
            try
            {
                foreach (string upload in Request.Files)
                {
                    var file = Request.Files[upload];

                    if (file.ContentLength > 1024 * 1024)
                    {
                        throw new Exception("不合适的文件,图片大小不能超过1M");
                    }
                    string fileNameExt = Path.GetExtension(file.FileName).ToLower();

                    if (fileNameExt != ".jpg" && fileNameExt != ".gif" && fileNameExt != ".png" && fileNameExt != ".jpeg")
                    {
                        throw new Exception("不合适的文件,只能支持jpg|gif|png|jpeg的文件");
                    }

                    if (!UpLoadFileHelp.HasFile(file)) continue;

                    var dateTimeNow = DateTime.Now;
                    var basePath = string.Empty;

                    basePath = DictionaryConst.UpLoadPath.StoreLogoPath;

                    var fileName = dateTimeNow.ToString("yyyyMMddHHmmss")
                        + RadomCode.DigitalCode(3) + fileNameExt;

                    relativePath = basePath + "/" + fileName;
                    string DirUrl = Server.MapPath("~" + basePath);

                    UpLoadFileHelp.SaveInFileSystem(file, DirUrl, fileName);
                }

                Hashtable successHash = new Hashtable();
                successHash["error"] = 0;
                successHash["url"] = relativePath;
                Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                Response.Write(JsonMapper.ToJson(successHash));
                Response.End();

            }
            catch (Exception e)
            {
                MvcLog.Write("Error:{0},State:{1}", e.Message, e.StackTrace);
                Hashtable failueHash = new Hashtable();
                failueHash["error"] = 1;
                failueHash["message"] = e.Message;
                Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                Response.Write(JsonMapper.ToJson(failueHash));
                Response.End();
            }
        }

        #endregion

        #region 商品规格选择
        public ActionResult SKUInfo(Guid productsGuid)
        {
            var product = ProductsManage.GetProductByGuid(productsGuid);
            if (product != null)
            {
                ViewBag.ProductGuid = product.ProductGuid;
                ViewBag.ProductImage = product.ProductImage;
                ViewBag.ProductName = product.ProductName;
                ViewBag.IsStandards = product.IsStandards;
                ViewBag.Invenotory = product.Inventory;
                ViewBag.MarketPrice = product.MarketPrice;
                ViewBag.ProductImage = product.ProductImage;
                ViewBag.Price = product.Price;
                ViewBag.ProductClassify = product.ProductClassify;
                ViewBag.IsVirtual = (product == null ? false : product.ProductClassify == 2 ? true : false);
                if (product.IsStandards == true)
                {
                    ViewBag.MinPrice = ProductSKUManage.GetSKUPrice(productsGuid, 0);
                    ViewBag.MaxPrice = ProductSKUManage.GetSKUPrice(productsGuid, 1);
                    //ViewBag.Invenotory = ProductSKUManage.GetSKUInvenotory(productsGuid);

                    //补充赠送积分 Bing 151218
                    int MinIntegral;
                    int MaxIntegral;
                    var IntegraEntity = IntegralRulesManage.GetIntegralRuleByMerchant(CurrentManage.MerchantGuid, null);
                    IntegralRulesManage.GetIntegral(ViewBag.MinPrice, IntegraEntity, out MinIntegral);
                    IntegralRulesManage.GetIntegral(ViewBag.MaxPrice, IntegraEntity, out MaxIntegral);
                    ViewBag.IntegraEntity = IntegraEntity;
                    ViewBag.MinIntegral = MinIntegral;
                    ViewBag.MaxIntegral = MaxIntegral;

                    ViewBag.ListSKUName = ProductSKUManage.GetSKUNameList(productsGuid);
                }
            }

            return View();



        }

        public JsonResult GetProductDetails(string skuValue, Guid productGuid)
        {
            if (string.IsNullOrEmpty(skuValue))
            {
                return Json(new { Result = "NO", Msg = "请选择商品规格！" });
            }
            var arrValus = skuValue.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');
            PT_BAS_ProductSKU entity = new PT_BAS_ProductSKU();
            int integral = 0;
            var result = ProductSKUManage.GetProductInfo(arrValus, productGuid, ref entity, ref integral);
            if (result.State)
            {
                if (entity != null)
                {
                    return Json(new { Result = "OK", Product = entity, integral = integral });
                }
                else
                {
                    return Json(new { Result = "NO", integral = integral });
                }
            }
            else
                return Json(new { Result = "NO", Msg = result.Msg, integral = integral });
        }


        #endregion

        #region 选择商品分类
        public ActionResult ProductCategory()
        {
            return View();
        }
        #endregion


        #region 分销申请

        /// <summary>
        /// 成为分销商
        /// </summary>
        /// <returns></returns>
        public ActionResult BecomeReseller()
        {
            var applyDistributionState = DistributionManage.GetApplyDistributionRecord(CurrentUser.GetCurrUserGuid());
            ViewBag.ApplyState = applyDistributionState;
            if (applyDistributionState == null || applyDistributionState.State == DictionaryConst.Apply.None)
            {
                using (var tran = new SqlRTransaction())
                {
                    ViewBag.ShareName = RFrameGenerate.BLL.DistributionManage.GetShareName();
                    ViewBag.SotreTitle = RFrameGenerate.BLL.DistributionManage.GetShareTitle();

                    var BaseAmount = ParameterManage.GetParam(RFrameGenerate.BLL.ParameterName.DistributionMemeber.BaseAmount);
                    if (BaseAmount != null && string.IsNullOrEmpty(BaseAmount.ParameterValue) != true)
                    {
                        ViewBag.Baseamount = BaseAmount.ParameterValue != null ? int.Parse(BaseAmount.ParameterValue) : 0;
                        if (ViewBag.Baseamount > 0)
                            ViewBag.TotalPrice = OrderManage.GetTotalMoney();
                    }
                }
            }
            else if (applyDistributionState.State == DictionaryConst.Apply.Pass)
            {
                return Redirect("/DistributionCenter/Index");
            }
            return View();
        }

        public JsonResult AddBecomeDistribution(string distributionName, string telphone)
        {
            var result = DistributionManage.ApplyDistribution(distributionName, telphone);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        public JsonResult Retry()
        {
            var result = DistributionManage.ApplyDistributionRetry();
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        #endregion
    }
}
