<?php 
header("Content-type: text/html; charset=utf-8");
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';
require_once '../lib/Base.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

//打印输出数组信息
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#00ff55;'>$key</font> : $value <br/>";
    }
}
function NumToStr($num){
    if (stripos($num,'e')===false) return $num;
    $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法，还原成字符串
    $result = "";
    while ($num > 0){
        $v = $num - floor($num / 10)*10;
        $num = floor($num / 10);
        $result   =   $v . $result;
    }
    return $result;
}
//①、获取用户openid
$tools = new JsApiPay();
// exit();
$openId = $tools->GetOpenid();
session_start();

//获取金额
$pFee = $_SESSION['premoney'];
// echo "<span>".$pFee."</span>";
$pBody = $_SESSION['body'];
$pCardNo = $_SESSION['cardno'];
$pRegID = $_SESSION['regId'];
$pRepeiceNo = $_SESSION['repeiceNo'];
$pOrder = $_SESSION['order'];
$pPatientID = $_SESSION['patientid'];
$pName = $_SESSION['name'];
$pPatientNO = $_SESSION['patientno'];
$tradeNo = NumToStr(WxPayConfig::MCHID.date("YmdHis"));

// echo "<span>".$pCardNo."</span>";
//微信订单表初始化
$tMO = new Model('wxorder');
$tTime = time();
$tDatas = $tMO->field('id')->where('out_trade_no = \''.$tradeNo.'\'')->select();
//查询卡号
$tMCMO = new Model('medical_card');
$tMCDatas = $tMCMO->field('med_c_card_no')->where('med_c_uid = '.$_SESSION['uid'])->select();
if(empty($pCardNo)) {
    $tCardNo = $tMCDatas[0]['med_c_card_no'];
}else{
    $tCardNo = $pCardNo;
}
if(empty($tDatas)) {
    $tData = array(
        'name' => $pName,
        'total_fee' => $pFee/100,
        'uid' => $_SESSION['uid'],
        'prepay_id' => $pOrder,
        'out_trade_no' => $tradeNo,
        'created' => $tTime,
        'status' => 1,
        'patientid' => $pPatientID,
        'regid' => $pRegID,
        'repeiceno' => $pRepeiceNo,
        'cardno' => $tCardNo,
    );

    $id = $tMO->insert($tData);
    if(!$id){
        return true;
    }
}else{
    $id = $tDatas[0]['id'];
}

switch($pBody) {
    case 'zyyj': $pBody = '住院押金';break;
    case 'mzjf': $pBody = '门诊缴费';break;
}
// var_dump($f);
//②、统一下单

$input = new WxPayUnifiedOrder();
$input->SetBody($pBody);
$input->SetAttach("test");
// $tradeNo = $input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetOut_trade_no($tradeNo);
$input->SetTotal_fee($pFee);
$timestamp = date("YmdHis");
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://lyl.medical.91paiyipai.com/wxpay/example/notifys.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order = WxPayApi::unifiedOrder($input);
// echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
// var_dump($order);exit();
// printf_info($input);
$jsApiParameters = $tools->GetJsApiParameters($order);

//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();

//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>确认支付</title>
	<meta name="viewport" content="width=device-width,initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="./css/wx.css">
    <!-- <link rel="stylesheet" href="../../medical_wx/lib/assets/css/bootstrap.min.css"> -->
    <link rel="stylesheet" href="../../medical_wx/lib/assets/css/home_two.css">
    <link rel="stylesheet" href="../../medical_wx/lib/assets/css/loaders.css">

</head>
<body class="wxbody">
	<div class="col-xs-12 wxcont">
		<h5>郴州市中医医院</h5>
		<h3>￥<?php echo $pFee/100;?></h3>
		<div class="col-xs-12 wxcol12">
			<p>收款方<span>郴州市中医医院</span></p>
			<p>商&nbsp;&nbsp;&nbsp;&nbsp;品<span><?php echo $pBody;?></span></p>
		</div>
		<div class="col-xs-12" style="cursor: pointer;" id="wx_btn"><button class="btn" id="btn" type="button" style="height: 50px;">立即支付</button></div>
	</div>
	<!-- <script src="../../medical_wx/lib/assets/js/jquery.min.js"></script> -->
	<script src="./js/jquery.js"></script>
    <!-- <script src="../../medical_wx/lib/assets/js/bootstrap.min.js"></script> -->
	<div class="tip_mess"></div>

    <script src="../../medical_wx/lib/assets/js/home.js"></script>
    <script src="../../medical_wx/js/base.js"></script>

    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="../../medical_wx/lib/assets/js/home.js"></script>

	<script type="text/javascript">
		// var t_uid = GetQuery('uid');
    var url = location.href.split('#')[0];
    var timestamp = '';
    var nonceStr = '';
    var signature = '';
    var uid = localStorage.getItem('uid', uid);

    //jssdk初始化配置
    (function () {
        $.ajax({
            type: 'post',
            async: true,
            url: domain1+'/apiv1_jssdk/',
            data:{url:decodeURI(url)},
            // beforeSend: function() {
            //     $.showLoading();
            // },
            success: function(obj) {
                // $.hideLoading();
                if(obj.status == 1) {
                    var data = obj.data;
                    timestamp = data.timestamp;
                    nonceStr = data.nonceStr;
                    signature = data.signature;
                    wx.config({
                        beta: true,
                        debug: false,//调试模式
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.nonceStr,
                        signature: data.signature,
                        jsApiList: [
                            "selectEnterpriseContact",
                            "checkJsApi",
                            "chooseImage",
                            "previewImage",
                            "uploadImage",
                            "downloadImage",
                            "openEnterpriseChat",
                            "openLocation",
                            "getLocation",
                            "chooseWXPay"
                        ]
                    })
                }else{
                    $.toptip(obj.msg,'error');return;
                }
            },
            error: function() {
                $.hideLoading();
                $.toptip('网络繁忙请稍后再试！');return;
            }
        })
    })();
    
    function pay(){
        var params = eval('(<?php echo $jsApiParameters;?>)');
        wx.chooseWXPay({
            nonceStr:params.nonceStr,
            package:params.package,
            paySign:params.paySign,
            signType:params.signType,
            timestamp:params.timeStamp+"",
            success: function(res) {
                // 支付成功后的回调函数
                if (res.errMsg == "chooseWXPay:ok") {
                    // refund("<?php echo $tradeNo;?>", "<?php echo $pFee;?>");
                    window.location.href='/medical_wx/h5/jfjl.html?title=缴费记录&type=jfjl&uid='+uid;
                } else {
                    alert(res.errMsg);
                }
            },
            cancel: function(res) {
                //支付取消
                alert('支付取消');
            }
        });
    }
		var btn = document.getElementById('btn');
		btn.onclick = function(){
			// alert('hello world!');
			pay();
		}
	</script>
</body>
</html>
