<?php
namespace Home\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=utf-8");
class WxJsAPIController extends Controller
{
	
	public function warning()
	{
		echo 'echomod';
	}

    /**
     * 获取 支付参数 (订单)
     */
    public function getParams()
    {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        // 引入退款类
        vendor('WxPayPubHelper.EnterprisePayment');
        $openid = $_GET["openid"];
        $order_sn = $_GET["order_sn"];
        $form_id = $_GET['form_id'];
        $money = M("order")->where("`order_sn`='{$order_sn}'")->getField("total_fee");
        // 保存 prepay_id (form_id)
        M("order")->where("`order_sn`='{$order_sn}'")->setField("prepay_id", $form_id);
        $result = $this->pay($openid, $money, $order_sn);
        if ($result['status'] == -1) {
            $data = array("status" => -1, "msg" => $result['msg']);
        } else {
            $data = array("status" => 1, "parameters" => $result['parameters']);
        }
        apiReturn($data);
    }

    /**
     * 调起支付 (订单)
     */
    public function pay($openid, $money, $order_sn)
    {
        $money = $money*100;
        $order_sn = $order_sn;
        //====================================================================================================
        $payname = "NO:{$order_sn}";
        // $money = (int)$money;
        $jsApi = new \JsApi_pub();
        //====================================================================================================
        //支付信息
        $unifiedOrder = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid",$openid);//用户表示
        $unifiedOrder->setParameter("body",$payname);//商品描述
        $out_trade_no = $order_sn;      //=====================================
        $unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户定单号
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url", "http://" . $_SERVER['HTTP_HOST'] . U("notyify"));//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //=========步骤3：使用jsapi调起支付============
        $result = $unifiedOrder->getPrepayId();
        if ($result['status'] == -1) {
            $data = array("status" => -1, "msg" => $result['msg']);
        } elseif ($result['status'] == 1) {
            // 参数设置 prepay_id
            $jsApi->setPrepayId($result['prepay_id']);
            $parameters = json_decode($jsApi->getParameters());
            $data = array("status" => 1, "parameters" => $parameters);
        }
        return $data;
    }

    /**
     * 微信支付回调地址 (订单)
     */
    public function notyify()
    {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        // 引入退款类
        vendor('WxPayPubHelper.EnterprisePayment');
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify -> saveData($xml);
        $msg = array();
        $msg = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        } else {
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        // 订单支付金额判断
        $sn = $notify->data["out_trade_no"];    // 订单号
        // $fee = $notify->data["total_fee"];    // 支付金额
        // $result = D("Order")->payFeeCheck($sn, $fee);
        // if (!$result) {
        //     die();
        // }
        echo $returnXml;
        file_put_contents("./Logs/checkSign.log", date("Y-m-d H:i:s ") . serialize($returnXml) . "\r\n", FILE_APPEND);
        if ($notify->checkSign() == TRUE) {
            // $sn = $notify->data["out_trade_no"];
            $transaction_id = $notify->data["transaction_id"];
            if ($notify->data["return_code"] == "FAIL") {
                //通信出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/payReturnFail.log", date("Y-m-d H:i:s ") . serialize($notify) . "\r\n", FILE_APPEND);
            }elseif($notify->data["result_code"] == "FAIL"){
                //业务出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/payResultFail.log", date("Y-m-d H:i:s ") . serialize($notify) . "\r\n", FILE_APPEND);
            }else{
                //支付成功，此处应该更新一下定单状态，商户自行增删操作
                D("Order")->payBySn($sn, $transaction_id);
                file_put_contents("./Logs/paySuccess.log", date("Y-m-d H:i:s ") . serialize($notify) . " SQL: " . D("Order")->getlastsql() . "\r\n", FILE_APPEND);
            }
        } else {
            file_put_contents("./Logs/checkSignFalse.log", date("Y-m-d H:i:s ") . serialize($notify) . "\r\n", FILE_APPEND);
        }
    }
    /**
     * 测试支付回调 (订单)
     */
    public function test_notyify()
    {
        $order_sn = $_GET['order_sn'];
        $transaction_id = "test_id";
        $result = D("Order")->payBySn($order_sn, $transaction_id);
        print_r($result);
    }

    /**
     * 宴席支付参数
     */
    public function getDinnerParams()
    {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        $openid = $_GET["openid"];
        $dinner_sn = $_GET["dinner_sn"];
        $money = M("dinner")->where("`dinner_sn`='{$dinner_sn}'")->getField("total_fee");
        $result = $this->payDinner($openid, $money, $dinner_sn);
        if ($result['status'] == -1) {
            $data = array("status" => -1, "msg" => $result['msg']);
        } elseif ($result['status'] == 1) {
            $data = array("status" => 1, "parameters" => $result['parameters']);
        }
        apiReturn($data);
    }

    /**
     * 调起支付 (宴席)
     */
    public function payDinner($openid, $money, $dinner_sn)
    {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        $money = $money*100;
        $dinner_sn = $dinner_sn;
        //====================================================================================================
        $payname = "NO:{$dinner_sn}";
        // $money = (int)$money;
        $jsApi = new \JsApi_pub();
        //====================================================================================================
        //支付信息
        $unifiedOrder = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid",$openid);//用户表示
        $unifiedOrder->setParameter("body",$payname);//商品描述
        $out_trade_no = $dinner_sn;      //=====================================
        $unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户定单号
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url", "http://" . $_SERVER['HTTP_HOST'] . U("notyifyDinner"));//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //=========步骤3：使用jsapi调起支付============
        $result = $unifiedOrder->getPrepayId();
        if ($result['status'] == -1) {
            $data = array("status" => -1, "msg" => $result['msg']);
        } elseif ($result['status'] == 1) {
            // 保存 prepay_id
            $saveData = array(
                "status" => 3,
                "prepay_id" => $result['prepay_id'],
                "pay_time" => $_SERVER['REQUEST_TIME']
            );
            M("dinner")->where("`dinner_sn`='{$dinner_sn}'")->save($saveData);
            // 参数设置 prepay_id
            $jsApi->setPrepayId($result['prepay_id']);
            $parameters = json_decode($jsApi->getParameters());
            $data = array("status" => 1, "parameters" => $parameters);
        }
        return $data;
    }

    /**
     * 微信支付回调地址 (宴席)
     */
    public function notyifyDinner()
    {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        // 引入退款类
        vendor('WxPayPubHelper.EnterprisePayment');
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify -> saveData($xml);
        $msg = array();
        $msg = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        } else {
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        // 订单支付金额判断
        $sn = $notify->data["out_trade_no"];    // 订单号
        echo $returnXml;
        file_put_contents("./Logs/checkSign.log","Start " . date("Y-m-d H:i:s ") . serialize($returnXml) . "\r\n", FILE_APPEND);
        if ($notify->checkSign() == TRUE) {
            $transaction_id = $notify->data["transaction_id"];
            if ($notify->data["return_code"] == "FAIL") {
                //通信出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/payReturnFail.log", "return_code:FAIL\r\n" . json_encode($notify) . "\r\n\r\n", FILE_APPEND);
            }elseif($notify->data["result_code"] == "FAIL"){
                //业务出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/payResultFail.log", "result_code:FAIL\r\n" . json_encode($notify) . "\r\n\r\n", FILE_APPEND);
            }else{
                //支付成功，此处应该更新一下定单状态，商户自行增删操作
                M("dinner")->where("`dinner_sn`='{$sn}'")->setField("transaction_id", $transaction_id);
                file_put_contents("./Logs/paySuccess.log", "SQL: " . M("dinner")->getlastsql() . "\r\n", FILE_APPEND);
                $row = M("dinner")->where("`dinner_sn`='{$sn}'")->find();
                file_put_contents("./Logs/paySuccess.log", "SQL: " . M("dinner")->getlastsql() . "\r\n", FILE_APPEND);
                $dinner_id = $row['dinner_id'];
                $dinnerDishGoodList = M("dinnerDishGood")->where("`dinner_id`={$dinner_id}")->select();
                file_put_contents("./Logs/paySuccess.log", "SQL: " . M("dinnerDishGood")->getlastsql() . "\r\n", FILE_APPEND);
                foreach ($dinnerDishGoodList as $key => $value) {
                    $good_id = $value['good_id'];
                    $num = $value['num'];
                    // 商品总仓库库存减少
                    $res = M("goodsStorage")->where("`village_id`=0 AND `good_id`={$good_id}")->lock()->setDec("storage", $num);
                    file_put_contents("./Logs/paySuccess.log", "SQL: " . M("goodsStorage")->getlastsql() . "\r\n", FILE_APPEND);
                    if ($res) {
                        // 生成总仓库出库记录
                        $addData = array(
                            "choice" => 1,
                            "type" => 3,
                            "order_id" => 0,
                            "dinner_id" => $dinner_id,
                            "good_id" => $good_id,
                            "change_num" => $num,
                            "create_time" => $_SERVER['REQUEST_TIME']
                        );
                        M("storageTotal")->add($addData);
                        file_put_contents("./Logs/paySuccess.log", "SQL: " . M("storageTotal")->getlastsql() . "\r\n", FILE_APPEND);
                    }
                }
                unset($key, $value);
                file_put_contents("./Logs/paySuccess.log","Fin" . "\r\n\r\n", FILE_APPEND);
                // 备注：多余商品退货 & 增加的商品 不在这里操作库存, 在生成附加订单及退货订单时进行库存操作
            }
        } else {
            file_put_contents("./Logs/checkSignFalse.log", date("Y-m-d H:i:s ") . serialize($notify) . "\r\n", FILE_APPEND);
        }
    }
}