using CallCenter.Utility;
using CallCenterApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.App_Start
{
    public class OutActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var sign = filterContext.HttpContext.Request["signcode"];
            var model = GetCityInfo();
            bool bl = true;
            if (sign != null && model!=null)
            {
                string insigncode = sign.ToString();
                string outsigncode = model["F_Sign"].ToString();
                string controllercode = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
                string actioncode = filterContext.ActionDescriptor.ActionName.ToLower();
                string signcode = EncryptHelper.MD5Encrypt(controllercode + "/" + actioncode + "+" + EncryptHelper.SHA1Encrypt(outsigncode + "+" + DateTime.Now.ToString("yyyyMMdd")));
                if (insigncode == signcode)
                {
                    bl = false;
                }
            }
            if (bl)
            {
                filterContext.Result = new ContentResult() { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = "签名错误" }.ToJson() };
                return;
            }

            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 获取当前网点信息
        /// </summary>
        /// <returns></returns>
        public Newtonsoft.Json.Linq.JObject GetCityInfo()
        {
            string code = Configs.GetValue("CityCode");
            string signcode = Configs.GetValue("CityOutSignCode");
            string url = Configs.GetValue("CityOutUrl");
            string outsigncode = CommonHelper.getsigncode("CountyBranch", "GetCityDetail", signcode);
            string strparams = "?code=" + code + "&signcode=" + outsigncode;
            var result = HttpMethods.HttpGet(url + "/CountyBranch/GetCityDetail" + strparams).ToJObject();
            if (result["state"].ToString() == "success")
            {
                return result["data"].ToString().ToJObject();
            }
            else
            {
                return null;
            }
        }
    }
}