<?php

namespace support;

use support\Db;

class ApiTask
{
    private $table = 'api_task';
    private $key;
    public function __construct(string $key)
    {
        $this->key = $key;
    }
    
    /**
     * 取数据
     */
    public function get()
    {
        return Db::table($this->table)->where('key',$this->key)->first();
    }
    
    /**
     * 错误信息
     */
    public function error(string $err)
    {
        Db::table($this->table)
            ->where('key',$this->key)
            ->update(['error' => $err]);
    }
    
    /**
     * 任务开始
     */
    public function Begin(string $time='')
    {
        if(empty($time)) $time = getNowTime();
        Db::table($this->table)
            ->where('key',$this->key)
            ->update(['access_time' => $time,'complete_status' => 0,'complete_time' => null,'error' => null]);
    }
    
    /**
     * 任务完成
     */
    public function meta(string|array $data)
    {
        $row = Db::table($this->table)
        		->where('key',$this->key)
        		->first();
        if(empty($row->meta) || is_string($data)){
            if(!is_string($data)) 
                $data = json_encode($data,JSON_UNESCAPED_UNICODE);
    		Db::table($this->table)
    		    ->where('key',$this->key)
    		    ->update(['meta'=>$data]);
        }else{
            $item = [];
            foreach($data as $k => $v){
                $item['meta->'.$k] = $v;
            }
            Db::table($this->table)
            ->where('key',$this->key)
            ->update($item);
        }
    }
    
    /**
     * 任务完成
     */
    public function complete(string $time='')
    {
        if(empty($time)) $time = getNowTime();
		Db::table('api_task')
		    ->where('key',$this->key)
		    ->update(['complete_status' => 1,'complete_time' => $time]);
    }
}