using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using RFrameGenerate.BLL;
using RFrameGenerate.Model;
using RFrameGenerate.Common;
using System.Net;
using RFramework.SQLServer;
using System.IO;
using Wechat.Model;

namespace jiouosdp.Controllers.WX
{
    public class DistributionCenterController : BaseWeiXinController
    {
        //
        // GET: /DistributionCenter/

        public ActionResult Index(string show)
        {
            var dist = DistributionManage.GetDistributionProp(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            if (dist != null && RFrameGenerate.Common.CurrentManage.IsDistribution == true)
            {
                if (dist.IsEnable != true)
                {
                    CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);
                    return Redirect("/Error/WarmPrompt?msg=店铺已关闭");
                }

                ViewBag.dist = dist;
                CookieManage.SetCookie(SessionKeys.ShareDistribution, dist.DistributionPropGuid.ToString(), 1);
                if (show == "1")
                {//点我的小店跳到我的小店
                    return Redirect("/WxShop/Index?did=" + dist.DistributionPropGuid);
                }

                return View();
            }
            else
            {
                return Redirect("/WxShop/BecomeReseller");
            }
        }

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

        public ActionResult DistributionDetail()
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                ViewBag.TotalBeClear = DistributionManage.GetTotal(did, true);
                ViewBag.TotalNotBeClear = DistributionManage.GetTotal(did, false);
            }
            return View();
        }

        public ActionResult MyTeam(Guid id, int teamNum)
        {
            var list = DistributionManage.GetMyTeamList(id);
            ViewBag.myteam = list.OrderByDescending(a => a.JoinDateTime).ToList();
            ViewBag.teamNum = teamNum;
            return View();
        }

        public ActionResult DistributionComWithdraws()
        {

            return View();
        }

        public ActionResult ShowQRcode(Guid did)
        {
            CookieManage.SetCookie(SessionKeys.ShareDistribution, did.ToString(), 1);
            var mentity = DistributionManage.GetStoreInfo();
            var backgoundImage = MerchantManage.GetBackgroundImgae();
            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();
            var StoreShareType = ParameterMagage.GetStoreShareType();
            ViewBag.StoreShareType = StoreShareType;
            #region 店铺二维码
            if (StoreShareType == DictionaryConst.StoreShareType.Store)
            {
                string qrcodeImage = DistributionManage.ShowQRCode(OpenID);
                #region 绘制二维码
                if (RFrameGenerate.BLL.ParameterMagage.GetImageType() == RFrameGenerate.BLL.DictionaryConst.ImageDistributionType.Image)
                {
                    var prop = DistributionManage.GetDistributeionProp(did);
                    var paramApp = ParameterManage.GetParameter(ParameterName.DistributionMemeber.AuditApproachNew, CurrentManage.MerchantGuid);

                    //检查文件是否存在,不存在重新生成
                    if (string.IsNullOrEmpty(prop.DistributionQRCode) != true)
                    {
                        string savePath = Server.MapPath("~/") + "\\" + prop.DistributionQRCode.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        if (System.IO.File.Exists(savePath) != true)
                            prop.DistributionQRCode = string.Empty;
                    }


                    if (string.IsNullOrEmpty(prop.DistributionQRCode) ||
                        (paramApp != null && int.Parse(paramApp.ParameterValue) == DictionaryConst.ApproachNew.Withoutm))
                    {
                        string url = "";
                        string savePath = Server.MapPath("~/" + DictionaryConst.UpLoadPath.DistributionQR) + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";
                        try
                        {
                            if (GraphicHelper.MadeRQ(mentity.Logo, backgoundImage, qrcodeImage.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0], prop.DistributionName, mentity.SotreTitle, savePath))
                            {
                                url = DictionaryConst.UpLoadPath.DistributionQR + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                                DistributionManage.UpdateDistributionQRCode(did, url);
                            }
                        }
                        catch (Exception ex)
                        {
                            Wechat.LogManage.Log("生成分销二维码异常:" + ex.Message);
                        }
                        ViewBag.Path = url;
                    }
                    else
                    {
                        ViewBag.Path = prop.DistributionQRCode;
                    }
                }
                #endregion
                #region 默认
                else
                {
                    ViewBag.StoreTitle = mentity.SotreTitle;
                    ViewBag.StoreLogo = mentity.Logo;
                    ViewBag.Name = DistributionManage.GetName(); ;
                    ViewBag.QRCode = qrcodeImage;
                    ViewBag.BackgroundImgae = backgoundImage;
                }
                #endregion
            }
            #endregion
            #region 带参数二维码
            else
            {
                var prop = DistributionManage.GetDistributeionProp(did);
                var paramApp = ParameterManage.GetParameter(ParameterName.DistributionMemeber.AuditApproachNew, CurrentManage.MerchantGuid);

                //检查文件是否存在,不存在重新生成
                if (string.IsNullOrEmpty(prop.DistributionQRCode) != true)
                {
                    string savePath = Server.MapPath("~/") + "\\" + prop.DistributionQRCode.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0];
                    if (System.IO.File.Exists(savePath) != true)
                        prop.DistributionQRCode = string.Empty;
                }

                if (string.IsNullOrEmpty(prop.DistributionQRCode) ||
                    (paramApp != null && int.Parse(paramApp.ParameterValue) == DictionaryConst.ApproachNew.Withoutm))
                {
                    string url = "";
                    string savePath = Server.MapPath("~/" + DictionaryConst.UpLoadPath.DistributionQRParam) + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";
                    try
                    {
                        if (string.IsNullOrEmpty(prop.QRCodeParamImage) == true)
                        {
                            QRCode qrcode = weixinopen.WeiXinOpenRequest.CreatePerpetualQRCode(did.ToString(), CurrentManage.AppId);
                            if (qrcode.state == true)
                            {

                                System.Drawing.Image image = weixinopen.WeiXinOpenRequest.GetQRCode(qrcode.ticket);
                                try
                                {
                                    if (System.IO.Directory.Exists(Path.GetDirectoryName(savePath)) != true)
                                        System.IO.Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                                finally
                                {
                                    image.Dispose();
                                }
                                url = DictionaryConst.UpLoadPath.DistributionQRParam + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                                DistributionManage.UpdateQRCodeParamImage(did, url);
                                prop.QRCodeParamImage = url;
                            }
                        }

                        savePath = Server.MapPath("~/" + DictionaryConst.UpLoadPath.DistributionQR) + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";
                  
                        //生成二维码
                        if (GraphicHelper.MadeRQ(mentity.Logo, backgoundImage, prop.QRCodeParamImage.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0], prop.DistributionName, mentity.SotreTitle, savePath))
                        {
                            url = DictionaryConst.UpLoadPath.DistributionQR + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                            DistributionManage.UpdateDistributionQRCode(did, url);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("生成公众号带参数二维码异常:" + ex.Message);
                    }
                    ViewBag.Path = url;
                }
                else
                {
                    ViewBag.Path = prop.DistributionQRCode;
                }
            }
            #endregion
            return View();
        }

        private string urlConvertor(string imagesurl1)
        {
            string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
            string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
            imagesurl2 = imagesurl2.Replace(@"/", @"/");
            //imagesurl2 = imagesurl2.Replace(@"Aspx_Uc/", @"");
            return imagesurl2;
        }


        #region 分销订单
        /// <summary>
        /// 所有订单
        /// </summary>
        /// <returns></returns>
        public ActionResult DistributionOrder()
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                ViewBag.Total = DistributionManage.GetTotal(did);
                var list = DistributionManage.GetDistributionList(did);
                if (list != null)
                {
                    ViewBag.List = list.Where(a => a.Level == 1).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.SList = list.Where(a => a.Level == 2).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.TList = list.Where(a => a.Level == 3).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                }
                else
                {
                    ViewBag.List = null;
                    ViewBag.SList = null;
                    ViewBag.TList = null;
                }
            }
            return View();
        }
        /// <summary>
        /// 已付款
        /// </summary>
        /// <returns></returns>
        public ActionResult DistributionOrderPaid()
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                ViewBag.Total = DistributionManage.GetTotal(did, DictionaryConst.OrderInnerState.WaitDelivery);
                var list = DistributionManage.GetDistributionList(did, DictionaryConst.OrderInnerState.WaitDelivery);
                if (list != null)
                {
                    ViewBag.List = list.Where(a => a.Level == 1).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.SList = list.Where(a => a.Level == 2).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.TList = list.Where(a => a.Level == 3).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                }
                else
                {
                    ViewBag.List = null;
                    ViewBag.SList = null;
                    ViewBag.TList = null;
                }
            }
            return View();
        }
        /// <summary>
        /// 待付款
        /// </summary>
        /// <returns></returns>
        public ActionResult DistributionOrderUnPaid()
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                ViewBag.Total = DistributionManage.GetTotal(did, DictionaryConst.OrderInnerState.Unpaid);
                var list = DistributionManage.GetDistributionList(did, DictionaryConst.OrderInnerState.Unpaid);
                if (list != null)
                {
                    ViewBag.List = list.Where(a => a.Level == 1).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.SList = list.Where(a => a.Level == 2).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.TList = list.Where(a => a.Level == 3).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                }
                else
                {
                    ViewBag.List = null;
                    ViewBag.SList = null;
                    ViewBag.TList = null;
                }
            }
            return View();
        }
        /// <summary>
        /// 已完成
        /// </summary>
        /// <returns></returns>
        public ActionResult DistributionOrderCompleted()
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                ViewBag.Total = DistributionManage.GetTotal(did, DictionaryConst.OrderInnerState.Completed);
                var list = DistributionManage.GetDistributionList(did, DictionaryConst.OrderInnerState.Completed);
                if (list != null)
                {
                    ViewBag.List = list.Where(a => a.Level == 1).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.SList = list.Where(a => a.Level == 2).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                    ViewBag.TList = list.Where(a => a.Level == 3).OrderByDescending(a => a.OrderTime).ThenBy(a => a.Level).ToList();
                }
                else
                {
                    ViewBag.List = null;
                    ViewBag.SList = null;
                    ViewBag.TList = null;
                }
            }
            return View();
        }

        public JsonResult GetDistributionData()
        {
            return Json(DistributionManage.GetList());
        }

        //public JsonResult GetMyTeamData()
        //{
        //    if (GetCurrentMember() != null)
        //    {
        //        ViewBag.MemberGuid = RFrameGenerate.Common.CurrentUser.GetCurrUserGuid();
        //    }
        //    return Json(DistributionManage.GetListByDistributionGuid());
        //}

        public JsonResult GetOrderDetailByOrderGuid(Guid orderGuid)
        {
            List<T_BAS_OrderDetails> list = new List<T_BAS_OrderDetails>();
            var result = OrderDetailsManage.GetListByOrder(orderGuid, ref list);
            if (result.State)
                return Json(new { Result = "OK", List = list });
            else
                return Json(new { Result = "No" });
        }
        /// <summary>
        /// 佣金提现
        /// </summary>
        /// <param name="applyAmount"></param>
        /// <returns></returns>
        public JsonResult CheckAllowed(decimal applyAmount)
        {
            if (CurrentUser.GetCurrUserGuid() != null)
            {
                var did = Guid.Parse(CookieManage.GetCookie(SessionKeys.ShareDistribution));
                var DistributionStoreInfo = ParameterManage.GetParam(ParameterName.DistributionMemeber.AuditApproachNew);
                if (DistributionStoreInfo != null && DistributionStoreInfo.ParameterValue.ToLower() == DictionaryConst.ApproachNew.Withoutm.ToString().ToLower())
                {
                    var dist = DistributionManage.GetDistributeionProp(did);
                    if(string.IsNullOrEmpty(dist.DistributionTelphone)==true)
                        return Json(new { Result = "Redirect" });
                }

                var result = WithdrawsComManage.CheckAllowed(did, applyAmount);
                if (result.State)
                    return Json(new { Result = "OK", Msg = result.Msg });
                return Json(new { Result = "No", Msg = result.Msg });
            }
            return null;
        }
        #endregion


        public JsonResult ShowQrCodeImg(Guid guid)
        {
            return Json(DistributionManage.ShowQRCode(OpenID));
        }

    }
}
