
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/
const query=require('querystring')
const crypto=require('crypto')

// 私有支付平台的操作
/*-------------------------------------------------------------------------------------------*/	
class privatePay
{
    static order(obj)
    {
        let oreder=Object.keys(obj)
        //1.获取所有请求参数，不包括字节类型参数，如文件、字节流，剔除sign字段，剔除值为空的参数
        oreder = oreder.filter((k) => obj[k]);
        //2.按照字符的键值ASCII码递增排序
        oreder.sort();
        //3.组合成“参数=参数值”的格式，并且把这些参数用&字符连接起来
        return oreder.map((k) => `${k}=${obj[k]}`).join('&');
    }

    static paysignapi(obj) 
    { 
        obj.appid=obj.appid?obj.appid:$ToolPay.private.appid
        obj.nonce_str=$Sys.uid().toString()

        var string = privatePay.order(obj); 
        string+='&key='+ (obj.key?obj.key:$ToolPay.private.appsecret)
        var sign = crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase(); 
        obj.sign=sign
        return obj; 
    }

    static paysign(obj)
    {
        let string = privatePay.order(obj); 

        string = string + '&key=' + (obj.key?obj.key:$ToolPay.private.appsecret); 
        var sign = crypto.createHash('md5').update(string,'utf8').digest('hex'); 
        return sign.toUpperCase(); 
    }

    // 此处的attach不能为空值 否则微信提示签名错误 
    static async buildParams (opt) 
    {  
        var timeStamp = parseInt(Date.now()/1000).toString(); 

        opt.spbill_create_ip=opt.spbill_create_ip?opt.spbill_create_ip:'127.0.0.1'
        //JSAPI -JSAPI支付
        //NATIVE -Native支付
        //APP -APP支付
        opt.trade_type=opt.trade_type?opt.trade_type:'JSAPI'
        opt=privatePay.paysignapi(opt)

        let data= await $Sys.model
        (
            '/request/fetch','post',
            [
                {
                    host: $ToolPay.private.gateway,
                    path: '/unifiedorder',
                    method: 'POST',
                    data:opt,
                }
            ]
        );
        data=data.data
        
        var prepay_id = data.prepay_id; 
        
        var _opt={appId:opt.appid,nonceStr:opt.nonce_str,package:'prepay_id=' + prepay_id,signType:'MD5',timeStamp:timeStamp}
        _opt.paySign=privatePay.paysign(_opt); 

        return _opt
    }

    static async back(obj)
    {
        let sign=privatePay.paysignapi(obj)
        let data= await $Sys.model
        (
            '/request/fetch','post',
            [
                {
                    host: $ToolPay.private.gateway,
                    path: '/refund',
                    method: 'POST',
                    data:sign,
                }
            ]
        );

        return data.data
    }

    static verifySign(obj)
    {
        let sign=obj.sign
        Reflect.deleteProperty(obj,'sign')
        var string =query.stringify(obj,null,null,{ encodeURIComponent: res=>res }); 
        string+='&key='+ (obj.key?obj.key:$ToolPay.private.appsecret)
        let signAfter = crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase(); 
        return (sign==signAfter)
    }

    static async back(obj)
    {
        let sign=privatePay.paysignapi(obj)
        let data= await $Sys.model
        (
            '/request/fetch','post',
            [
                {
                    host: $ToolPay.private.gateway,
                    path: '/refund',
                    method: 'POST',
                    data:sign,
                }
            ]
        );

        return $Sys.model('/tool/wx/xml','getXml',[data.data])
    }

    static async query(obj,url='/orderquery')
    {
        let sign=privatePay.paysignapi(obj)
        let data= await $Sys.model
        (
            '/request/fetch','post',
            [
                {
                    host: $ToolPay.private.gateway,
                    path: url,
                    method: 'POST',
                    data:sign,
                }
            ]
        );

        return data.data
    }

    static async tran(obj,url='/transfers')
    {
        if(obj.re_user_name)obj.check_name='FORCE_CHECK'
        let sign=privatePay.paysignapi(obj)
        let data= await $Sys.model
        (
            '/request/fetch','post',
            [
                {
                    host: $ToolPay.private.gateway,
                    path: url,
                    method: 'POST',
                    data:sign,
                }
            ]
        );

        return data.data
    }


    static success()
    {
    	return `SUCCESS`
    }
    
}
/*-------------------------------------------------------------------------------------------*/    
module.exports=privatePay;