<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;



class Incentivead extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }

        if(!in_array('incentivead',$base['pay_plugin'])){
            return []; 
        }
        
        return $base['incentivead'];
    }


    public static function setReward($user_id){
        $config = self::getSet();
        if(empty($config) ||$config['status']!=1){
            return __json(0,"未开启激励广告");
        }

        $reward_score = max(0,$config['reward_score']);
        $view_count = max(0,$config['view_count']);
        if($reward_score <= 0){
            return __json(0,"未设置激励积分");
        }

        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        if($view_count > 0){
            $count = Db::name("bbfx_incentivead_view_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->count();
            if($count >= $view_count){
                return __json(0,"每天最多观看激励视频{$view_count}次");
            }
        }

        try{
            Db::startTrans();
            $log = [
                "uniacid"=>UNIACID,
                "user_id"=>$user_id,
                "type"=>0,
                "money"=>$reward_score,
                "createtime"=>time(),
            ];
            $log_id = Db::name("bbfx_incentivead_view_log")->insertGetId($log);
            $log['id'] = $log_id;
            User::setUserMoney($user['id'],$reward_score,2,64,"激励广告奖励",$log);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }
        return __json(1,"操作成功");
    }

    public static function getViewLogList($where,$page=1,$limit=10){
        $list = Db::name("bbfx_incentivead_view_log")->alias("a")->join("bbfx_user b","a.user_id=b.id")->field("a.*,b.nickname,b.avatar")->where($where)->order("id desc")->limit(($page-1)*$limit,$limit)->select();
        $total = 0;
        if(!empty($list)){
            $total = Db::name("bbfx_incentivead_view_log")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->count();
            foreach($list as $key=>&$val){
                $val['avatar'] = cdnurl($val['avatar']);
                $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            }
            unset($val);
        }
        return __json(1,"操作成功",["list"=>$list,"total"=>$total]);
    }
}