<?php

namespace app\manystoreapi\model;

use app\common\model\BaseModel;
use app\common\model\dyqc\ManystoreShop;
use app\common\model\school\classes\ClassesLib;
use app\manystore\model\Manystore;
use app\manystoreapi\library\Auth;
use think\Model;

class ManystoreApiLog extends BaseModel
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    //自定义日志标题
    protected static $title = '';
    //自定义日志内容
    protected static $content = '';

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

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

    public static function record($title = '')
    {
        $auth = Auth::instance();
        $shop_id = 0;
        $store_id = 0;
        $username =  __('Unknown');
        if(!defined('SHOP_ID')){
            define('SHOP_ID', 0);
        }
        if(!defined('STORE_ID')){
            define('STORE_ID',0 );
        }

        if(!defined('SHOP_USER_ID')){
            define('SHOP_USER_ID',0 );
        }

        if($auth->isLogin()){
            $shop_id =  SHOP_ID ;
            $store_id = STORE_ID;
            $username = $auth->username;
        }
        $content = self::$content;
        if (!$content) {
            $content = request()->param('', null, 'trim,strip_tags,htmlspecialchars');
            foreach ($content as $k => $v) {
                if (is_string($v) && strlen($v) > 200 || stripos($k, 'password') !== false) {
                    unset($content[$k]);
                }
            }
        }
        $title = self::$title;
        if (!$title) {
            $title = [];
            $breadcrumb = Auth::instance()->getBreadcrumb();

            foreach ($breadcrumb as $k => $v) {
                $title[] = $v['title'];
            }
            $title = implode(' ', $title);
        }
//        var_dump($breadcrumb);

        self::create([
            'shop_id'  => $shop_id ? $shop_id : 0,
            'store_id'  => $store_id ? $store_id : 0,
            'user_id'   => SHOP_USER_ID,
            'title'     => $title ?: ManystoreApiAuthRule::where("name",substr(request()->url(), 0, 1500))->value('title')?:"",
            'content'   => !is_scalar($content) ? json_encode($content) : $content,
            'url'       => substr(request()->url(), 0, 1500),
            'username'  => $username,
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip'        => request()->ip()
        ]);

    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }




    public function store()
    {
        return $this->belongsTo(Manystore::class, 'store_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function shop()
    {
        return $this->belongsTo(ManystoreShop::class, 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }




    /**得到基础条件
     * @param $status
     * @param null $model
     * @param string $alisa
     */
    public static function getBaseWhere($whereData = [], $model = null, $alisa = '',$with = false)
    {

        if (!$model) {
            $model = new static;
            if ($alisa&&!$with) $model = $model->alias($alisa);
        }
        if ($alisa) $alisa = $alisa . '.';
        $tableFields = (new static)->getTableFields();
        foreach ($tableFields as $fields)
        {
            if(in_array($fields, ['content']))continue;
//            if (isset($whereData[$fields]) && $whereData[$fields]) $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);

            if (isset($whereData[$fields]) && $whereData[$fields]){
                if(is_array($whereData[$fields])){
                    $model = $model->where("{$alisa}{$fields}", $whereData[$fields][0], $whereData[$fields][1]);
                }else{
                    $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
                }

            }


        }
//        if (isset($whereData['status']) && $whereData['status']) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
//        if (isset($whereData['not_status']) && $whereData['not_status']) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);


        if (isset($whereData['keywords'])&&$whereData['keywords']){

            if($with){
                $model = $model->where( function($query) use($whereData,$alisa,$with){
                    $query = $query->where("{$alisa}url|{$alisa}title|{$alisa}content|{$alisa}ip", 'like', "%". $whereData['keywords']."%");
                    if(in_array('user',$with)){
                        $query = $query->whereOr("user.nickname|user.realname|user.mobile", 'like', "%". $whereData['keywords']."%");
                    }
                    if(in_array('shop',$with)){
                        $query = $query->whereOr("shop.name|shop.address|shop.address_detail|shop.tel", 'like', "%". $whereData['keywords']."%");
                    }
                    if(in_array('store',$with)){
                        $query = $query->whereOr("store.username|store.nickname|store.email", 'like', "%". $whereData['keywords']."%");
                    }
                });
            }else{
                $model = $model->where("{$alisa}url|{$alisa}title|{$alisa}content|{$alisa}ip", 'like', "%". $whereData['keywords']."%");
            }

        }
        if (isset($whereData['time'])&&$whereData['time']){
            $model = $model->time(["{$alisa}createtime",$whereData['time']]);
        }


        return $model;
    }




    public static function logList($page, $limit,$params=[]){
        $with_field = [
            'base'=>['*'],
            'user'=>['nickname',"realname","mobile","avatar"],
            'shop'=>['name','address',"address_detail","tel","logo","image"],
            'store'=>['username','nickname',"email","user_id","avatar"],
        ];

        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.id desc,{$alisa}.createtime desc";
        $serch_where = [];
        $serch_where = array_merge($serch_where,$params);
        return (new self)->getBaseList($serch_where, $page, $limit,$sort,$with_field);
    }




    /** 日志详情
     * @param $id
     * @throws \think\exception\DbException
     */
    public static function detail($id){
        $self = self::get($id,['user','shop',"store"]);
        if(!$self) throw new \Exception("未找到相关数据");


        $self->getRelation('user')->visible(['nickname',"realname","mobile","avatar"]);
        $self->getRelation('shop')->visible(['name','address',"address_detail","tel","logo","image"]);
        $self->getRelation('store')->visible(['username','nickname',"email","user_id","avatar"]);
        //参与人数 = 虚拟人数 + 平台人数
        return $self;
    }


}
