<?php
namespace app\web\controller;
use app\model\Goods as GoodsModel;
use app\model\Card as CardModel ;
use app\web\lib\Order as OrderOp ;
use app\model\OrderGoods as OrderGoodsModel ;
use think\facade\View;

class Order extends WebController{

    /**
     * 创建订单
     */
    public function create(OrderOp $order){

        $d = request()->post();

        $order->init($d);
        $rs = $order->create() ;
        $params= $order->getPayUrl() ;
        return $this->responseSuccess($params);

    }

    // 订单结果
    public function index(){

        $trade_no = request()->get('trade_no');
        $order = OrderGoodsModel::getTradeNoOrder($trade_no);
        if( is_null( $order ) ){
            return $this->responseError('订单不存在');
        }

        return view('success') ;
    }

    public function status(){

        $trade_no = request()->get('trade_no');
        $order = OrderGoodsModel::getTradeNoOrder($trade_no);
        if( is_null( $order ) ){
            return $this->responseError('订单不存在');
        }

        // 显示一下订单信息

        View::assign('order',$order);
        return view('success') ;
    }


    public function query($trade_no = ''){

        $querys = cache($trade_no.'_query');
        $time = getCurrentTime() ;
        $data = [] ;

        if( !empty( $trade_no ) ) {
            if ($querys) {
                // 判断是否需要查询数据库
                if ($querys['i'] < 4 || $querys['time'] < $time) {
                    $data = OrderGoodsModel::getTradeNoOrder($trade_no);
                    $querys['i'] += 1 ;
                    $querys['time'] = $time + 180 ;
                    $querys['data'] = $data ;
                    cache($trade_no.'_query',$querys);

                }else{
                    $data = $querys['data'] ;
                }

            }else{
                $data = OrderGoodsModel::getTradeNoOrder($trade_no);
                cache($trade_no.'_query',['i'=>1,'time'=>$time]);
            }
        }
        /*else{

            if( !empty( $trade_no ) ){
                $data = OrderGoodsModel::getTradeNoOrder($trade_no);
                if( !is_null( $data ) ) {
                    $order = $data ;
                }
            }
        }*/

        View::assign('order',$data);
        View::assign('trade_no',$trade_no);
        return view() ;
    }
}
