<?php

use Illuminate\Support\Facades\DB;

abstract class TestCase extends Laravel\Lumen\Testing\TestCase
{
    protected $token = '';
    protected $username = 'william.y@matchpages.com';
    protected $password = 'Mm123654!';

    /**
     * Creates the application.
     *
     * @return \Laravel\Lumen\Application
     */
    public function createApplication()
    {
        return require __DIR__.'/../bootstrap/app.php';
    }

    /**
     * 测试模拟请求
     * @param string $method
     * @param string $url
     * @param array $params
     */
    public function request(string $method,string $url,array $params=[]){
        print_r(PHP_EOL.PHP_EOL.json_encode($params,JSON_UNESCAPED_UNICODE).PHP_EOL);
        $token=empty($this->token)?$this->getToken():$this->token;
       // $token=$this->getToken();

        $headers = [
            'X-Requested-With'=>'XMLHttpRequest',
            'Content-Type' => 'application/x-www-form-urlencoded',
            'token' => $token // AuthCheck的时候会进行刷新赋值
        ];

        $server = $this->transformHeadersToServerVars($headers);
        $response = $this->call($method,$url,$params,[], [], $server);
        print_r('HTTP状态码：'.$response->getStatusCode().PHP_EOL);
        print_r('返回值：'.PHP_EOL);
        $data = json_decode($response->getContent(),true);
        print_r($data);
//        $this->assertEquals(0,$data['ret']??-1);
        echo PHP_EOL.PHP_EOL.json_encode($data,JSON_UNESCAPED_UNICODE);
        return $data;
    }

    protected function getToken(){
        $response = $this->call('post','/api/admin/user/admin-login',['user_name'=>$this->username,'password'=>$this->password]);
        if($response->getStatusCode()!=200){
            echo '登录失败';exit;
        }
        $data = json_decode($response->getContent(),true);
        if(!isset($data['code'])||isset($data['code']) && $data['code']!=0){
            print_r($data);
            exit;
        }
        print_r($data);
        return $data['data']['token'];
    }

    /**
     * 覆盖setUp方法 添加对sql查询监听
     */
    public function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub
       DB::listen(function($query){
            $params = $query->bindings;
            $parttern = [];
            foreach($params as $key=>$value){
                $params[$key] = "'".str_replace('\'','\\\'',$value)."'";
                $parttern[] = '/(\?)/';
            }
            print_r(preg_replace($parttern,$params,$query->sql,1).';'.PHP_EOL);
        });
    }
}
