using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using LitJson;
using Library;
using System.Linq;
using System;
using MySystem.MainModels;
using System.IO;
using System.Text;
using Aliyun.OSS;
using System.Security.Cryptography;

namespace MySystem.Areas.Api.Controllers.v1
{
    public class OutApiController : BaseController
    {
        public OutApiController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }

        #region 设置服务费
        [Route("/api/v1/deposit/set")]
        public JsonResult SetDeposit()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            JsonData data = JsonMapper.ToObject(requestMes);
            Dictionary<string, object> req = new Dictionary<string, object>();
            string PosSn = data["posSn"].ToString();
            req.Add("PosSn", PosSn);
            req.Add("BrandId", data["brandId"].ToString());
            req.Add("Deposit", data["deposit"].ToString());
            string UserId = "0";
            if(requestMes.Contains("\"userId\""))
            {
                UserId = data["userId"].ToString();
            }
            req.Add("UserId", UserId);
            string CallBackUrl = "";
            if(requestMes.Contains("\"callBackUrl\""))
            {
                CallBackUrl = data["callBackUrl"].ToString();
            }
            req.Add("CallBackUrl", CallBackUrl);
            RedisDbconn.Instance.AddList("ChangePosFeeQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
            return Json(new AppResultJson() { Status = "1", Info = "" });
        }
        #endregion

        #region 设置费率
        [Route("/api/v1/fee/set")]
        public JsonResult SetFee()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            JsonData data = JsonMapper.ToObject(requestMes);
            string PosSn = data["posSn"].ToString();
            string MerNo = data["mchNo"].ToString();
            int BrandId = int.Parse(data["brandId"].ToString());
            decimal FeeRate = decimal.Parse(data["feeRate"].ToString());
            int FeeExtra = int.Parse(data["feeExtra"].ToString());
            string CallBackUrl = "";
            if(requestMes.Contains("\"callBackUrl\""))
            {
                CallBackUrl = data["callBackUrl"].ToString();
            }
            int ChangeKind = 0;
            if(FeeRate == 0.63M && FeeExtra == 3)
            {
                ChangeKind = 1;
            }
            else if(FeeRate == 0.63M && FeeExtra == 0)
            {
                ChangeKind = 2;
            }
            else if(FeeRate == 0.6M && FeeExtra == 0)
            {
                ChangeKind = 3;
            }
            // PosId:机具Id
            // Kind:1或2，1为费率0.63+3，2为费率0.63，3为费率0.6
            // OpMan:操作人，app传创客编号，后台传SysUserName
            string info = "{\"RecordId\":\"0\",\"PosSn\":\"" + PosSn + "\",\"MerNo\":\"" + MerNo + "\",\"BrandId\":\"" + BrandId + "\",\"Fee\": \"" + FeeRate.ToString().TrimEnd('0') + "\",\"Kind\": \"" + ChangeKind + "\",\"OpMan\": \"接口\",\"CallBackUrl\":\"" + CallBackUrl + "\"}";
            RedisDbconn.Instance.AddList("SetDepositPostQueue", info);
            return Json(new AppResultJson() { Status = "1", Info = "" });
        }
        #endregion

        #region WIFI解绑
        [HttpPost]
        [Route("/kxs/unbind/wifi")]
        public Dictionary<string, object> UnBindWifi()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            if (string.IsNullOrEmpty(requestMes))
            {
                return new Dictionary<string, object>();
            }
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(Request.Headers) + "#cut#" + requestMes;
            Utils.WriteLog(content, "WIFI解绑推送消息");
            string fileName = function.MD5_16(Guid.NewGuid().ToString());
            RedisDbconn.Instance.AddList("kxs_unbindwifi_list", content + "#cut#" + fileName);
            Dictionary<string, object> obj = new Dictionary<string, object>();
            obj.Add("resCode", 200);
            obj.Add("resMsg", "success");
            return obj;
        }
        #endregion

        #region WIFI换绑
        [HttpPost]
        [Route("/kxs/changebind/wifi")]
        public Dictionary<string, object> ChangeBindWifi()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            if (string.IsNullOrEmpty(requestMes))
            {
                return new Dictionary<string, object>();
            }
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(Request.Headers) + "#cut#" + requestMes;
            Utils.WriteLog(content, "WIFI换绑推送消息");
            string fileName = function.MD5_16(Guid.NewGuid().ToString());
            RedisDbconn.Instance.AddList("kxs_changebindwifi_list", content + "#cut#" + fileName);
            Dictionary<string, object> obj = new Dictionary<string, object>();
            obj.Add("resCode", 200);
            obj.Add("resMsg", "success");
            return obj;
        }
        #endregion

        #region 同行奖同步
        [Route("/leader/prize/do/{month:minlength(6)}")]
        public string LeaderPrize(string month)
        {
            if(RedisDbconn.Instance.Get<string>("LeaderTxjPrizeFlag" + month) == "1")
            {
                return "请勿频繁操作";
            }
            RedisDbconn.Instance.Set("LeaderTxjPrizeFlag" + month, "1");
            RedisDbconn.Instance.SetExpire("LeaderTxjPrizeFlag" + month, 60);
            RedisDbconn.Instance.AddList("TxjQueue", month);
            return "ok";
        }
        #endregion

        #region 获取更新过期身份证链接
        [Route("/api/v1/ls/idcardurl")]
        public JsonResult LsIdCardUrl()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            requestMes = requestMes.Replace("\"", "");
            Utils.WriteLog(requestMes, "获取更新过期身份证链接");
            requestMes = PublicImportDataService.Instance.AesDecryptForIv(requestMes);
            Utils.WriteLog(requestMes + "\n\n", "获取更新过期身份证链接");
            JsonData data = JsonMapper.ToObject(requestMes);
            string merNo = data["merNo"].ToString();
            string content = PublicImportDataService.Instance.LePassGetExpiredIdCardUrl(merNo);
            JsonData jsonObj = JsonMapper.ToObject(content);
            if(jsonObj["error_code"].ToString() == "0")
            {
                return Json(new AppResultJson() { Status = "1", Info = jsonObj["error_msg"].ToString(), Data = jsonObj["data"].ToString() });
            }
            return Json(new AppResultJson() { Status = "-1", Info = jsonObj["error_msg"].ToString() });
        }
        #endregion

        #region 更新小程序版本
        [Route("/api/v1/mini/addver")]
        public string MiniAddVesion(string id)
        {
            RedisDbconn.Instance.AddList("MiniSetVersionQueue", id);
            return "ok";
        }
        #endregion






        #region 前端上传oss返回参数
        [Route("/api/oss/uploadinfo")]
        public JsonResult OssInfo(string value)
        {
            value = AesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string dir = data["dir"].ToString(); //文件上传路径        
            if (string.IsNullOrEmpty(data["dir"].ToString()))
            {
                return Json(new AppResultJson() { Status = "1", Info = "文件上传路径不能为空" });
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var OssUrl = "https://laikeba.oss-cn-chengdu.aliyuncs.com";
            var AccessKeyId = "LTAI5tJsPaNzqCSMCPwb8zfz";
            var AccessKeySecret = "efM31Up75fQcgZ32U6xvAciagceQae";
            var endpoint = "https://oss-cn-chengdu.aliyuncs.com";
            // "OSSKey": "LTAI5tJsPaNzqCSMCPwb8zfz",
            // "OSSSecret": "efM31Up75fQcgZ32U6xvAciagceQae",
            // "OSSEndpoint": "oss-cn-chengdu.aliyuncs.com",
            // "OSSBucketName": "laikeba",

            // 构造OssClient实例。 endpoint 格式:https://oss-cn-beijing.aliyuncs.com
            var ossClient = new OssClient(endpoint, AccessKeyId, AccessKeySecret);
            var config = new PolicyConditions();
            config.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 1024L * 1024 * 1024 * 5);// 文件大小范围：单位byte
            config.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
            var expire = DateTimeOffset.Now.AddMinutes(30);// 过期时间

            // 生成 Policy，并进行 Base64 编码
            var policy = ossClient.GeneratePostPolicy(expire.LocalDateTime, config);
            var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));

            // 计算签名
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(AccessKeySecret));
            var bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(policyBase64));
            var Signature = Convert.ToBase64String(bytes);

            Obj.Add("OssUrl", OssUrl);
            Obj.Add("AccessKeyId", AccessKeyId);
            // Obj.Add("AccessKeySecret", AccessKeySecret);
            Obj.Add("Policy", policyBase64);
            Obj.Add("Expiration", expire);
            Obj.Add("Signature", Signature);
            Obj.Add("dir", dir);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion

        // [Route("/api/v1/{c1}/{c2}")]
        // public JsonResult ToApServer(string c1, string c2, string value)
        // {
        //     string apis = function.CheckNull(RedisDbconn.Instance.Get<string>("ToApServer"));
        //     Utils.WriteLog(DateTime.Now.ToString() + "\n" + value, "接口转发日志");
        //     string hasDo = "";
        //     if (apis.Contains(c1 + "/" + c2))
        //     {
        //         value = dbconn.DesEncrypt(value, "*ga34|^7");
        //     }
        //     else
        //     {
        //         hasDo = "do";
        //     }
        //     Utils.WriteLog(value, "接口转发日志");
        //     string url = AppConfig.Base.ApHost + "api/v1/" + c1 + "/" + c2 + hasDo;
        //     Utils.WriteLog(url, "接口转发日志");
        //     string result = function.PostWebRequest(url, "value=" + value);
        //     Utils.WriteLog(str: result, "接口转发日志");
        //     JsonData data = JsonMapper.ToObject(result);
        //     if(result.Contains("\"status\""))
        //     {
        //         return Json(new AppResultJson() { Status = data["status"].ToString(), Data = data["data"].ToJson(), Info = data["info"].ToString(), Other = data["other"] == null ? "" : data["other"].ToJson(), Timestamp = int.Parse(function.CheckInt(data["timestamp"].ToString())) });
        //     }
        //     return Json(new AppResultJson() { Status = "1", Data = result, Info = "" });
        // }
    }
}
