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;

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("f0").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;
            function.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;
            function.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


        // [Route("/api/v1/{c1}/{c2}")]
        // public JsonResult ToApServer(string c1, string c2, string value)
        // {
        //     string apis = function.CheckNull(RedisDbconn.Instance.Get<string>("ToApServer"));
        //     function.WriteLog(DateTime.Now.ToString() + "\n" + value, "接口转发日志");
        //     string hasDo = "";
        //     if (apis.Contains(c1 + "/" + c2))
        //     {
        //         value = dbconn.DesEncrypt(value, "*ga34|^7");
        //     }
        //     else
        //     {
        //         hasDo = "do";
        //     }
        //     function.WriteLog(value, "接口转发日志");
        //     string url = AppConfig.Base.ApHost + "api/v1/" + c1 + "/" + c2 + hasDo;
        //     function.WriteLog(url, "接口转发日志");
        //     string result = function.PostWebRequest(url, "value=" + value);
        //     function.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 = "" });
        // }
    }
}
