using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFrameGenerate.BLL.WX_BaseCommon;
using LitJson;

namespace jiouosdp.Areas.WeiXinBase.Controllers
{
    public class MaterialController : Controller
    {
        //
        // GET: /BaseCommon/Material/



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

        public ActionResult Edit(string guid)
        {
            try
            {
                var model = new T_WX_Material();
                if (!string.IsNullOrEmpty(guid))
                {
                    //update
                    ViewBag.TabTitle = "编辑素材";
                    model = BaseCommonBLL.GetMaterialByGuid(new Guid(guid));
                }
                else
                {
                    //add
                    ViewBag.TabTitle = "新增素材";
                    model.Createdate = DateTime.Now;
                    
                }
                if (string.IsNullOrEmpty(model.MaterialCoverFace))
                {
                    model.MaterialCoverFace = "/images/manage/imgBlank.jpg"; 
                }
                return View(model);
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
                return View();
            }
        }


        public JsonResult Delete(string guid)
        {
            try
            {
                BaseCommonBLL.DeleteMaterial(new Guid(guid));
                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "OK", Data = e.Message });
            }
        }


        public JsonResult EditSubmit(T_WX_Material model)
        {
            try
            {
                BaseCommonBLL.MaterialSubmit(model);
                return Json(new { Result = "OK", Data = model.MaterialGuid });
            }
            catch (Exception e)
            {
                return Json(new { Result = "Error", Data = e.Message });
            }
        }

        public JsonResult LoadData(GridModel gridModel, string title) 
        {
            //'会员昵称', '手机号码', '地址', '状态', '关注时间', '操作'
            gridModel.datarows = (from s in BaseCommonBLL.GetMaterialPageList(gridModel, title )
                                  select new
                                  {
                                      id = s.MaterialGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.MaterialCode,
                                                         s.MaterialTitle,
                                                         s.MaterialCoverFace,
                                                         s.Createdate.ToDateString()
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }


        [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.MaterialImagePath;


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

        }


    }
}
