<?php

namespace app\admin\model\jdgw;

use think\Model;
use traits\model\SoftDelete;

class Article extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'jdgw_article';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

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

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $nav = db('jdgw_nav')->where('id', $row['nav_id'])->find();

            $tpl = "";
            switch($nav['typedata']){
                case 'article';
                    $tpl = "article_article";
                    break;
                case 'images';
                    $tpl = "article_images";
                    break;
                default :
                    $tpl = "article_article";
                    break;
            }

            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk], 'typedata'=>$nav['typedata'], 'tpl'=>$tpl]);
        });

        self::afterUpdate(function ($row) {
            $pk = $row->getPk();
            $changedData = $row->getChangedData();
            if (isset($changedData['nav_id'])) {
                $nav = db('jdgw_nav')->where('id', $row['nav_id'])->find();
                $tpl = "";
                switch($nav['typedata']){
                    case 'article';
                        $tpl = "article_article";
                        break;
                    case 'images';
                        $tpl = "article_images";
                        break;
                    default :
                        $tpl = "article_article";
                        break;
                }
                $row->getQuery()->where($pk, $row[$pk])->update(['typedata'=>$nav['typedata'], 'tpl'=>$tpl]);
            }
        });
    }

    
    public function getTypedataList()
    {
        return ['article' => __('Typedata article'), 'images' => __('Typedata images')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getTypedataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['typedata']) ? $data['typedata'] : '');
        $list = $this->getTypedataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function nav()
    {
        return $this->belongsTo('\app\admin\model\jdgw\Nav', 'nav_id')->setEagerlyType(0);
    }




}
