<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\common\behavior;

use app\common\model\Webconfig;
use think\Db;
use think\Request;
use think\Session;

class AdminLogBehavior
{
    /**
     * 全局记录admin_log
     * @param $params
     * @return bool
     */
    public function run(&$params)
    {
        $islog = Webconfig::getValue('is_log', 3600 * 24);
        if (empty($islog) || $islog != 1) {
            return true;//关闭了日志
        }
        $request = Request::instance();
        $data['admin_id'] = Session::get('admin')??0;//管理员id
        $data['ip'] = $request->ip();
        $data['url'] = limitStrLen('url', $request->url(), 255);
        $data['params'] = limitStrLen('params', $this->getParams($request->param()), 2000);
        $data['create_time'] = time();

        //获取url参数
        $url['module'] = $request->module();
        $url['controller'] = $request->controller();
        $url['function'] = $request->action();

        $ignore = ['admin/AdminLog/index', 'admin/Menu/index'];
        if (in_array($url['module'] . '/' . $url['controller'] . '/' . $url['function'], $ignore)) {
            return true;//排除
        }

        $data['admin_menu_id'] = Db::name('admin_menu')->where($url)->where('parameter', $request->query())->value('id') ?? Db::name('admin_menu')->where($url)->value('id');
        if (empty($data['admin_menu_id'])) {
            $data['admin_menu_id'] = 0;
        }
        //保存日志
        Db::name('admin_log')->insert($data);
        return true;
    }

    /**
     * @param $post
     * @return int|string
     */
    private function getParams($post)
    {
        if (empty($post) || count($post) == 0) {
            return "";
        }
        $str = "";
        foreach ($post as $key => $val) {
            if (is_array($val)) {
                $val = json_encode($val, 320);
            }
            if (empty($str)) {
                $str .= $key . '=' . $val;
            } else {
                $str .= '&' . $key . '=' . $val;
            }
        }
        return $str;
    }

    /**
     * 更新最新一条日志
     * @param $param string  [新的param]
     * @param $cover boolean [true覆盖param,false追加param]
     * @return bool
     */
    public function updateLastLog($param, $cover = true)
    {
        $islog = Webconfig::getValue('is_log', 3600 * 24);
        if (empty($islog) || $islog != 1) {
            return true;//关闭了日志
        }
        $model = new \app\admin\model\AdminLog();
        $last = $model->order('id desc')->find();
        $param = $cover ? $param : limitStrLen('params', $last->params . ' ' . $param, 2000);
        $model->save(['params' => $param], ['id' => $last->id]);
    }
}