using jiouosdp.Models;
using LitJson;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace jiouosdp.Controllers.Crowdfundings
{
    public class CrowdfundingController : BaseWeiXinController
    {
        //
        // GET: /Crowdfunding/
        //首页

        #region Page Actions

        public ActionResult Index()
        {
            #region 分享
            var share = new Share(Request.Url.ToString())
            {
                title = "一元夺宝",
                desc = "快来夺宝吧!",
            };

            if (string.IsNullOrEmpty(CookieManage.GetCookie(SessionKeys.ShareDistribution)) == true)
            {
                var mentity = DistributionManage.GetStoreInfo();
                share.imgUrl = mentity.Logo;
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "Crowdfunding/Index?inviter=" + OpenID;
            }
            else
            {
                var member = GetCurrentMember();
                share.imgUrl = member.HeadImgUrl;
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "Crowdfunding/Index?did=" + CookieManage.GetCookie(SessionKeys.ShareDistribution) + "&inviter=" + OpenID;
            }
            ViewBag.sharejs = share.CreateShareToHtml();

            #endregion
            return View();
        }

        public JsonResult GetLotteryName(Guid perid)
        {
            string name = CrowdWinningManage.GetLotteryName(perid);
            return Json(new { Result = "OK", Name = name });
        }

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

        //夺宝记录
        public ActionResult IndianaRecord()
        {
            return View();
        }
        //个人中心
        public ActionResult MyCenter()
        {
            return View();
        }
        #region 购物车
        public ActionResult Car()
        {
            return View();
        }

        public JsonResult AddCart(Guid ProductCrowdPeriodGuid, int CrowdPeriods, int TotalTime, int RemainTime, Guid ProductCrowdGuid, string ProductName, string ProductImage, int quantity, int unitPrice)
        {
            CrowdfundingCar.SetCar(new CrowdProduct() { ProductCrowdPeriodGuid = ProductCrowdPeriodGuid, CrowdPeriods = CrowdPeriods, TotalTime = TotalTime, RemainTime = RemainTime, ProductCrowdGuid = ProductCrowdGuid, ProductName = ProductName, ProductImage = ProductImage, MyBuyTime = quantity, UnitBuy = unitPrice });
            return Json(new { Result = "OK" });
        }
        public JsonResult DelCart(Guid ProductCrowdPeriodGuid)
        {
            CrowdfundingCar.Del(ProductCrowdPeriodGuid);
            return Json(new { Result = "OK" });
        }
        public JsonResult SaveCart(string guids, string quantity)
        {
            CrowdfundingCar.Save(guids, quantity);
            return Json(new { Result = "OK" });
        }


        public ActionResult CarBuy()
        {
            return View();
        }
        public JsonResult AddBuyCart(Guid ProductCrowdPeriodGuid, int CrowdPeriods, int TotalTime, int RemainTime, Guid ProductCrowdGuid, string ProductName, string ProductImage, int quantity, int unitPrice)
        {
            CrowdfundingCar.SetBuyCar(new CrowdProduct() { ProductCrowdPeriodGuid = ProductCrowdPeriodGuid, CrowdPeriods = CrowdPeriods, TotalTime = TotalTime, RemainTime = RemainTime, ProductCrowdGuid = ProductCrowdGuid, ProductName = ProductName, ProductImage = ProductImage, MyBuyTime = quantity, UnitBuy = unitPrice });
            return Json(new { Result = "OK" });
        }
        public JsonResult SaveBuyCart(string guids, string quantity)
        {
            CrowdfundingCar.SaveBuy(guids, quantity);
            return Json(new { Result = "OK" });
        }

        public JsonResult SubmitOrder(string type)
        {
            if (!RecieverAddressManage.CurrentUserHasDefault()) return Json(new { Result = "NO Address" });

            Result result;
            string orderNo;
            if (type == "car")
            {
                result = CrowdParticipateManage.SubmitOrder(CrowdfundingCar.GetProduct(), out orderNo, GetIP());
            }
            else
            {
                result = CrowdParticipateManage.SubmitOrder(CrowdfundingCar.GetBuyProduct(), out orderNo, GetIP());
            }

            if (result.State == true)
                return Json(new { Result = "OK", orderNo = orderNo });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        #endregion

        //支付订单
        public ActionResult PayOrders()
        {
            return View();
        }

        #endregion

        #region 晒单分享  panwp

        public ActionResult ShareOrder(Guid productCrowdPeriodGuid)
        {
            return View();
        }

        public JsonResult SaveShare(T_CR_Share entity)
        {
            var result = ShareManage.AddShare(entity);

            if (!result.State) return Json(new { Result = "NO", Msg = result.Msg });

            return Json(new { Result = "OK" });
        }

        [HttpPost]
        public void Upload()
        {
            string returnstr = string.Empty;
            string relativePath = string.Empty;
            try
            {
                foreach (string upload in Request.Files)
                {
                    var file = Request.Files[upload];
                    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 = DictionaryConst.UpLoadPath.ShareImgPath;
                    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 计算结果  panwp

        public ActionResult ComputedResult(Guid winningGuid)
        {
            var winning = CrowdWinningManage.GetEntity(winningGuid);

            if (winning == null) return ErrorContent("未找到中奖记录！");

            if (winning.ProductCrowdPeriodGuid == null || winning.ProductCrowdPeriodGuid.Value == Guid.Empty)
                return ErrorContent("期数表ID不能为空！");

            var period = ProductCrowdPeriodsManage.GetEntity(winning.ProductCrowdPeriodGuid.Value);

            if (period == null) return ErrorContent("未找到产品期数！");

            if (winning.LotteryResultGuid == null || winning.LotteryResultGuid.Value == Guid.Empty)
                return ErrorContent("未找到开奖结果！");

            var lotteryResult = LotteryResultManage.GetEntity(winning.LotteryResultGuid.Value);

            if (lotteryResult == null) return ErrorContent("未找到开奖结果！");

            ViewBag.LotteryResult = lotteryResult;
            ViewBag.Period = period;
            ViewBag.Winning = winning;

            return View();
        }

        #endregion

        #region  产品详情   panwp

        public ActionResult ProductInfo(Guid crowdPeriodsGuid)
        {
            var crowdPeriods = ProductCrowdPeriodsManage.GetEntity(crowdPeriodsGuid);

            if (crowdPeriods == null) return ErrorContent("未找到商品！");

            ProductCrowdModel model = new ProductCrowdModel();
            model.CrowdPeriods = crowdPeriods;

            var crowdProd = ProductCrowdManage.GetProductCrowd(crowdPeriods.ProductCrowdGuid);
            #region 分享
            var share = new Share(Request.Url.ToString())
            {
                imgUrl = CurrentManage.CurrentDomainWx + crowdProd.ProductImage,
                title = crowdProd.ProductName,
                desc = string.Format("还剩下{0}次,快来夺宝吧!", crowdPeriods.RemainTime),
            };

            if (string.IsNullOrEmpty(CookieManage.GetCookie(SessionKeys.ShareDistribution)) == true)
            {
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "Crowdfunding/ProductInfo?crowdPeriodsGuid=" + crowdPeriodsGuid + "&inviter=" + OpenID;

            }
            else
            {
                share.shareOpenUrl = CurrentManage.CurrentDomainWx + "Crowdfunding/ProductInfo?did=" + CookieManage.GetCookie(SessionKeys.ShareDistribution) + "&crowdPeriodsGuid=" + crowdPeriodsGuid + "&inviter=" + OpenID;
            }
            ViewBag.sharejs = share.CreateShareToHtml();

            #endregion


            return View(model);
        }

        //分页获取商品
        public JsonResult GetProductList(int page)
        {
            var list = ProductCrowdPeriodsManage.GetPageList(new GridModel() { page = page });

            if (list == null || list.Count <= 0) return Json(new { Result = "NoData" });

            return Json(new { Result = "OK", List = ProductCrowdModel.ForList(list), page = page + 1 });
        }

        #endregion

        #region 全部商品 panwp

        public ActionResult AllProduct(GridModel gridModel)
        {
            var list = ProductCrowdPeriodsManage.GetPageList(gridModel);

            if (list == null || list.Count <= 0) return View(new List<ProductCrowdModel>(0));

            return View(ProductCrowdModel.ForList(list));
        }
        //分页参与记录
        public JsonResult GetParticipateList(int page, Guid crowdPeriodGuid)
        {
            var list = CrowdParticipateManage.GetPageList(new GridModel() { page = page, rows = 5 }, crowdPeriodGuid);

            if (list == null || list.Count <= 0) return Json(new { Result = "NoData" });

            return Json(new { Result = "OK", List = list, page = page + 1 });
        }

        #endregion

        #region 图文详情 panwp

        public ActionResult TxtDetail(Guid productCrowdGuid)
        {
            var product = ProductCrowdManage.GetProductCrowd(productCrowdGuid);

            if (product == null) return ErrorContent("未找到商品！");

            return View(product);
        }
        #endregion

        #region 往期产品详情页 panwp

        public ActionResult OldTimeyDetails(Guid winningGuid)
        {
            var winning = CrowdWinningManage.GetWinningEntity(winningGuid);

            if (winning == null) return ErrorContent("未找到中奖记录！");

            var model = CrowdParticipateManage.GetFirstParticipate(winning.ProductCrowdPeriodGuid.Value);

            if (model != null)
            {
                ViewBag.FirstTime = model.CrowdDate.ToString("yyyy-MM-dd HH:mm:ss");
            }
            return View(winning);
        }

        #endregion

        #region 夺宝记录
        public ActionResult IndianaRecordAll()
        {
            return View();
        }
        public ActionResult IndianaRecording()
        {
            return View();
        }
        public ActionResult IndianaRecorded()
        {
            return View();
        }
        public JsonResult GetPariticipateListPage(int page, int state)
        {
            var list = CrowdParticipateManage.GetCrowdParticipateRecordPageList(new GridModel() { page = page, rows = 10 }, state);
            return Json(list);
        }

        public JsonResult GetMyLuckyNumbers(Guid productCrowdPeriodGuid)
        {
            var list = CrowdParticipateManage.GetMyLuckyNums(productCrowdPeriodGuid, (a, b) => new { b.LuckyNum });

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

            return Json(new { Result = "OK", List = list });
        }
        #endregion

        #region 往期揭晓
        public ActionResult OldTimeyResult(Guid crowdGuid)
        {
            ViewBag.Crowd = ProductCrowdManage.GetProductCrowdLastPeriod(crowdGuid);
            ViewBag.Id = crowdGuid;
            return View();
        }
        public JsonResult GetWinPage(int page, Guid crowdGuid, int? period)
        {
            var list = ProductCrowdManage.GetWinnigPage(new GridModel() { page = page, rows = 10 }, crowdGuid, period);
            return Json(list);
        }
        #endregion

        #region 我的晒单
        //我的所有晒单
        public ActionResult MyBask()
        {
            return View();
        }
        public JsonResult GetSharePage(int page)
        {
            var list = ShareManage.GetSharePageList(new GridModel() { page = page, rows = 10 });
            return Json(list);
        }
        //每一期所有晒单
        public ActionResult AllBask(Guid productid)
        {
            ViewBag.id = productid;
            return View();
        }
        public JsonResult GetAllSharePage(int page, Guid productid)
        {
            var list = ShareManage.GetAllSharePageList(new GridModel() { page = page, rows = 10 }, productid);
            return Json(list);
        }
        //晒单详情
        public ActionResult BaskDetail(Guid perodGuid, Guid shareGuid)
        {
            ViewBag.WinProduct = ProductCrowdManage.GetWinProduct(perodGuid);
            ViewBag.Share = ShareManage.GetShare(shareGuid);

            return View();
        }


        #endregion

        #region 中奖记录
        //中奖记录-待发货
        public ActionResult OrderDaiFa()
        {
            return View();
        }
        //中奖记录-待收
        public ActionResult WinningDaiShou()
        {
            return View();
        }
        //中奖记录-已完成
        public ActionResult OrderCompleted()
        {
            return View();
        }

        public ActionResult Address(Guid winningGuid)
        {
            ViewBag.id = winningGuid;
            return View();
        }

        public JsonResult GetOrderListPage(int page, int state)
        {
            var list = CrowdParticipateManage.GetCrowdParticipatePageList(new GridModel() { page = page, rows = 10 }, state);
            return Json(list);
        }

        public JsonResult UpdateStateComplete(Guid id)
        {
            var result = CrowdParticipateManage.UpdateStateComplete(id);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        #endregion
    }
}
