<?php

namespace app\api\controller;


use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use think\Db;
use app\admin\model\Admin;
use think\Config;
use think\Validate;

/**
 * API控制器基类
 */
class Adminapi
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    public $page = 1;
    public $listrow = 10;
    protected $_error = '';
    protected $admin_uid = false;
    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;
        $this->page = input('page',1);
        $this->listrow= input('listrow',10);
        // 控制器初始化
        $this->_initialize();
        //验证后台用户和密码
        $this->admin_login();
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 管理员登录
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param int    $keeptime 有效时长
     * @return  boolean
     */
    public function auth_login($username, $password, $keeptime = 0)
    {
        $admin = Admin::get(['username' => $username]);
        if (!$admin) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin['status'] == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }
        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        if ($admin->password != md5(md5($password) . $admin->salt)) {
            $admin->loginfailure++;
            $admin->save();
            $this->setError('Password is incorrect');
            return false;
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->save();

        //登录关键
        $this->admin_uid = $admin->id;

        return true;
    }
    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }

    public function admin_login()
    {

        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
            ];

            $validate = new Validate($rule, [], ['username' => '用户名', 'password' => '密码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }

            $result = $this->auth_login($username, $password, 0);
            if ($result === true) {
                return $this->admin_uid;
            } else {
                $msg = $this->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg);
            }
        }else{
            $this->error('no post');
        }

    }

    //接口
    public function index(){
        $admin_uid = $this->admin_uid;
        $this->success('success',$admin_uid);
    }


    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        if(empty($msg)){
            $msg = '操作成功';
        }
        $this->result($msg, $data, $code, $type, $header);
    }
    //find查询出来的结果如果为空数组,强制转换object
    protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        if(empty($msg)){
            $msg = '操作成功';
        }
        if(is_null($data) || $data === []){
            $data = (object)[];
        }
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        if(empty($msg)){
            $msg = __('Invalid parameters');
        }
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型,支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];


        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }
}