<?php

namespace app\admin\model\teacher;
use app\admin\library\Auth;
use app\admin\model\department\Department;
use think\Exception;
use think\Model;
use think\Db;
use traits\model\SoftDelete;


class Task extends Model
{

    use SoftDelete;

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

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

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

    protected static function init()
    {
        $auth = Auth::instance();
        self::beforeUpdate(function ($row) {
            if(!empty($row['createtime'])){
                $pk = $row->getPk();
                $create_time = date('Y-m-d H:i:s',$row['createtime']);
                $update_time = date('Y-m-d H:i:s',$row['updatetime']);
                $row->getQuery()->where($pk, $row[$pk])->update(['create_time' => $create_time,'update_time'=>$update_time]);
            }
        });
        self::afterInsert(function ($row) {
            if(!empty($row['createtime'])){
                $pk = $row->getPk();
                $create_time = date('Y-m-d H:i:s',$row['createtime']);
                $update_time = date('Y-m-d H:i:s',$row['updatetime']);
                $row->getQuery()->where($pk, $row[$pk])->update(['create_time' => $create_time,'update_time'=>$update_time]);
            }
        });
    }

    public function getXianxiangCountAttr($value, $data)
    {
        $faultid = Db::name('task_fault')->where('task_id',$data['task_id'])->column('fault_id');
        $faultpid = Db::name('fault')->where('fault_id','in',$faultid)->where('sim_type',$data['sim_type'])->column('parent_fault_id');
        return Db::name('fault')->where('fault_id','in',$faultpid)->where('sim_type',$data['sim_type'])->count();
    }

    public function getBuweiCountAttr($value, $data){
        return Db::name('task_fault')->where('task_id',$data['task_id'])->count();
    }







}
