<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model\users;

use think\Model;
use think\facade\Db;
use app\common\service\Users as UsersService;

/**
 * @package app\common\model\users
 * @class UsersVisit
 * @author xzncit 2024-03-04
 */
class UsersVisit extends Model {

    protected $name = "users_visit";

    /**
     * 记录会员浏览记录
     * @param $category 活动商品(0:普通商品 1:拼团活动 2:限时秒杀 3:砍价活动 4:限时折扣 5:限购活动 6:积分商品)
     * @param $goods_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function history($category,$goods_id,$activity_id=0){
        $user_id = UsersService::auth("id");
        if(empty($user_id)){
            return false;
        }

        $condition = [];
        $condition[] = ["category","=",$category];
        $condition[] = ["goods_id","=",$goods_id];
        $condition[] = ["activity_id","=",$activity_id];
        $condition[] = ["user_id","=",$user_id];
        $visit = self::where($condition)->find();
        if(!empty($visit)){
            $visit->save([ "count"=>Db::raw("count+1"), "create_time"=>time() ]);
            return true;
        }

        self::create([
            "category"    => $category,
            "goods_id"    => $goods_id,
            "activity_id" => $activity_id,
            "user_id"     => $user_id,
            "create_time" => time()
        ]);
        return true;
    }

}