<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2023/02/05
 * Time: 20:33
 */


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\admin\model\AdminMenu;
use think\Db;
use think\Hook;


class AdminLog extends Permissions
{
    /**
     * 管理员操作记录
     * @return mixed
     */
    public function index()
    {
        $model = new \app\admin\model\AdminLog();
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [];
            if (isset($post['admin_menu_id']) and $post['admin_menu_id'] > 0) {
                $where['admin_menu_id'] = $post['admin_menu_id'];
            }
            if (isset($post['admin_id']) and $post['admin_id'] > 0) {
                $where['admin_id'] = $post['admin_id'];
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $timerang = explode(' - ', $post['create_time']);
                $min_time = strtotime($timerang[0]);
                $max_time = strtotime($timerang[1]);
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('id desc')->select();

            $admin_cates = Db::name('admin_cate')->column('name', 'id');
            foreach ($data as $k => $v) {
                $v['title'] = !empty($v->menu) ? $v->menu->name : 'no route';
                $v['params'] = htmlspecialchars($v->params);
                $v['person'] = $v->admin->nickname;
                if (!empty($v->admin_id)) {
                    $v['person'] .= '<' . $admin_cates[$v->admin->admin_cate_id] . '>';
                }
                $data[$k] = $v;
            }

            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            //菜单
            $model = new AdminMenu();
            $menu = $model->order('orders asc')->select();
            $menus = $model->menulist($menu);
            $this->assign('menus', $menus);
            //管理员
            $this->assign('adminer', Db::name('admin')->select());
            return $this->fetch();
        }
    }

    //清空log
    public function clearLog()
    {
        $prefix = \think\Env::get("db_prefix", "tplay_");
        Db::execute("TRUNCATE {$prefix}admin_log");
        //
        $result = Hook::exec('app\\common\\behavior\\AdminLogBehavior', 'run', $params);
        $this->success("执行成功");
    }
}
