<?php
namespace app\wendasns\service;

use app\wendasns\model\UserData as Data;
use app\wendasns\model\UserBehavior as Behavior;
use app\wendasns\model\Credit;
use app\wendasns\model\CreditReward;
use app\wendasns\model\CreditLog;
use wendasns\Wend;
use think\Exception;

class PwCredit
{
	public $uid;
	private $credit;
	private $credit_id;
	protected $data= [];
		
	public function save()
	{
		$dm = Data::where('user_id', $this->uid)->find();
		if(!$dm){
			throw new Exception('用户不存在');
		}
		
		$dm->allowField(['credit1', 'credit2'])->save($this->data);
		return $this;
	}
	
	//获取积分值
	public function getCredit(int $type = 1)
	{
		$dm = Data::where('user_id', $this->uid)->find();
		if($dm){
			$credit_id = 'credit'.$type;
			if($dm->$credit_id){
				return $dm->$credit_id;
			}
		}
		return 0;
	}
	
	//增加积分
	public function setInc(float $value, int $type = 1)
	{
		Data::where('user_id', $this->uid)->inc('credit'.$type, $value)->update();
		$this->credit = $value;
		$this->credit_id = $type;
		return $this;
	}
	
	//减少积分
	public function setDec(float $value, int $type = 1)
	{
		Data::where('user_id', $this->uid)->dec('credit'.$type, $value)->update();
		$this->credit = $value;
		$this->credit_id = $type;
		return $this;
	}
	
	//系统积分策略奖励
	public function setReward(string $action)
	{
		$dm = CreditReward::where('action', $action)->find();
		if(!$dm){
			return false;
		}
		$min_time = strtotime(date('Y-m-d', Wend::getTime()));
		$max_time = $min_time + 86399;
		$sql = [
			['user_id','=',$this->uid],
			['action','=',$action],
			['create_time','>',$min_time],
			['create_time','<',$max_time],
		];
		$number = Behavior::where($sql)->count();
		if($number>=$dm->number){
			return false;
		}
		$this->setInc($dm->credit, 2);
		$this->setLog(2, $dm->credit, $action, $dm->name);
	}
	
	/* 记录积分日志
	 * $reward   积分值
	 * $descrip  描述
	 */
	public function setLog(int $type, float $value, string $action, string $descrip = '')
	{
		//积分日志
    	CreditLog::create([
    		'credit_id' => $type,
    		'credit' => $value,
    		'action' => $action,
    		'descrip' => $descrip,
    		'user_id' => $this->uid,
    		'created_time' => Wend::getTime()
    	]);
	}

	public function log(string $action, string $descrip = '')
	{
		$this->setLog($this->credit_id, $this->credit, $action, $descrip);
	}
	
	//检查积分情况
	public function checkCredit(float $value, int $type = 1)
	{
		$credit = Credit::find($type);
		if(!$credit){
			return new Exception('信用类型不正确');
		}
		$dm = Data::where('user_id', $this->uid)->find();
		$credit_id = 'credit'.$type;
        if($dm->$credit_id < $value){
        	return new Exception("您的{$credit->name}不足");
        }
        
        //检查是否开启付费模式
        if($type==1 && !configure('site.model')){
        	return new Exception('非付费模式');
        }
        
        return true;
	}
}