<?php
/**
 * Created by PhpStorm.
 * User: ChiaHsiang
 * Date: 2018/8/20
 * Time: 13:03
 */

namespace app\common\behavior;

use app\api\model\AdminLog;
use think\Request;
use think\Session;
use think\Config;

class Log
{
    public function run() {
        try {
            $request = Request::instance();
            $controller = $request->controller();
            $controller_path = explode('.', $controller);
            $controller = strtolower(end($controller_path));

            $action = strtolower($request->action());

            $data['controller'] = $controller;
            $data['action'] = $action;
            $data['params'] = $request->param('id');

            $admin_info = Session::get('admin_info');

            $data['admin_uuid'] = $admin_info['uuid'];

            $this->getDesc($data);

            $data['uuid'] = uuid();

            return AdminLog::build()
                ->save($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    private function getDesc(&$data) {
        $controller = $data['controller'];
        $action = $data['action'];

        $log2desc = Config::get('log2desc');

        $controller_desc = $log2desc[$controller]['desc'];
        $operate_desc = $log2desc[$controller]['action'][$action]['desc'];

        $data['desc'] = "管理员在［{$controller_desc}］进行了［{$operate_desc}］操作";

        if (!empty($data['params'])) {
            $data['desc'] .= "，对应参数 id 为 {$data['params']}";
        }
    }

}