<?php

use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;

class UserTest extends TestCase
{
    protected $token = '40d45add515486ab70a8a93336a835b2';

    /**
     * 测试模拟请求
     * @param string $method
     * @param string $url
     * @param array $params
     */
    public function request(string $method,string $url,array $params=[],$needToken=true){
        print_r(PHP_EOL.PHP_EOL.json_encode($params,JSON_UNESCAPED_UNICODE).PHP_EOL);

        if($needToken){
            $token=empty($this->token)?$this->getToken():$this->token;
        }else{
            $token='';
        }
        $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);
//        $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/user/login',['username'=>$this->username,'password'=>$this->password,'app_code'=>'JYGJ','app_key'=>'D0AB3EE73EDD8F70EB23E37231FCBC33']);
        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;
        }
        return $data['data']['token'];
    }

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testUserLogin()
    {
        $data=[];
        $data['user_name']='mp_admin';
        $data['password']='Mm123654!';

        $this->request('post','/api/admin/user/admin-login',$data,false);
    }


    public function testUserLogout()
    {
        $data=[
            'api_token'=>'76884827a184f909ca778f9373d19dd4'
        ];
        $this->request('post','/api/app/user/logout',$data);
    }

    public function testGetUser()
    {
        $data=[
        ];
        $ret=$this->request('get','/api/admin/user/get-admin-user',$data);
        print_r($ret);die;
        $this->assertTrue(true);
    }

    public function testDef()
    {
        $data=[

        ];
        $this->request('get','/',$data);
    }

    public function testGetProductByTypeIds(){
        $data=[
            'type_id'=>[3]
        ];
        $ret=$this->request('get','/api/product/get-list-by-type',$data);
        print_r($ret);die;
        $this->assertTrue(true);

    }

}
