<?php
namespace app\common\Model;
use think\Model;

class Userpay extends Model{
	protected $dateFormat = 'Y/m/d H:i:s';
	protected $type = [
		'addtime'  =>  'timestamp',
		'img'  =>  'array',
    ];
	protected $insert = ['addtime'];
	
	protected function setAddtimeAttr()
    {
        return time();
    }
	
	public function getAll($t=true){
		$data=input();
		$psize=$data['limit'];
		$page=$data['page'];
		if(isset($data['name'])){
			if(empty($data['name'])){
				$map['id']=['gt',0];
			}else{
			  $map['user|id|photo|email']=$data['name'];
			}
		}else{
			$map['id']=['gt',0];
		}
		if($t){
			$map['isxt']=1;
		}else{
			$map['isxt']=0;
		}
		$ok=$this::with('profile')->where($map)->order("id desc")->paginate(array('list_rows'=>$psize,'page'=>$page))->each(function($item, $key){
			$sm=0;
			if(!empty($item->profile['count'])){
				foreach($item->profile['count'] as $v){
					$sm+=count($v);
				}
			}
			$item->cnum=$sm;
			
		})->toArray();
		
		return $ok;
	}
	
	public function profile()
    {
        return $this->hasOne('Ewm','id','bid')->bind(['count','sid'=>'id']);
    }
	
	/*
	前台
	*/
	public function getList(){
		$data=input();
		$psize=$data['length'];
		$page=$data['start']/$data['length']+1;
		$map['uid']=session('user_id');
		$map['isxt']=['eq',0];
		$des=$data['order'][0]['dir'];
		$str=$data['columns'][$data['order'][0]['column']]['data']." ".$des;
		$res=[];
		$ok=$this->where($map)->order($str)->paginate(array('list_rows'=>$psize,'page'=>$page))->toArray();	
		return $ok;
	}
	
	//返回二维码
	public function generate($money,$type,$uid=0){
		if($money>0){
			if($uid!=0){
				$map['uid']=$uid;
				$map['isxt']=0;
			}else{
				$map['isxt']=1;
			}
			$map['state']=1;
			$map['status']=0;
			$map['type']=$type;
			$count=$this->field('id')->where($map)->select();
			if($count){
				$son=collection($count)->toArray();
				$rand=array_rand($son,1);
				$id=$son[$rand]['id'];
				$list=$this::with('profile')->where(['id'=>$id])->find();
				$e=explode(".",$money);
				$arr=$list['count'];
				if(!isset($e[1]))$e[1]='00';
				$url=!isset($arr[$e[0]][$e[1]])?isset($arr[0][0])?$arr[0][0]:false:$arr[$e[0]][$e[1]];
				if($url){
					return ['id'=>$id,'url'=>$url];
				}else{
				   return false;
				}
			}else{
				return false;
			}
		}
	}
}