<?php

namespace app\index\extend;

/**
 * Created by PhpStorm.
 * User: zw
 * Date: 2017/12/4
 * Time: 9:35
 * 基类
 */
use app\model\GOperatingRecords;
use think\Controller;
use think\Request;
use think\Response;
use think\Session;
use think\Db;

class Basic extends Controller
{
    /**
     * 访问请求对象
     * @var Request
     */
    public $request;

    public $params;

    public $userName;

    public $userId;

    public $lastLoginTime;

    protected $filterVerify = array(
        "index/login",
        "index/loginVerify",
    );

    /**
     * 基础接口SDK
     * @param Request|null $request
     */
    public function __construct(Request $request = null)
    {
        // CORS 跨域 Options 检测响应
        $this->corsOptionsHandler();
        // 输入对象
        $this->request = is_null($request) ? Request::instance() : $request;

        if (strtoupper($this->request->method()) === "GET") {
            $this->params = $this->request->param();
        } elseif (strtoupper($this->request->method()) === "POST") {
            $this->params = $this->request->param() != null ? $this->request->param() : null;
        }
        $requestPath = $this->request->routeInfo()["rule"][0] . "/" . $this->request->routeInfo()["rule"][1];


        if (!in_array(trim($requestPath), $this->filterVerify)) {
            $this->userVerify();
        }

    }


    /**
     * 验证登录时效
     */
    public function userVerify(){

        $this->userName = Session::get("userName");
        $this->userId = Session::get("userId");
        $this->lastLoginTime = Session::get("lastLoginTime");
        if(empty($this->userName) || empty($this->userId) || empty($this->lastLoginTime) ){
            $this->redirect('/index/login');
        }
        //登录有效期为1小时
        if ((time() - $this->lastLoginTime) > 7200) {
            $this->redirect('/index/login');
        }
    }

    /**
     * 输出返回数据
     * @param string $msg 提示消息内容
     * @param string $code 业务状态码
     * @param mixed $data 要返回的数据
     * @param string $type 返回类型 JSON XML
     * @return Response
     */
    public function response($code = 'SUCCESS', $msg, $data = [], $type = 'json')
    {
        $result = [ 'code' => $code, 'msg' => $msg, 'data' => $data, 'type' => strtolower($type) ];
        return Response::create($result, $type);
    }


    /**
     * Cors Options 授权处理
     */
    public static function corsOptionsHandler()
    {
        if (request()->isOptions()) {
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
            header('Access-Control-Max-Age:1728000');
            header('Content-Type:text/plain charset=UTF-8');
            header('Content-Length: 0', true);
            header('status: 204');
            header('HTTP/1.0 204 No Content');
            exit;
        }
    }

    /**
     * Cors Request Header信息
     * @return array
     */
    public static function corsRequestHander()
    {
        return [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Credentials' => true,
            'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS',
            'Access-Defined-X-Support' => 'service@cuci.cc',
            'Access-Defined-X-Servers' => 'Guangzhou Cuci Technology Co. Ltd',
        ];
    }
    
    
       /**
     * 设置一条或者多条数据的状态
     * @param $script 严格模式要求处理的纪录的uid等于当前登陆用户UID
     */
    public function setStatus($model = CONTROLLER_NAME, $script = false) {
        $ids = $this->request->param('ids/a');
        $status = $this->request->param('status');
        if (empty($ids)) {
            $this->error('请选择要操作的数据');
        }
        $model_primary_key = model($model)->getPk();
        $map[$model_primary_key] = ['in',$ids];
        if ($script) {
            $map['uid'] = ['eq', is_login()];
        }
        switch ($status) {
            case 'forbid' :  // 禁用条目
                $data = ['status' => 0];
                $this->editRow(
                    $model,
                    $data,
                    $map,
                    ['success'=>'禁用成功','error'=>'禁用失败']
                );
                break;
            case 'resume' :  // 启用条目
                $data = ['status' => 1];
                $map  = array_merge(['status' => 0], $map);
                $this->editRow(
                    $model,
                    $data,
                    $map,
                    array('success'=>'启用成功','error'=>'启用失败')
                );
                break;
            case 'hide' :  // 隐藏条目
                $data = array('status' => 1);
                $map  = array_merge(array('status' => 2), $map);
                $this->editRow(
                    $model,
                    $data,
                    $map,
                    array('success'=>'隐藏成功','error'=>'隐藏失败')
                );
                break;
            case 'show' :  // 显示条目
                $data = array('status' => 2);
                $map  = array_merge(array('status' => 1), $map);
                $this->editRow(
                   $model,
                   $data,
                   $map,
                   array('success'=>'显示成功','error'=>'显示失败')
                );
                break;
            case 'recycle' :  // 移动至回收站
                $data['status'] = -1;
                $this->editRow(
                    $model,
                    $data,
                    $map,
                    array('success'=>'成功移至回收站','error'=>'删除失败')
                );
                break;
            case 'restore' :  // 从回收站还原
                $data = array('status' => 1);
                $map  = array_merge(array('status' => -1), $map);
                $this->editRow(
                    $model,
                    $data,
                    $map,
                    array('success'=>'恢复成功','error'=>'恢复失败')
                );
                break;
            case 'delete'  :  // 删除条目
                action_log(0, is_login(), ['param'=>$this->param],'删除操作');
                $result = model($model)->where($map)->delete();
                if ($result) {

                    $this->success('删除成功，不可恢复！');
                } else {
                    $this->error('删除失败');
                }
                break;
            default :
                $this->error('参数错误');
                break;
        }
    }

    /**
     * 记录操作
     *
     * @param int $agents_id
     * @param string $type
     * @param string $remark
     * @return bool|int|string
     */
    public function operating_records($agents_id = 0, $type = '' ,$remark = '') {
        $records = new GOperatingRecords();
        $result  = $records->record($agents_id, $type, $remark);
        return $result;
    }

}


