<?php
namespace app\shared\logic\user;
use app\shared\model\Bill;
use app\shared\model\ShareOrder;
use app\shared\model\User;
use app\shared\model\HouseOrder;
use app\shared\model\GoodsOrder;
use app\shared\model\App;
use app\shared\model\Option;
use app\shared\model\Withdraw;
use think\facade\Cache;
use think\facade\Db;
use think\Validate;
class ShareForm extends UserForm
{
    //首页数据
    public function index(){
        $this->user=User::find($this->user_id);
        $info['wd_success']=Withdraw::where(['asset_type'=>1,'user_id'=>$this->user_id,'status'=>1])->sum('money');
        $info['can_wd']=$this->user->price;
        $info['stay_price']=ShareOrder::where(['user_id'=>$this->user_id,'user_type'=>ShareOrder::USER_TYPE_USER,'status'=>1,'is_delete'=>0])->sum('price'); //待入账佣金
        $info['app_share_rule']=Option::get_data($this->acid,'platform','app_share_rule');
        return fetchJson($info);
    }

	//推荐列表
	public function list(){
		$page=input('page');
		$status=input('status');
		$query=MoneyLog::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'account_type'=>1,'status'=>1]);
		$money=0;
		if($page==1){
			if($status==1){
				$query=$query->whereTime('create_time', 'month');
				$money=MoneyLog::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'account_type'=>1,'status'=>1])->whereTime('create_time', 'month')->sum('price');
				$data='本月日佣金收益(元)';
			}else if($status==2){
				$query=$query->whereTime('create_time', 'last month');
				$money=MoneyLog::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'account_type'=>1,'status'=>1])->whereTime('create_time', 'last month')->sum('price');
				$data='上月佣金收益(元)';
			}else{
				$money=MoneyLog::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'account_type'=>1,'status'=>1])->whereTime('create_time', 'today')->sum('price');
				$data='今日佣金收益(元)';
			}
		}else{
			$data=-1;
			if($status==1){
				$query=$query->whereTime('create_time', 'last month');
			}else if($status==2){
				$query=$query->whereTime('create_time', 'month');
			}
		}
		$list=$query->limit(10)->page($page)->field('acid,type,status,update_time,user_id',1)->select();
		foreach ($list as $key => &$value) {
			$user=User::where('id',$value['form_user_id'])->field('nickname,avatar_url')->find();
			$value['nickname']=$user->nickname;
			$value['avatar_url']=$user->avatar_url;
		}
		return fetchJson([
			'data'=>[
				'money'=>$money,
				'data'=>$data
			],
			'list'=>$list
		]);
	}
	//推荐团队
	public function team(){
		$level=input('level');
		if($level==0){
            $level=2;
		    $is_all=1;
        }else{
		    $is_all=0;
        }
		$list=User::childAll($this->user_id,$level,'id,nickname,avatar_url,create_time',$this->page,$is_all);
		foreach ($list as &$value) {
			$value['create_time']=date('Y-m-d',$value['create_time']);
            $value['share_count']=ShareOrder::where(['form_user_id'=>$value['id'],'user_type'=>ShareOrder::USER_TYPE_USER])->count();
            $value['share_price']=ShareOrder::where(['form_user_id'=>$value['id'],'user_type'=>ShareOrder::USER_TYPE_USER])->sum('price');
		}
		return fetchJson([
			'list'=>$list
		]);
	}
    //佣金列表
    public function commission_list(){
        $query=Bill::where([
            'acid'=>$this->acid,
            'type'=>[Bill::TYPE_SHARE,Bill::TYPE_WITHDRAW],//分销、提现
            'account_type'=>Bill::ACCOUNT_TYPE_USER,//用户
            'form_id'=>$this->user_id,
        ]);

        $status=input('status');
        if($status==1){
            $money=Bill::where([
                        'acid'=>$this->acid,
                        'type'=>Bill::TYPE_SHARE,//分销
                        'account_type'=>Bill::ACCOUNT_TYPE_USER,//用户
                        'form_id'=>$this->user_id,
                        'status'=>1
                    ])
                    ->whereMonth('create_time')
                    ->sum('price');
            $data=[
                'money'=>$money,
                'data'=>'本月'
            ];
            $query->whereMonth('create_time');
        }else if($status==2){
            $money=Bill::where([
                        'acid'=>$this->acid,
                        'type'=>Bill::TYPE_SHARE,//分销
                        'account_type'=>Bill::ACCOUNT_TYPE_USER,//用户
                        'form_id'=>$this->user_id,
                        'status'=>1
                    ])
                    ->whereMonth('create_time','last month')
                    ->sum('price');
            $data=[
                'money'=>$money,
                'data'=>'上月'
            ];
            $query->whereMonth('create_time','last month');
        }else{
            $money=Bill::where([
                        'acid'=>$this->acid,
                        'type'=>Bill::TYPE_SHARE,//分销
                        'account_type'=>Bill::ACCOUNT_TYPE_USER,//用户
                        'form_id'=>$this->user_id,
                        'status'=>1
                    ])->sum('price');
            $data=[
                'money'=>$money,
                'data'=>'全部'
            ];
        }
        $list=$query->page($this->page)
        ->limit($this->limit)
        ->field('id,price,des,type,status,create_time')
        ->order('id desc')
        ->select();
        return fetchJson([
            'data'=>$data,
            'list'=>$list
        ]);
    }
    //分销订单
    public function order(){
	    $today=input('today');
        $condition=[
            [ 'so.acid','=',$this->acid],
            [ 'so.user_id','=',$this->user_id],
            [ 'so.status','>=',0],
            [ 'so.is_delete','=',0],
        ];
        $list=ShareOrder::alias('so')
            ->where($condition)
            ->leftJoin([User::getTable() => 'u'], 'so.form_user_id=u.id')
            ->when($today,function ($query){
                $query->whereTime('so.create_time', 'today');
            })
            ->page($this->page)
            ->limit($this->limit)
            ->field('u.nickname,u.avatar_url,so.id,so.price,so.create_time,so.status,so.type,so.order_id')
            ->order('so.id DESC')
            ->select()->toArray();
        foreach ($list as $key => &$value) {
        	$value['status_title']=$value['status']==1?'待入账':$value['status']==2?'已入账':'已取消';
            if($value['type']==1){
                $value['order_price']=HouseOrder::where('id',$value['order_id'])->value('pay_price');
            }else{

                $value['order_price']=GoodsOrder::where('id',$value['order_id'])->value('pay_price');
            }
            
        }
        return fetchJson($list);
    }

	//微信分享二维码
	public function qrcode(){

		$acid=App::where(['id'=>$this->acid])->find();
        $param= [
            'path' => 'pages/index/index?parent_id='.$this->user_id,
        ];
        $res['user']=$this->user->hidden(['password','access_token','wxapp_open_id','wx_open_id','wx_app_openid']);
        if($this->platform=='ttapp'){
        	$res['qrcode_url']=self::getTtQcode($param,'user_ref',$this->user_id);
        }else{
        	$res['qrcode_url']=self::getQcode($acid,$param,'user_ref',$this->user_id);
        }
        $res['share_bgurl']=Option::get_data($this->acid,'platform','app_share_bg');
        $res['qrcode_dec']='扫一扫邀请的二维码，邀请会员';
        return fetchJson($res);
	}
	//二维码
	public function qrcodeUrl(){
		$acid=App::where(['id'=>$this->acid])->find();
		$id=input('id');
        //方形
        $type=input('type');
        if($type==1){
        	$param= [
	            'path' => 'shared/detail/index?store_id='.$id,
	        ];
        }else{
        	$param= [
	            'path' => 'shared/detail/index?store_id='.$id,
	        ];
        }
        if($this->platform=='ttapp'){
        	$res['qrcode_url']=self::getTtQcode($param,'store_ref',$this->user_id);
        }else{
        	$res['qrcode_url']=self::getQcode($acid,$param,'store_ref',$this->user_id);
        }
        return fetchJson($res);
	}
    //分销规则
    public function getShareRule(){
        return fetchJson(Option::get_data($this->acid,'platform','app_share_rule'));
    }
	//注意：提交格式为json
	protected function curlPost($url,$data) {
	  $curl = curl_init();
	  curl_setopt($curl, CURLOPT_URL, $url);
	  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	  if (!empty($data)) {
	    curl_setopt($curl, CURLOPT_POST, 1);
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    curl_setopt($curl, CURLOPT_HTTPHEADER,
	    array('Content-Type: application/json','Content-Length: ' . strlen($data)));
	  }
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
	  $output = curl_exec($curl);
	  curl_close($curl);
	  return $output;
	}
	public function getTtQcode($param=[],$type="user",$user_id=0){
		 $ttapp=Option::get_data($this->acid,'platform','ttapp_config');
     	 $ttapp=json_decode($ttapp);
	 	 $appid=isset($ttapp->appid)?$ttapp->appid:'';
	 	 $appsecret=isset($ttapp->app_secret)?$ttapp->app_secret:'';

         $saveRoot = public_path();
         $saveDir="qrcode/{$this->acid}/{$type}/";
         if (!is_dir($saveRoot . $saveDir)) {
            @mkdir($saveRoot . $saveDir, 0755, true);
            file_put_contents($saveRoot . $saveDir . '.gitignore', "*\r\n!.gitignore");
         }
         $saveName = $user_id.'_tt'.md5('ttapp'.$user_id).'.png';
         $base_file = request()->baseFile();
         $base_dir  = substr($base_file, 0, strripos($base_file, '/') + 1);
         if(Cache::get('user_share_qrcode'.$this->user_id)){
         	 return request()->domain().$base_dir.$saveDir.$saveName;
         }
         $token=self::getToken($appid,$appsecret);
		 $url = "https://developer.toutiao.com/api/apps/qrcode";
		 $send=[
		   'access_token' => $token,
		   'appname'=>'toutiao',
		   'path'=>urlencode('pages/index/index?user_parent_id='.$this->user_id),
		 ];
		 $send = json_encode($send);
		 $data = $this->curlPost($url,$send);
        //保存到本地
		 Cache::get('user_share_qrcode'.$this->user_id,1,20);
         file_put_contents($saveRoot.$saveDir.$saveName, $data);
         return request()->domain().$base_dir.$saveDir.$saveName;
	}
	 //微信小程序获取二维码
    public function getQcode($acid=[],$param=[],$type='user',$user_id=0){
        //保存到本地
        $saveRoot = public_path();
        $saveDir="qrcode/{$this->acid}/{$type}/";
        if (!is_dir($saveRoot . $saveDir)) {
            @mkdir($saveRoot . $saveDir, 0755, true);
            file_put_contents($saveRoot . $saveDir . '.gitignore', "*\r\n!.gitignore");
        }
        $saveName = $user_id.'_'.md5($user_id).'.png';
        $base_file = request()->baseFile();
        $base_dir  = substr($base_file, 0, strripos($base_file, '/') + 1);

        if(Cache::get('user_share_qrcode'.$this->user_id)){
         	 return request()->domain().$base_dir.$saveDir.$saveName;
        }
        $token=self::getToken($acid['wxapp_app_id'],$acid['wxapp_app_secret']);
        if(isset($param['path'])){
        	//$url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$token}";//方形
        	$url="https://api.weixin.qq.com/wxa/getwxacode?access_token={$token}";//方形
        }else{
        	$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";//圆形
        }
        $params = json_encode($param, JSON_UNESCAPED_UNICODE);
        $data=httpRequest($url,'POST',$params);
        file_put_contents($saveRoot.$saveDir.$saveName, $data);
        Cache::get('user_share_qrcode'.$this->user_id,1,20);
        return request()->domain().$base_dir.$saveDir.$saveName;
    }
    //获取令牌
    private function getToken($appid,$secret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        if($this->platform=="ttapp"){
        	$url="https://developer.toutiao.com/api/apps/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        }
        $data=httpRequest($url);
        $data=json_decode($data);
        if(isset($data->access_token)){
            return ($data->access_token);
        }else{
            die(json_encode(['code'=>-1,'data'=>'','msg'=>'access_token获取错误请检查微信参数是否错误']));
        }
    }

}