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 LitJson;

namespace jiouosdp.Areas.Systems.Controllers
{
    public class SettingController : Controller
    {
        //
        // GET: /System/Setting/

        [PF(PCode.SystemStoreManage.StoreSetting)]
        public ActionResult Index()
        {
            return View();
        }

        #region JsonResult UpdateSystemSetting

        /// <summary>
        /// updata (or add)system parameter setting
        /// </summary>
        /// <param name="storeState"></param>
        /// <param name="closeReason"></param>
        /// <returns></returns>
        public JsonResult UpdateSystemSetting(bool storeState, string closeReason)
        {
            var result = MerchantManage.UpdateSystemSetting(storeState, closeReason);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        #endregion

        #region JsonResult GetSystemSettingParameter
        /// <summary>
        /// get system setting parameter
        /// </summary>
        /// <returns></returns>
        public JsonResult GetSystemSettingParameter()
        {
            var allParList = ParameterManage.GetSettingParameters(ParameterName.SystemSet.ShowState);

            var parameterList = from c in allParList
                                where c.MerchantGuid == CurrentManage.MerchantGuid
                                select new
                                {
                                    ParameterName = c.ParameterName,
                                    ParameterValue = c.ParameterValue,
                                    ParameterGuid = c.ParameterGuid
                                };
            return Json(new { Result = "OK", Data = parameterList.ToArray() });

        }// this is old function by getdata for parameter
        #endregion

        #region JsonResult GetAreaData

        /// <summary>
        /// get area data
        /// </summary>
        /// <returns></returns>
        public JsonResult GetAreaData()
        {
            return Json(AreasManage.GetAreaData());
        }

        #endregion

        #region void Upload
        /// <summary>
        /// upload photo
        /// </summary>
        [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 == null) continue;
                    var extension = Path.GetExtension(file.FileName);
                    if (extension == null) continue;
                    var fileNameExt = extension.ToLower();

                    if (fileNameExt != ".jpg" && fileNameExt != ".gif" && fileNameExt != ".png")
                    {
                        throw new Exception("不合适的文件,只能支持jpg|gif|png的文件");
                    }
                    //System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);
                    //if (upload == "shopLOGO")
                    //{
                    //    if (image.Width != image.Height)
                    //    {
                    //        throw new Exception("请上传比例为100x100作为店铺LOGO");
                    //    }
                    //}
                    //else
                    //{
                    //    if (!(image.Width%8==0 && image.Height %3==0))
                    //    {
                    //        throw new Exception("请上传比例为8:3的背景图片");
                    //    }
                    //}

                    if (!file.HasFile()) continue;

                    var dateTimeNow = DateTime.Now;
                    if (Request.UrlReferrer == null) continue;
                    var basePath = AppDomain.CurrentDomain.BaseDirectory + "upload/storeimg";
                    Guid parGuid = Guid.NewGuid();
                    var fileName = parGuid + fileNameExt;
                    relativePath = basePath + "/" + fileName;
                    file.SaveInFileSystem(basePath, 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();
            }

        }


        #endregion

        #region JsonResult UpdateStorePar
        /// <summary>
        /// update store parameter
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonResult UpdateStorePar(T_BAS_Merchants entity, int imgtype)
        {
            ParameterMagage.SetImageType(imgtype);
            var result = MerchantManage.UpdateStorePar(entity);
            if (result.State)
            {
                return Json(new { Result = "OK", Data = entity });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        #endregion

        #region JsonResult GetSystemInfo
        /// <summary>
        /// get system info
        /// </summary>
        /// <returns></returns>
        public JsonResult GetSystemInfo()
        {
            return Json(MerchantManage.GetList());
        }
        #endregion

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

        public JsonResult Changepwd(string password)
        {
            if (string.IsNullOrEmpty(password))
                return Json(new { Result = "OK" });

            var result = MerchantManage.ChangePassword(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid(), password);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        [PF(PCode.SystemStoreManage.ParameterSetting)]
        public ActionResult AutoReply()
        {
            //var a = AutoReplyRule.RuleParse("欢迎大家关注我的公众号F[Join],S[DT],C[Txt1],C[Txt2],C[Txt3],C[Txt4]", CurrentManage.MerchantGuid);

            return View();
        }
        public JsonResult SaveParam(string txt1, string txt2, string txt3, string txt4)
        {
            ParameterMagage.SetTxt1(txt1);
            ParameterMagage.SetTxt2(txt2);
            ParameterMagage.SetTxt3(txt3);
            ParameterMagage.SetTxt4(txt4);
            return Json(new { Result = "OK" });
        }

        [MerchantFilter()]
        [PF(PCode.MarketingManage.MarketingSet)]
        public ActionResult MarketingSet()
        {
            return View();
        }

        public JsonResult UpdateParameterSettingAndMore(string parameterName, string parameterValue, T_INT_IntegralRules entity)
        {
            Result result = new Result(false);
            var names = parameterName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var values = parameterValue.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();

                    // 2015-12-17 Bing 原有基础上 新增 当前商家自定义积分规则
                    if (entity != null && entity.IntegralEnable == true)
                    {//新增(覆盖)
                        IntegralRulesManage.AddorUpdateIntegralRulesTemp(entity, tran);
                    }
                    if (entity != null && entity.IntegralEnable == false)
                    {//删除
                        IntegralRulesManage.DeleteIntegralRulesTemp(entity.MerchantGuid.Value, tran);
                    }

                    for (var i = 0; i < names.Length; i++)
                    {
                        string name = names[i];
                        string value = values[i];
                        result = ParameterManage.UpdateParam(name, value);
                        if (result.State != true)
                        {
                            break;
                        }
                    }
                    tran.Commit(); 
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result.State = false;
                    result.Msg = ex.Message;
                }
            }
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "OK", Msg = result.Msg });

        }

        #region 公告
        [PF(PCode.SystemStoreManage.Notice)]
        public ActionResult Notice()
        {
            return View();
        }
        public JsonResult GetNoticeData(GridModel gridModel)
        {
            var slist = NoticeManage.GetPageList(gridModel);
            gridModel.datarows = (slist.Select(c => new
            {
                id = c.NoticeGuid,
                cell = new object[]
                {
                    c.Title,
                    c.Content,
                    c.CreateDate.ToString("yyyy/MM/dd HH:mm:ss"),
                    c.IsEnable
                }
            }).ToArray());
            return Json(gridModel.PackagePageModel());
        }
        public JsonResult SaveNotice(Guid? noticeid, string title, string content, bool isenable)
        {
            var result = NoticeManage.Save(noticeid, title, content, isenable);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }
        public JsonResult DelNotice(Guid noticeid)
        {
            var result = NoticeManage.Del(noticeid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }

        public JsonResult EnableNotice(Guid id, bool isenable)
        {
            var result = NoticeManage.EnableChange(id, isenable);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }



        #endregion
    }
}
