<?php

namespace app\admin\model;

use app\common\model\Counter;
use think\Model;
use think\Session;

class Archives extends Model
{
    // 表名
    protected $name = 'archives';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'views',
    ];


    /**
     * 根据后台入口和管理员等级来自动读取
     * 1, 如果是从站点后台登录，所有管理员只能读取本站点信息
     * 2, 如果是从总后台登录，管理员读取属于自己的站点的信息，超级管理员无限制
     */
    protected function base($query)
    {
        if (Session::has("user_site_id")) {
            $query->where('site_id', Session::get("user_site_id"));
        }
        //$query->alias('a')->join('counter c', 'c.item_id=a.id')->where('c.item_type','archive')->field('c.views, c.good, c.bad, c.comments');
    }

    public function Sites()
    {
        return $this->belongsTo('Sites', 'site_id')->field('id,name,domain');
    }
    public function Channel()
    {
        return $this->belongsTo('Channel', 'channel_id')->field('id,name');
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])
                ->update(['weigh' => $row[$pk]]);
        });

        self::beforeDelete(function($row){
            if (intval($row->isDelete)==0) {
                $row->isDelete = time();
                $row->save();
                return false;
            }
        });
    }

    public function restore()
    {
        return $this->update(['isDelete'=>0]);
    }

    public function getViewsAttr($value,$data)
    {
        if(!isset($data['id'])) return 0;
        $result = Counter::get(['item_id'=>$data['id']]);
        return $result?$result['views']:0;
    }

}
