using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.CacheManager.User;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web;

namespace Mall.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiFilter]
    [EnableCors("AllowCors")]
    public class BaseController : ControllerBase
    {

        /// <summary>
        /// 整理前端传递的post参数
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        public RequestParm RequestParm
        {
            get
            {
                #region 读取post参数
                var requestMsg = Request.HttpContext.Items[GlobalKey.UserPostInfo];

                var requestParm = new RequestParm();
                if (requestMsg != null)
                {
                    requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
                }
                if (Request.HttpContext.Items[GlobalKey.TokenUserInfo] != null)
                {
                    JObject parms = JObject.Parse(Request.HttpContext.Items[GlobalKey.TokenUserInfo].ToString());
                    requestParm.uid = parms.GetStringValue("uid");
                    if (requestParm.uid != null && !string.IsNullOrWhiteSpace(requestParm.uid))
                    {
                        requestParm.TenantId = Convert.ToInt32(requestParm.uid);
                    }
                }
                #endregion
                //根据token 获取uid
                return requestParm;
            }
        }

        /// <summary>
        /// 商户缓存信息
        /// </summary>
        public UserInfo UserInfo
        {
            get
            {
                var parm = this.RequestParm;
                UserInfo userInfo = UserReidsCache.GetUserLoginInfo(parm.uid);
                return userInfo;
            }
        }

        /// <summary>
        /// 小程序用户缓存
        /// </summary>
        public AppletUserInfo AppletUserInfo 
        {
            get {
                var parm = this.RequestParm;
                AppletUserInfo userInfo = UserReidsCache.GetAppletUserLoginInfo(parm.uid);
                return userInfo;
            }
        }
    }
}