<?php
namespace app\web\controller;

use app\model\Card;
use app\model\OrderGoods as OrderGoodsModel;
use app\model\UserPay;
use app\pay\lib\Sign;
use think\response\Redirect;

class Notify extends WebController{

    public function index(){

        $data = request()->get();

        if( empty( $data ) ){
            return $this->responseError('数据不存在');
        }

        if( $data['trade_status'] != 'TRADE_SUCCESS'){
            echo 'fails' ;
        }

        $order = OrderGoodsModel::where([
            'trade_no'=>$data['out_trade_no'],
            'status' => 0
        ])->findOrEmpty();

        if( $order->isEmpty() ){
            return $this->responseError('订单不存在或已经修改状态');
        }

        $rs = OrderGoodsModel::update(['id'=>$order->id,'status'=>1]) ;

        if( $rs !== FALSE ){
            if( $order->goods_type == 2 ){
                Card::update(['id'=>$order->card_id,'status'=>2]);
            }
        }

        echo 'success' ;
        exit;
    }

    public function success(){

        $params = request()->get();
        //print_r($params);
        $userPay = UserPay::getPayConfig() ;
        if( !Sign::validate($params,$params['sign'],$userPay['code_key']) ){
            return $this->responseError('验证失败');
        }
        $order = OrderGoodsModel::getTradeNoOrder($params['out_trade_no']);
        if( is_null( $order ) ){
            return $this->responseError('订单不存在');
        }

        return redirect('/web/query?trade_no='.$order->trade_no) ;

    }
}
