<?php



namespace app\common\dao\user;

use app\common\dao\BaseDao;
use app\common\model\user\UserHistory;

class UserHistoryDao extends BaseDao
{
    protected function getModel(): string
    {
        return UserHistory::class;
    }


    public function createOrUpdate(array $data)
    {
        $ret = $this->getModel()::getDB()->where($data)->find();
        if($ret){
            $ret->update_time = time();
            $ret->save();
        }else{
            $data['update_time'] = time();
            $this->create($data);
        }
    }

    public function search(?int $uid, int $type)
    {
        $query = ($this->getModel()::getDB())->when($uid, function ($query) use ($uid) {
            $query->where('uid', $uid);
        })->when($type, function ($query) use ($type) {
            $query->where('res_type', $type);
        });

        return $query->order('update_time DESC');
    }


    public function deleteBatch($uid,$data)
    {
        if(is_array($data)){
            $this->getModel()::getDB()->where($this->getPk(),'in',$data)->delete();
        }else if($data == 1){
            $this->getModel()::getDB()->where('uid',$uid)->delete();
        }
    }

    public function userTotalHistory($uid)
    {
        return $this->getModel()::getDB()->where('uid',$uid)->count();
    }

}
