using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;
using System.Security.Cryptography;
using System.Text;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using System.Collections;   
using Aop.Api.Util;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class ConsumersController : BaseController
    {
        public ConsumersController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 消费者-微信小程序通过code获取openid
        [Authorize]
        public JsonResult WeChatMiniOpenId(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = WeChatMiniOpenIdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson WeChatMiniOpenIdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string code = data["code"].ToString(); //微信小程序获取的code
            string nickName = data["nickName"].ToString(); //昵称
            string avatarUrl = data["avatarUrl"].ToString(); //头像地址
            string encryptedData = data["encryptedData"].ToString(); //微信小程序获取手机号的数据包
            string iv = data["iv"].ToString(); //微信小程序获取手机号的IV
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // PublicAccountSet set = RedisDbconn.Instance.Get<PublicAccountSet>("PublicAccountSet") ?? new PublicAccountSet();
            string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + new WeChatFunction().AppId + "&secret=" + new WeChatFunction().AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
            function.WriteLog(url, "微信小程序通过code获取openid");
            string result = function.GetWebRequest(url);
            function.WriteLog(result + "\n", "微信小程序通过code获取openid");
            JsonData jsonObj = JsonMapper.ToObject(result);
            string openid = jsonObj["openid"].ToString();
            string session_key = jsonObj["session_key"].ToString();
            string mobile = getPhoneNumber(encryptedData, iv, session_key)["Mobile"];
            if (mobile == "err")
            { 
                Obj.Add("ConsumerId", "");
                return new AppResultJson() { Status = "-1", Info = "授权失败，请重试", Data = Obj };
            }
            int ConsumerId = 0;
            Consumers check = maindb.Consumers.FirstOrDefault(m => m.WechatOpenId == openid);
            if (check == null)
            {
                check = maindb.Consumers.Add(new Consumers()
                {
                    CreateDate = DateTime.Now,
                    NickName = filterEmoji(nickName),
                    HeadPhoto = avatarUrl,
                    Mobile = mobile,
                    WechatOpenId = openid,
                }).Entity;
                maindb.SaveChanges();
                ConsumerId = check.Id;
                maindb.ConsumerOpenIds.Add(new ConsumerOpenIds()
                {
                    OpenId = openid,
                    ConsumerId = ConsumerId,
                });
                maindb.SaveChanges();
            }
            else
            {
                check.NickName = filterEmoji(nickName);
                check.HeadPhoto = avatarUrl;
                check.Mobile = mobile;
                ConsumerId = check.Id;
                maindb.SaveChanges();
            }
            Obj.Add("ConsumerId", ConsumerId); //消费者Id
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        public Dictionary<string, string> getPhoneNumber(string encryptedData, string iv, string session_key)
        {
            Dictionary<string, string> Obj = new Dictionary<string, string>();
            try
            {
                byte[] encryData = Convert.FromBase64String(encryptedData);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(iv);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);

                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                string phoneNumber = model.phoneNumber;
                //return model.phoneNumber;
                if (string.IsNullOrEmpty(phoneNumber))
                {
                    phoneNumber = "";
                }
                Obj.Add("Mobile", phoneNumber);
            }
            catch(Exception ex)
            {
                Obj.Add("Mobile", "err");
                function.WriteLog(DateTime.Now.ToString(), "微信小程序获取手机号异常");
                function.WriteLog(encryptedData, "微信小程序获取手机号异常");
                function.WriteLog(iv, "微信小程序获取手机号异常");
                function.WriteLog(session_key, "微信小程序获取手机号异常");
                function.WriteLog(ex.ToString(), "微信小程序获取手机号异常");
                function.WriteLog("\r\n\r\n", "微信小程序获取手机号异常");
            }
            return Obj;
        }
        public string filterEmoji(string str)
        {
            string origin = str;
            try
            {
                //关键代码
                foreach (var a in str)
                {
                    byte[] bts = System.Text.Encoding.UTF32.GetBytes(a.ToString());
                    if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
                    {
                        str = str.Replace(a.ToString(), "");
                    }
                }
            }
            catch
            {
                str = origin;
            }
            return str;
        }
        #endregion


        #region 消费者-支付宝通过code获取openid
        [Authorize]
        public JsonResult AlipayMiniOpenId(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(Request.Body);
                value = sr.ReadToEnd();
                value = value.Split('=')[1];
            }
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AlipayMiniOpenIdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson AlipayMiniOpenIdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string code = data["code"].ToString(); //微信小程序获取的code
            // string nickName = data["nickName"].ToString(); //昵称
            // string avatarUrl = data["avatarUrl"].ToString(); //头像地址
            string encryptedData = data["encryptedData"].ToString(); //微信小程序获取手机号的数据包
            // string iv = data["iv"].ToString(); //微信小程序获取手机号的IV
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string openid = new AlipayFunction(_accessor.HttpContext).GetAlipayUserId(code);
            // string AlipayOpenId = UserIdString.Split('|')[0];
            string mobile = new AlipayFunction(_accessor.HttpContext).GetAlipayMobile(encryptedData);
            if (mobile.StartsWith("success|"))
            {
                mobile = mobile.Split('|')[1];
            }
            int ConsumerId = 0;
            Consumers check = maindb.Consumers.FirstOrDefault(m => m.AlipayUserId == openid);
            if (check == null)
            {
                check = maindb.Consumers.Add(new Consumers()
                {
                    CreateDate = DateTime.Now,
                    // NickName = filterEmoji(nickName),
                    // HeadPhoto = avatarUrl,
                    // Mobile = mobile,
                    AlipayUserId = openid,
                }).Entity;
                maindb.SaveChanges();
                ConsumerId = check.Id;
                maindb.ConsumerOpenIds.Add(new ConsumerOpenIds()
                {
                    OpenId = openid,
                    ConsumerId = ConsumerId,
                });
                maindb.SaveChanges();
            }
            else
            {
                // check.NickName = filterEmoji(nickName);
                // check.HeadPhoto = avatarUrl;
                // check.Mobile = mobile;
                ConsumerId = check.Id;
                maindb.SaveChanges();
            }
            Obj.Add("ConsumerId", ConsumerId); //消费者Id
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 消费者-消费者详情
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Consumers query = new Consumers();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = ConsumersDbconn.Instance.Get(Id) ?? new Consumers();
            Obj.Add("NickName", query.NickName); //昵称
            Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
            Obj.Add("Mobile", query.Mobile); //手机号
            string TotalDividend = new ConsumerProfitService().Sum("GetMoney", " and ConsumerId=" + Id)["GetMoney"];
            Obj.Add("TotalDividend", TotalDividend); //累计分红
            Obj.Add("TotalIntegral", query.TotalIntegral); //累计积分
            Obj.Add("CurIntgegral", query.CurIntgegral); //当前积分
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            return Obj;
        }
        #endregion




        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
