<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\model;

use app\admin\library\Auth;
use think\Model;
use think\Loader;
use think\Db;

class AdminLog extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    //自定义日志标题
    protected static $title = '';
    //自定义日志内容
    protected static $content = '';
    //忽略的链接正则列表
    protected static $ignoreRegex = [
        '/^(.*)\/(selectpage|index)$/i',
    ];

    public static function setTitle($title)
    {
        self::$title = $title;
    }

    public static function setContent($content)
    {
        self::$content = $content;
    }

    public static function setIgnoreRegex($regex = [])
    {
        $regex = is_array($regex) ? $regex : [$regex];
        self::$ignoreRegex = array_merge(self::$ignoreRegex, $regex);
    }

    /**
     * 记录日志
     * @param string $title
     * @param string $content
     */
    public static function record1($title = '', $content = '',$info = [])
    {
        $auth = Auth::instance();
        $admin_id = $auth->isLogin() ? $auth->id : 0;
        $username = $auth->isLogin() ? $auth->username : __('Unknown');

        $controllername = Loader::parseName(request()->controller());
        $actionname = strtolower(request()->action());
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        if (self::$ignoreRegex) {
            foreach (self::$ignoreRegex as $index => $item) {
                if (preg_match($item, $path)) {
                    return;
                }
            }
        }
        $content = $content ? $content : self::$content;
        if (!$content) {
            $content = request()->param('', null, 'trim,strip_tags,htmlspecialchars');
            $content = self::getPureContent($content);
        }
        $title = $title ? $title : self::$title;
        if (!$title) {
            $title = [];
            $breadcrumb = Auth::instance()->getBreadcrumb($path);
            foreach ($breadcrumb as $k => $v) {
                $title[] = $v['title'];
            }
            $title = implode(' / ', $title);
        }
        self::create([
            'title'     => $title,
            'content'   => !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content,
            'url'       => substr(request()->url(), 0, 1500),
            'admin_id'  => $admin_id,
            'username'  => $username,
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'info'=>iserializer($info),
            'ip'        => request()->ip()
        ]);
    }
    
    public static function record($title = '', $content = '',$json = '',$table = '')
    {
        $auth = Auth::instance();
        if(!$auth->isLogin()){
            return false;
        }
        $admin_id = $auth->isLogin() ? $auth->id : 0;
        $username = $auth->isLogin() ? $auth->username : __('Unknown');

        // 设置过滤函数
        request()->filter('trim,strip_tags,htmlspecialchars');

        $controllername = Loader::parseName(request()->controller());
        $actionname = strtolower(request()->action());
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        if (self::$ignoreRegex) {
            foreach (self::$ignoreRegex as $index => $item) {
                if (preg_match($item, $path)) {
                    return;
                }
            }
        }
        $is_restore = -1;
        $search = '';
        if(empty($content) && !empty($json) && !empty($table)){
            $content = "";
            
            $search_fields = ['id','user_id','order_no','title','name','nickname','realname'];
            if(!empty($json['table'])){
                
                foreach ($json['data'] as $key => $val){
                    if(!in_array($key,$search_fields)){
                        continue;
                    }
                    if(is_array($val)){
                        $val = json_encode($val,JSON_UNESCAPED_UNICODE);
                    }
                    $content .= $key."：".$val;
                    $content .= "</br>";
                }
                $is_restore = 1;
                
            }
            else{

                $columns = Db::query('SHOW FULL COLUMNS FROM '.tablename($table));
            
                $json1 = [];
                foreach ($columns as $key => $val){
                    if(!is_null($json[$val['Field']])){
                        $json1[$val['Field']] = $json[$val['Field']];
                    }
                }
                $json = $json1;
                
                $columns = array_skey($columns,"Field");
                $exclude_fields = [];
                if($table == 'bbfx_goods'){
                    $exclude_fields = ['commission1','commission2','commission3','jc_reward','jd_reward','pj_reward','ab_reward','repurchase_reward1','repurchase_reward2','repurchase_reward3','repurchase_pingji_reward','level_discount','returns','agent','give','contract','guarantee','cumulative_fanhuan','cloud_warehouse','cloud_warehouse_chuhuo','ladder_push','plugin'];
                }

                foreach ($json as $key => $val){
                
                    if(in_array($key,$exclude_fields)){
                        continue;
                    }
                    if(is_array($val)){
                        $val = json_encode($val,JSON_UNESCAPED_UNICODE);
                    }
                    
                    if(!empty($columns[$key]) && !empty($columns[$key]['Comment'])){
                        $Comment = $columns[$key]['Comment'];
                        $Comments = explode(":",$Comment);
                        if(count($Comments) > 1){
                            $sels = explode(",",$Comments[1]);
                            $select = [];
                            foreach ($sels as $k => $v){
                                $s = explode("=",$v);
                                $select[$s[0]] = $s[1]; 
                            }
                            
                            if(!empty($select[$val])){
                                $content .= $Comments[0]."：".$select[$val];
                            }
                            else{
                                $content .= $Comments[0]."：".$val;
                            }
                        }
                        else{
                            
                            $str = $val;
                            
                            $content .= $Comments[0]."：".$str;
                        }
                    }
                    else{
                        $content .= $key."：".$val;
                    }
                    $content .= "</br>";
                }
            }
            
        }
        $search = '';
        if(!empty($json)){
            $search_fields = ['id','user_id','order_no','title','name','nickname','realname'];
            if(!empty($json['table'])){
                foreach ($json['data'] as $key => $val){
                    if(!in_array($key,$search_fields)){
                        continue;
                    }
                    $search .= $json['table']."_".$key."=".$val."&";
                }
            }
            else{
                
                foreach ($json as $key => $val){
                    if(!in_array($key,$search_fields)){
                        continue;
                    }
                    $search .= $table."_".$key."=".$val."&";
                }
            }
        }
        
        $json = $json ?: self::$content;
        if (!$json) {
            $json = request()->param('') ?: file_get_contents("php://input");
            $json = self::getPureContent($json);
        }
        $title = $title ?: self::$title;
        if (!$title) {
            // $title = [];
            // $breadcrumb = Auth::instance()->getBreadcrumb($path);
            
            // foreach ($breadcrumb as $k => $v) {
            //     $title[] = $v['title'];
            // }
            // $title = implode(' / ', $title);
            $path = str_replace("bbfxshop/","",$path);
            $title = self::getRuleName($path);
            if(empty($title)){
                return false;
            }
            // file_put_contents("log111.txt",$RuleName);
        }
        self::create([
            'uniacid'   => UNIACID,
            'title'     => $title,
            'content'   => $content,
            'is_restore'   => $is_restore,
            'search'      => $search,
            'info'      => !is_scalar($json) ? json_encode($json, JSON_UNESCAPED_UNICODE) : $json,
            'url'       => substr(xss_clean(strip_tags(request()->url())), 0, 1500),
            'admin_id'  => $admin_id,
            'username'  => $username,
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip'        => xss_clean(strip_tags(request()->ip()))
        ]);
    }
    
    protected static function getRuleName($path,$list=[]){
        $rule = Db::name("bbfx_auth")->where(['rule'=>$path,'type'=>1])->field("id,rule,pid,name")->find();
        if(empty($rule)){
            return false;
        }
        $rule['num'] = 0;
        $list[] = $rule;
        return self::getChildRuleName($rule['pid'],$list);
    }
    
    protected static function getChildRuleName($pid,$list){
        $rule = Db::name("bbfx_auth")->where(['id'=>$pid])->field("id,rule,pid,name")->find();
        if(empty($rule)){
            
            $nums = array_column($list,'num');
            array_multisort($nums,SORT_DESC,$list);
            
            $name = array_column($list, 'name');;
            
            
            return implode("-",$name);
            
        }
        if(count($list) > 0){
            $rule['num'] = $list[count($list) - 1]['num'] + 1;
        }
        else{
            $rule['num'] = 0;
        }
        $list[] = $rule;
        
        return self::getChildRuleName($rule['pid'],$list);
    }

    /**
     * 获取已屏蔽关键信息的数据
     * @param $content
     * @return false|string
     */
    protected static function getPureContent($content)
    {
        if (!is_array($content)) {
            return $content;
        }
        foreach ($content as $index => &$item) {
            if (preg_match("/(password|salt|token)/i", $index)) {
                $item = "***";
            } else {
                if (is_array($item)) {
                    $item = self::getPureContent($item);
                }
            }
        }
        return $content;
    }

    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id')->setEagerlyType(0);
    }
}
