<?php

namespace app\api\controller\cloudapi;

use app\admin\model\reservoir\Equipment;
use app\common\controller\Api;
use app\common\library\cloudapi\CloudapiSign;
use app\common\library\cloudapi\ErrorCode;
use think\Exception;
use think\Request;

/**
 * 云API基类
 * Class Base
 * @package app\api\controller\cloudapi
 */
class Base extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //API用户信息
    protected $apiUserInfo = null;

    /**
     * 获取当前用户基本信息
     * Base constructor.
     * @param Request|null $request
     */
    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $params = $request->param();
        $token = $request->header('token');

        if (!empty($params['token']) || !empty($token)){
            //有token走token流程
            $token = empty($token) ? $params['token'] : $token;

            // 获取用户基本信息
            $apiUser = (new \app\admin\model\cloudapi\User())->where(['token' => $token])->find();
            if (empty($apiUser)){
                $this->error(ErrorCode::getMessage(ErrorCode::INVALID_TOKEN),null,ErrorCode::INVALID_TOKEN);
            }
            if ($apiUser['expire_time'] < time()){
                $this->error(ErrorCode::getMessage(ErrorCode::TOKEN_EXPIRATION_DATE),null,ErrorCode::TOKEN_EXPIRATION_DATE);
            }
            $this->apiUserInfo = $apiUser;

            //认证访问权限
            if (!$this->auth()){
                $this->error(ErrorCode::getMessage(ErrorCode::NO_ACCESS_PERMISSIONS),null,ErrorCode::NO_ACCESS_PERMISSIONS);
            }
        }else{
            //走验签流程
            try {
                CloudapiSign::check($params);
            } catch (Exception $e) {
                $this->error($e->getMessage(), null, $e->getCode());
            }
        }
    }

    /**
     * 认证权限
     */
    protected function auth(){
        // 检查接口权限
        $reqUri = request()->path();
        $apiModel = new \app\admin\model\cloudapi\Api();
        $apiId = $apiModel->where(['api_uri' => ['LIKE',"%" . trim($reqUri,'/')]])->value('id');
        $apiIds = explode(',', $this->apiUserInfo->api_ids);
        if (!in_array($apiId, $apiIds)){
            return false;
        }

        //检查水库权限
        $reservoirIds = explode(',', $this->apiUserInfo->reservoir_ids);
        $reservoirId = $this->request->param('reservoir_id');//根据水库ID
        if (!empty($reservoirId)){
            if (!in_array($reservoirId, $reservoirIds)){
                return false;
            }
        }
        $deviceCode = $this->request->param('device_code');//根据设备码
        $equipmentId = $this->request->param('equipment_id');//根据设备码
        $number = $this->request->param('number');//根据设备码
        if (!empty($deviceCode)){
            $device_code = $deviceCode;
        }elseif(!empty($equipmentId)){
            $device_code = $equipmentId;
        }elseif(!empty($number)){
            $device_code = $number;
        }
        if (!empty($device_code)){
            $reservoirId = (new Equipment())->where(['deviceId' => $device_code])->value('reservoir_id');
            if (!in_array($reservoirId, $reservoirIds)){
                return false;
            }
        }

        return true;
    }
}