<?php

namespace app\model;
use support\think\Db;

use traits\model\SoftDelete;

class Archives extends Base
{

    //use SoftDelete;// 表名
    
    protected function getOptions(): array{
        return array_merge(parent::getOptions(),[
            'append'    =>    [
                'status_text'
            ],
        ]);
    }
    public static function onAfterInsert(Archives $row)
    {
        \support\Log::error(''. json_encode($row));
        $pk = $row->getPk();
        self::where($pk, $row->$pk)->update(['weigh' => $row[$pk]]);
        $changedData = $row->getData();
        if (isset($changedData['content'])) {
            //在更新成功后刷新副表
            $values = array_intersect_key($changedData, array_flip(['content']));
            $values['id'] = $row['id'];
            //更新副表
            Db::name('content')->insert($values, true);
        }
    }
    public static function onAfterUpdate($row)
    {
        \support\Log::info('onAfterUpdate'.$row->id. json_encode($row->getChangedData()));
        $changedData = $row->getChangedData();
        if (isset($changedData['content'])) {
            //在更新成功后刷新副表
            $values = array_intersect_key($row->getData(), array_flip(['content']));
            //更新副表
            Db::name('content')->where('id',$row->id)->update($values);
        }
    }
    public static function onAfterDelete($row)
    {
        Db::name('content')->where('id',$row->id)->delete();
    }
    /**
     * 批量设置数据
     * @param $data
     * @return $this
     */
    public function setAddonData(string|array|object $data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }
        foreach($data as $k=>$v){
            $this->$k=$v;
        }
        return $this;
    }
    
    public function getStatusList()
    {
        return ['1' => '正常', '0' => '隐藏'];
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getCategoryOptions($type='default'){
        return Category::where('status','1')->where('type',$type)->column('id,title');
    }
    
    function setCreatedAtAttr($v){
        if($v && strpos($v,'-')){
            return strtotime($v);
        }
        return $v;
    }
    function setUpdatedAtAttr($v){
        if($v && strpos($v,'-')){
            return strtotime($v);
        }
        return $v;
    }


    public function getFlagList()
    {
        return Config('site.flagtype');
    }

    public function content()
    {
        return $this->hasOne('content', 'id', 'id');
        //    ->bind(['content']);//->setEagerlyType(0);
    }
    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id');//->setEagerlyType(0);
    }
}
