using LitJson;
using RFrameGenerate.BLL;
using RFrameGenerate.BLL.Category;
using RFrameGenerate.BLL.Products;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace jiouosdp.Areas.Products.Controllers
{
    public class MainController : Controller
    {
        //
        // GET: /Products/Main/
        static string urlPath = string.Empty;
        public MainController()
        {
            var applicationPath = VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~");
            urlPath = applicationPath + DictionaryConst.UpLoadPath.ProductsImagePath;
        }
        #region 商品管理
        [PF(PCode.ProductManage.ProductIndex)]
        public ActionResult Index()
        {
            if (MerchantManage.IsTopTe())
            {
                return View();
            }
            else
            {
                return View("IndexSub");
            }


        }
        /// <summary>
        /// 获取商品列表（分页）
        /// </summary>
        /// <param name="gridModel"></param>
        /// <returns></returns>
        public JsonResult GetPageList(GridModel gridModel, string name, Guid? ptid)
        {
            //var list = ProductsManage.GetPageList(gridModel,name,ptid);

            var list = ProductsManage.GetProductPageList(gridModel, name, ptid, m => new
            {
                m.ProductGuid,
                m.ProductName,
                m.ProductUrl,
                m.QRCodeUrl,
                m.ProductCode,
                m.Price,
                m.AgentPrice,
                m.Inventory,
                m.SalesVolume,
                m.BaseSalesVolume,
                m.IsPutaway,
                m.Sort
            });

            gridModel.recordCount = list.RecordCount;
            gridModel.datarows = (from s in list.Data
                                  select new
                                  {
                                      id = s.ProductGuid,
                                      cell = new object[]
                                            {                                    
                                                s.ProductName,
                                                s.ProductUrl,
                                                s.QRCodeUrl,
                                                s.ProductCode,                                                
                                                s.Price,
                                                s.AgentPrice,
                                                s.Inventory,                                                
                                                s.SalesVolume,
                                                s.BaseSalesVolume,
                                                s.IsPutaway,
                                                s.Sort,                                               
                                            }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        /// <summary>
        /// 保存商品
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonResult Save_Product(T_BAS_Products entity, string data)
        {
            var list = GetListByData(entity.ProductGuid, data);
            try
            {
                RFrameGenerate.Common.GraphicHelper.CutImage(Server.MapPath("~" + entity.ProductImage), Server.MapPath("~" + DictionaryConst.UpLoadPath.ProductsImagePath));
            }
            catch
            {

            }
            var result = ProductsManage.SaveChangeEntity(entity, list);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        /// <summary>
        /// 保存下级商品
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonResult Save_ProductSub(T_BAS_Products entity, string data)
        {
            try
            {
                RFrameGenerate.Common.GraphicHelper.CutImage(Server.MapPath("~" + entity.ProductImage), Server.MapPath("~" + DictionaryConst.UpLoadPath.ProductsImagePath));
            }
            catch
            {

            }
            var result = ProductsManage.SaveChangeEntitySub(entity, data);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });

        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <returns></returns>
        public JsonResult GetParameter()
        {
            string first = ParameterManage.GetParameterByName(ParameterName.CommissionMember.FirstCommission);
            string second = ParameterManage.GetParameterByName(ParameterName.CommissionMember.SecondCommission);
            string third = ParameterManage.GetParameterByName(ParameterName.CommissionMember.ThirdCommission);
            return Json(new { Result = "OK", FirstCommission = first, SecondCommission = second, ThirdCommission = third });
        }
        /// <summary>
        /// 获取所有商品分类
        /// </summary>
        /// <returns></returns>
        public JsonResult Getlist_ProductCategory()
        {
            var list = ProductCategorysManage.GetList();
            var relList = new List<T_BAS_ProductCategorys>();

            foreach (var item in list)
            {
                if (relList.Exists(m => m.ProductCategoryGuid == item.ProductCategoryGuid)) continue;

                relList.Add(item);

                GetSubList(item, ref list, ref relList);
            }
            return Json(new { Result = "OK", List = relList });
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Del_Product(Guid? entityGuid)
        {
            List<T_BAS_Products> relList = new List<T_BAS_Products>();
            var result = ProductsManage.DeleteEntity(entityGuid.Value, ref relList);

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

        }

        //下架
        public JsonResult Pull_Product(Guid? entityGuid)
        {
            bool shelves = false;
            var result = ProductsManage.GetEntity(entityGuid.Value, shelves);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        //上架
        public JsonResult Put_Product(Guid? entityGuid)
        {
            bool shelves = true;
            var result = ProductsManage.GetEntity(entityGuid.Value, shelves);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        //获取微信二维码
        public JsonResult GetQRCode(Guid? entityGuid)
        {
            string srcQRCode = "";
            var result = ProductsManage.GetQRCode(entityGuid.Value, ref srcQRCode);
            if (result.State)
                return Json(new { Result = "OK", Url = srcQRCode });
            else
                return Json(new { Result = "OK", Msg = result.Msg });
        }

        //下载二维码
        public FileResult Download(string url)
        {
            string fileName = Server.MapPath(url);

            return File(fileName, "application/png", url.Substring(url.LastIndexOf("/") + 1));
        }

        public JsonResult LoadOriginalProduct(Guid OriginalProductGuid)
        {
            var product = ProductsManage.GetProductByOriginalProductGuid(OriginalProductGuid);

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

            if (!string.IsNullOrEmpty(product.Description))
            {
                product.Description = HttpUtility.HtmlEncode(product.Description);
            }

            if (!string.IsNullOrEmpty(product.CategoryCode))
            {
                var trees = CategoryManage.CategoryTrees(product.CategoryCode);
                if (trees != null) trees.Reverse();

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

        private List<T_BAS_ProductSKU> GetListByData(Guid productGuid, string data)
        {
            if (string.IsNullOrEmpty(data)) return null;
            List<T_BAS_ProductSKU> list = new List<T_BAS_ProductSKU>();
            int sort = 0;
            foreach (Match match in Regex.Matches(data, @"(?<=\[)[^\[]*?(?=\])", RegexOptions.IgnoreCase | RegexOptions.Singleline))
            {
                var array = match.Value.Replace("\"", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var groupGuid = Guid.NewGuid();

                if (!MerchantManage.IsMar())
                {
                    if (array.Length < 5) continue;
                    var newArray = array.Take(array.Length - 5);
                    if (newArray.Count() % 2 != 0) continue;

                    for (int i = 0; i < newArray.Count(); i += 2)
                    {
                        T_BAS_ProductSKU sku = new T_BAS_ProductSKU();

                        sku.ProductSKUGuid = Guid.NewGuid();
                        sku.ProductGuid = productGuid;
                        sku.Price = string.IsNullOrEmpty(array[array.Length - 5]) ? 0m : decimal.Parse(array[array.Length - 5]);
                        sku.Invenotory = string.IsNullOrEmpty(array[array.Length - 4]) ? 0m : decimal.Parse(array[array.Length - 4]);
                        sku.Code = array[array.Length - 3];
                        sku.Weight = string.IsNullOrEmpty(array[array.Length - 2]) ? 0m : decimal.Parse(array[array.Length - 2]);
                        sku.AgentPrice = string.IsNullOrEmpty(array[array.Length - 1]) ? 0m : decimal.Parse(array[array.Length - 1]);

                        sku.ProductSKUNameGuid = Guid.Parse(newArray.ElementAt(i));
                        sku.ProductSKUValueGuid = Guid.Parse(newArray.ElementAt(i + 1)); ;
                        sku.ProductSKUGroupGuid = groupGuid;
                        sku.Sort = sort;
                        sku.MerchantGuid = CurrentManage.MerchantGuid;
                        sku.EntityState = EntityStates.ToBeAdd;
                        list.Add(sku);
                    }
                    sort++;
                }
                else
                {
                    if (array.Length < 4) continue;
                    var newArray = array.Take(array.Length - 4);
                    if (newArray.Count() % 2 != 0) continue;

                    for (int i = 0; i < newArray.Count(); i += 2)
                    {
                        T_BAS_ProductSKU sku = new T_BAS_ProductSKU();

                        sku.ProductSKUGuid = Guid.NewGuid();
                        sku.ProductGuid = productGuid;
                        sku.Price = string.IsNullOrEmpty(array[array.Length - 4]) ? 0m : decimal.Parse(array[array.Length - 4]);
                        sku.Invenotory = string.IsNullOrEmpty(array[array.Length - 3]) ? 0m : decimal.Parse(array[array.Length - 3]);
                        sku.Code = array[array.Length - 2];
                        sku.Weight = string.IsNullOrEmpty(array[array.Length - 1]) ? 0m : decimal.Parse(array[array.Length - 1]);
                        //sku.AgentPrice = string.IsNullOrEmpty(array[array.Length - 1]) ? 0m : decimal.Parse(array[array.Length - 1]);

                        sku.ProductSKUNameGuid = Guid.Parse(newArray.ElementAt(i));
                        sku.ProductSKUValueGuid = Guid.Parse(newArray.ElementAt(i + 1)); ;
                        sku.ProductSKUGroupGuid = groupGuid;
                        sku.Sort = sort;
                        sku.MerchantGuid = CurrentManage.MerchantGuid;
                        sku.EntityState = EntityStates.ToBeAdd;
                        list.Add(sku);
                    }
                    sort++;
                }
            }
            return list;
        }
        //上传文件
        [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")
                    {
                        throw new Exception("不合适的文件,只能支持jpg|gif|png的文件");
                    }

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

                    var dateTimeNow = DateTime.Now;
                    var basePath = DictionaryConst.UpLoadPath.ProductsImagePath;


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


                    //returnstr = ;

                    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)
            {
                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();
            }

        }

        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;

            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, DictionaryConst.UpLoadPath.ProductsImagePath);
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }

            string ext = Path.GetExtension(file.FileName).ToLower();
            if (ext.ToLower() != ".jpg" && ext.ToLower() != ".gif" && ext.ToLower() != ".png" && ext.ToLower() != ".jpeg" && ext.ToLower() != ".bmp")
            {
                throw new Exception("不合适的文件,只能支持jpg|gif|png|jpeg|bmp的文件");
            }
            filePathName = DateTime.Now.ToString("yyyyMMddHHmmss")
                        + RFrameGenerate.Common.RadomCode.DigitalCode(3) + ext;
            if (!System.IO.Directory.Exists(localPath))
            {
                System.IO.Directory.CreateDirectory(localPath);
            }
            var basePath = DictionaryConst.UpLoadPath.ProductsImagePath;
            string DirUrl = Server.MapPath("~" + basePath);
            var relativePath = basePath + "/" + filePathName;
            UpLoadFileHelp.SaveInFileSystem(file, DirUrl, filePathName);
            return Json(new
            {
                jsonrpc = "2.0",
                id = id,
                filePath = relativePath
            });

        }

        #endregion

        #region 商品分类
        [PF(PCode.ProductManage.ProductCategorys)]
        public ActionResult ProductCategorys()
        {
            return View();
        }

        /// <summary>
        /// 加载商品分类
        /// </summary>
        /// <param name="gridModel"></param>
        /// <returns></returns>
        public ActionResult LoadData(GridModel gridModel)
        {


            var list = ProductCategorysManage.LoadData(gridModel);
            var relList = new List<T_BAS_ProductCategorys>();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    if (relList.Exists(m => m.ProductCategoryGuid == item.ProductCategoryGuid)) continue;

                    relList.Add(item);

                    GetSubList(item, ref list, ref relList);
                }
            }
            gridModel.datarows = (from s in relList
                                  select new
                                  {
                                      id = s.ProductCategoryGuid,
                                      cell = new object[]
                                            {
                                                s.ProductCategoryGuid,
                                                s.MerchantGuid,
                                                s.CategoryName,
                                                s.CategoryCode,
                                                //s.Url,
                                                s.Levels,
                                                s.ParentGuid,
                                                s.Sort
                                            }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        public static void GetSubList(T_BAS_ProductCategorys entity, ref List<T_BAS_ProductCategorys> list, ref List<T_BAS_ProductCategorys> relList)
        {
            if (entity == null) return;

            foreach (var item in list.Where(m => m.ParentGuid == entity.ProductCategoryGuid).OrderBy(a => a.Sort))
            {
                if (relList.Exists(m => m.ProductCategoryGuid == item.ProductCategoryGuid)) continue;

                relList.Add(item);

                if (list.Exists(m => m.ParentGuid == item.ProductCategoryGuid))
                    GetSubList(item, ref list, ref relList);
            }
        }
        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Del_ProductCategorys(Guid? entityGuid)
        {

            List<T_BAS_ProductCategorys> relList = new List<T_BAS_ProductCategorys>();
            var result = ProductCategorysManage.DeleteEntity(entityGuid.Value, ref relList);

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

        }
        /// <summary>
        /// 保存商品分类
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Save_ProductCategorys(T_BAS_ProductCategorys entity)
        {
            var result = ProductCategorysManage.SaveChangeEntity(entity);

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

        #endregion
        
        #region 类目管理

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

        public JsonResult GetCategories(string code)
        {
            if (code.Contains(","))
            {
                var list = CategoryManage.GetCategories(code.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), m => new { m.CategoryCode, m.Leaf, m.CategoryName, m.Level, m.IsVirtual });
                return Json(list);
            }
            else
            {
                var list = CategoryManage.GetCategories(code, m => new { m.CategoryCode, m.Leaf, m.CategoryName, m.Level, m.IsVirtual });
                return Json(list);
            }
        }

        #endregion
    }
}
