using Newtonsoft.Json;
using Sugar.Enties;
using System;
using System.Collections.Generic;
using System.Text;

namespace WxPayAPI
{
    public class JSAPIPay
    {
        /// <summary>
        /// nlog日志
        /// </summary>
        private static NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();


        /// <summary>
        /// 生成JSAPI所需的数据 （先下单，然后获取返回的数据）
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="total_fee">订单金额，单位为分，类型为整数</param>
        /// <param name="out_trade_no">从商户传来的订单号</param>
        /// <returns>模式二URL</returns>
        public WxPayDTO GetJSAPIWxPayData(int total_fee, string openid, string out_trade_no)
        {
            //统一下单： 调用统一下单接口
            Log.Info(this.GetType().ToString() + "JSAPI-GetPayUrl");

            WxPayData data = new WxPayData();
            data.SetValue("body", "缴费"); //商品描述
            //data.SetValue("detail", "缴费"); //商品详情
            data.SetValue("out_trade_no", out_trade_no); //商户订单号
            data.SetValue("total_fee", Convert.ToDouble(total_fee).ToString()); //订单总金额,以分为单位
            data.SetValue("trade_type", "JSAPI");//交易类型
            data.SetValue("openid", openid);
            //string xml = data.ToXml(); //转换成XML
            //var startTime = DateTime.Now; //开始时间

            Log.Info($"【GetJSAPIWxPayData】data组装:{WxPayConfig.NOTIFY_URL}");
            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口


            //获取微信返回数据
            TimeSpan timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));

            string appId = result.GetValue("appid") == null ? "" : result.GetValue("appid").ToString();
            string timeStamp = ((int)timeSpan.TotalSeconds).ToString() + "";
            string nonceStr = result.GetValue("nonce_str") == null ? "" : result.GetValue("nonce_str").ToString();
            string package = result.GetValue("prepay_id") == null ? "prepay_id=" : "prepay_id=" + result.GetValue("prepay_id").ToString();
            string signType = "MD5";
            string prepay_id = result.GetValue("prepay_id") == null ? "" : result.GetValue("prepay_id").ToString();
            string result_code = result.GetValue("result_code") == null ? "" : result.GetValue("result_code").ToString();
            string return_code = result.GetValue("return_code") == null ? "" : result.GetValue("return_code").ToString();
            string err_code = "";
            string err_code_des = "";
            if (return_code == "SUCCESS" || result_code == "FAIL")
            {
                err_code = result.GetValue("err_code") == null ? "" : result.GetValue("err_code").ToString();
                err_code_des = result.GetValue("err_code_des") == null ? "" : result.GetValue("err_code_des").ToString();
            }
            //获取微信签名
            WxPayData wxPaydata = new WxPayData();

            wxPaydata.SetValue("appId", appId); //公众号名称
            wxPaydata.SetValue("timeStamp", timeStamp); //时间戳，自1970年以来的秒数
            wxPaydata.SetValue("nonceStr", nonceStr); //随机串
            wxPaydata.SetValue("package", package); //商品描述
            wxPaydata.SetValue("signType", signType); //微信签名方式
            string sign = wxPaydata.MakeSign();
            //wxPaydata.SetValue("sign", sign);//微信签名


            WxPayDTO wxpaydto = new WxPayDTO();
            wxpaydto.AppId = appId;
            wxpaydto.TimeStamp = timeStamp;
            wxpaydto.NonceStr = nonceStr;
            wxpaydto.Package = package;
            wxpaydto.SignType = signType;
            wxpaydto.PaySign = sign;
            wxpaydto.PrepayId = prepay_id;
            wxpaydto.ReturnCode = return_code;
            wxpaydto.ResultCode = result_code;
            wxpaydto.ErrCode = err_code;
            wxpaydto.ErrCodeDes = err_code_des;
            wxpaydto.OutTradeNo = out_trade_no;




            //string mweb_url = result.GetValue("mweb_url") == null ? "" : result.GetValue("mweb_url").ToString();//mweb_url为拉起微信支付收银台的中间页面，可通过访问该url来拉起微信客户端，完成支付,mweb_url的有效期为5分钟。
            return wxpaydto;
        }
        /// <summary>
        /// 取消支付或其他原因，关闭预支付订单
        /// </summary>
        /// <param name="out_trade_no"></param>
        /// <returns></returns>
        public WxPayDTO CloseOrder(string out_trade_no)
        {
            //统一下单： 调用统一下单接口
            Log.Info(this.GetType().ToString() + "JSAPI-Reverse");

            WxPayData data = new WxPayData();
            data.SetValue("out_trade_no", out_trade_no); //商户订单号

            Log.Info($"【CloseOrder】data组装:{JsonConvert.SerializeObject(data)}");
            WxPayData result = WxPayApi.CloseOrder(data);//调用撤销订单

            WxPayDTO wxpaydto = new WxPayDTO();
            wxpaydto.AppId = result.GetValue("appid") == null ? "" : result.GetValue("appid").ToString();
            wxpaydto.ResultCode = result.GetValue("result_code") == null ? "" : result.GetValue("result_code").ToString();
            wxpaydto.ReturnCode = result.GetValue("return_code") == null ? "" : result.GetValue("return_code").ToString();
            //wxpaydto.TimeStamp = timeStamp;
            //wxpaydto.NonceStr = nonceStr;
            //wxpaydto.Package = package;
            //wxpaydto.SignType = signType;
            //wxpaydto.PaySign = sign;
            //wxpaydto.PrepayId = prepay_id;
            //wxpaydto.ReturnMsg = return_msg;

            return wxpaydto;
        }

    }
}
