<?php
!defined('IN_ONEZ') && exit('Access Denied');
#名称：生成平台代理
#标识：build.www

onez('site.www');
class onezphp_build_www extends onezphp_site_www{
  function __construct(){
    //exit('暂停服务');
  }
  function totalprice($item){
    global $G;
    $total=0;
    $html=array();
    if($item['token']=='android'){
      $total+=30;
      $html[]='<strong>安卓客户端(.apk)</strong>x1 = ¥<code class="totalprice">30</code>元';
    }elseif($item['token']=='desktopnw'){
      $total+=30;
      $html[]='<strong>电脑客户端(.apk)</strong>x1 = ¥<code class="totalprice">30</code>元';
    }else{
      $total+=30;
      $html[]='<strong>软件客户端(.exe)</strong>x1 = ¥<code class="totalprice">30</code>元';
    }
    if($item['is_setup']){
      $total+=20;
      $html[]='<strong>安装包</strong>x1 = ¥<code class="totalprice">20</code>元';
    }
    
    $html[]='';
    if($G['userinfo']['nolimit']){
      $html[]='<s>总计支付:¥<code class="totalprice">'.$total.'</code>元</s> <br /><span class="vip">您有无限生成特权，无需支付此费用。</span>';
      $total=0;
    }elseif($G['userinfo']['index1']>0){
      $html[]='<s>总计支付:¥<code class="totalprice">'.$total.'</code>元</s> <br /><span class="vip">您还可以生成'.$G['userinfo']['index1'].'次，本次无需支付此费用。</span>';
      $total=0;
    }else{
      $html[]='总计支付:¥<code class="totalprice">'.$total.'</code>元';
      $html[]='账户金额:¥<code class="totalprice">'.$G['user']['amt'].'</code>元';
    }
    if($total==0 && !$G['userinfo']['nolimit']){
      //if($G['userid']==1){
        $info=parse_url($item['softurl']);
        $host=strtolower($info['host']);
        $history=$G['this']->data()->open('task')->record("extra like '%$host%' and userid<>'$G[userid]' order by id desc");
        if($history){
          #print_r($history);exit();
          if($G['userinfo']['pay_total']*1<=0 && $host!='daping.faiten.cn'){
            #$total=10;
            #$html[]='<span style="background:#FFEDEC;display:inline-block;border:1px solid #d43f3a;padding:3px;margin:5px 0;border-radius:5px">系统提示：域名“<code class="totalprice">'.$host.'</code>”已于<code>'.date('Y-m-d H:i:s',$history[0]['updatetime']).'</code>生成过，再次生成需要额外支付<code class="totalprice">10</code>元。如果域名不是您要生成的，请修改后重新生成。（新域名不受此限制）</span>';
            #$html[]='累计所需费用:¥<code class="totalprice">'.$total.'</code>元';
          }
        }
      //}
    }
    if($total>0){
      $btnname='';
      $btns='';
      $btns.='<button class="btn btn-info" type="button" onclick="_pay_alipay()">支付宝支付</button> ';
      $btns.='<button class="btn btn-success" type="button" onclick="'.onez('wxpay')->set('info',array(
          'plugintoken'=>$G['this']->token,
          'paytype'=>'wxpay',
          'payname'=>'微信支付',
          'itemid'=>$item['id'],
          'userid'=>$G['userid'],
          'type'=>'buy',
          'price'=>$total,
          'goto'=>'http://build.onez.cn/?mod=%2Findex.php&menu=log',
          'subject'=>'客户端生成费用“'.$item['softname'].'”',
          'proxy'=>'http://www.onez.cn',
        ))->click().'">微信支付</button> ';
      if($G['user']['amt']>$total){
        $btns.='<button class="btn btn-warning" type="button" onclick="_pay_account()">余额支付</button> ';
      }else{
        $btns.='<button class="btn btn-warning" type="button" disabled title="账户余额不足" data-toggle="tooltip">余额支付</button> ';
      }
      $btns.='<a class="btn btn-default" href="'.onez()->href('/index.php?menu='.$this->buildname($item)).'">修改资料</a> ';
      $G['footer-js'].=<<<ONEZ
$(function(){
  onez.wxpay.payok=function(){
    location.href='?mod=%2Findex.php&menu=log';
  }
});
ONEZ;
    }
    return array($total,implode("\n",$html),$btns);
  }
  function buildname($item){
    if($item['token']=='android'){
      return 'build.android';
    }elseif($item['token']=='desktopnw'){
      return 'build.desktopnw';
    }else{
      return 'build.desktop';
    }
  }
  function bindwx(){
    $id=(int)onez()->gp('id');
    onez()->location(onez('login.weixin')->mlink($this->token,'http://www.onez.cn',$id));
  }
  function payback($order){
    global $G;
    $G['this']=$this;
    
    
    $postdata=$order['postdata'];
    $order['price']<=1 && exit('非法操作');
    
    $orderno=$order['orderno'];
    $orderno=$order['orderno'];
    if($orderno){
      $T=$G['this']->data()->open('paylog')->one("token='$orderno'");
      if($T){
        return;
      }
      $item=array();
      $item['order']=$order;
      $G['this']->data()->open('paylog')->insert($item);
    }
    
    #支付成功，计算推广分成
    $my=$G['this']->data()->open('userinfo')->one("userid='$postdata[userid]'");
    if($my['upid'] && $my['addtime']>strtotime('-3 months')){
      $up=$G['this']->data()->open('userinfo')->one("userid='$my[upid]'");
      if($up){
        $earn=$order['price']*0.1;
        if($earn>0){
          #上级
          $G['this']->data()->open('money')->insert(array(
            'userid'=>$up['userid'],
            'subject'=>$order['subject'],
            'money1'=>$earn,
            'money2'=>$up['money3'],
            'money3'=>$up['money3']+$earn,
          ));
          $G['this']->data()->open('userinfo')->update(array(
            'money1'=>$up['money1']+$earn,
            'money3'=>$up['money3']+$earn,
          ),"userid='$my[upid]'");
          
          #当前
          $G['this']->data()->open('userinfo')->update(array(
            'totalpay'=>$my['totalpay']+$order['price'],
            'bill'=>$my['bill']+$earn,
          ),"userid='$my[userid]'");
        }
      }
    }
    #支付总额
    $G['this']->data()->open('userinfo')->update(array(
      'pay_total'=>$my['pay_total']+$order['price'],
    ),"userid='$my[userid]'");
    
    if($postdata['type']=='buy'){
      $itemid=(int)$postdata['itemid'];
      if($itemid){
        $item=$G['this']->data()->open('task')->one("id='$itemid'");
        if($item['key1']=='pay'){
          $this->build($item,$postdata['payname']);
        }
      }
    }elseif($postdata['type']=='package'){
      $num=(int)$postdata['num'];
      $this->addnum($postdata['userid'],$num,$postdata['payname']);
    }
    $user=onez('db')->open('member')->one("userid='$my[userid]'");
  }
  function addnum($userid,$num,$payname=''){
    global $G;
    $userinfo=$G['this']->data()->open('userinfo')->one("userid='$userid'");
    if($userinfo){
      $G['this']->data()->open('package')->insert(array(
        'userid'=>$userid,
        'index1'=>$num,//剩余
        'index2'=>$num,//总
        'index3'=>0,//已用
        'index4'=>strtotime('+1 years'),
        'payname'=>$payname,
      ));
      $totalnum=$hasnum=0;
      $nolimit=0;
      $T=$G['this']->data()->open('package')->record("userid='$userid' and index4>=".time()."");
      foreach($T as $rs){
        $hasnum+=$rs['index1'];
        $totalnum+=$rs['index2'];
        if($rs['index2']==-1){
          $nolimit=1;
        }
      }
      $G['this']->data()->open('userinfo')->update(array(
        'index1'=>$hasnum,
        'index2'=>$totalnum,
        'index5'=>time(),
        'nolimit'=>$nolimit,
      ),"userid='$userid'");
    }
  }
  function once($userid){
    global $G;
    $userinfo=$G['this']->data()->open('userinfo')->one("userid='$userid'");
    if($userinfo){
      $T=$G['this']->data()->open('package')->record("userid='$userid' and index4>=".time()." order by index4");
      $ok=0;$nolimit=0;
      foreach($T as $rs){
        if($rs['index2']==-1){//不限
          $nolimit=1;
          $ok=1;
          $G['this']->data()->open('package')->update(array(
            'index3'=>$rs['index3']+1,
            'index5'=>time(),
          ),"id='$rs[id]'");
          break;
        }elseif($rs['index1']>0){//有剩余
          $ok=1;
          $G['this']->data()->open('package')->update(array(
            'index1'=>$rs['index1']-1,
            'index3'=>$rs['index3']+1,
            'index5'=>time(),
          ),"id='$rs[id]'");
          break;
        }
      }
      if($ok){
        $totalnum=$hasnum=0;
        $T=$G['this']->data()->open('package')->record("userid='$userid' and index4>=".time()."");
        foreach($T as $rs){
          $hasnum+=$rs['index1'];
          $totalnum+=$rs['index2'];
        }
        $G['this']->data()->open('userinfo')->update(array(
          'index1'=>$hasnum,
          'index2'=>$totalnum,
          'nolimit'=>$nolimit,
        ),"userid='$userid'");
        return true;
      }
    }
    return false;
  }
  /**
  * 生成客户端
  * @return
  */
  function build($item,$payname){
    global $G;
    onez('debug')->showerror();
    $itemid=(int)$item['id'];
    $G['this']->data()->open('task')->update(array('key1'=>'ing','payname'=>$payname,'key2'=>''),"id='$itemid'");
    $files=array();
    #配置信息
    if($item['token']=='android'){
      $keystore=$G['this']->data()->open('android_keystore')->one("id='$item[keystore_id]'");
      $item['keystore']=array(
        'id'=>$keystore['id'],
        'fileurl'=>$keystore['fileurl'],
        'alias'=>$keystore['alias'],
        'password'=>$keystore['password'],
      );
    }elseif($item['token']=='desktopnw'){
      #图标
      $files['build.icon']=$item['icon'];
    }else{
      #图标
      $files['build.icon']=$item['icon'];
    }
    $files['config.json']=json_encode($item);
    
    
    #配置信息
    //$taskFile=ONEZ_CACHE_PATH.'/plugins/open.build/tasks/'.$itemid.'.zip';
    //onez()->write($taskFile,onez('zip')->zip($files)->data);
    ob_clean();
    $sn=$G['this']->data()->open('sn')->one("index2=0 and index1>".time());
    !$sn && onez()->error('生成码不足，请与系统管理员联系~');
    $data=onez()->post('http://build.onez.cn/?_m=agent_api_build',http_build_query(array(
      'action'=>'build',
      'sn'=>$sn['key1'],
      'token'=>$item['token'],
      'itemid'=>$itemid,
      //'zipurl'=>ONEZ_CACHE_URL.'/plugins/open.build/tasks/'.$itemid.'.zip',
      'base64'=>base64_encode(onez('zip')->zip($files)->data),
    )));
    if(strpos($data,'error ')!==false){
      onez()->error($data);
      exit($data);
    }
    $item=array();
    $item['index2']=time();
    $item['userid']=$G['userid'];
    $item['upid']=$itemid;
    $G['this']->data()->open('sn')->update($item,"id='$sn[id]'");
    
    $G['this']->data()->open('userinfo')->update(array(
      'index6'=>$G['userinfo']['index6']+1,
    ),"userid='$G[userid]'");
  }
  function paytype($key=false){
    $$options=array();
    $options['wxpay']='<label class="label label-xs label-success">微信支付</label>';
    $options['alipay']='<label class="label label-xs label-info">支付宝支付</label>';
    if($key!==false){
      return $options[$key];
    }
    return $options;
  }
  function status($key=false){
    $$options=array();
    $options['new']='新建';
    $options['pay']='等待生成';
    $options['ziping']='正在编译...';
    $options['zip']='编译完成';
    $options['setuping']='正在制作安装包...';
    $options['setup']='制作安装包成功';
    if($key!==false){
      return $options[$key];
    }
    return $options;
  }
  function showstatus($item){
    if($item['key1']=='new'){
      $text='<span style="color:gray">新建</span>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&ac=pay').'" class="btn btn-xs btn-info">
            去生成
          </a>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item)).'" class="btn btn-xs btn-success">
            编辑
          </a>
          <a href="javascript:void(0)" onclick="onez.del('.$item['id'].')" class="btn btn-xs btn-danger">
            删除
          </a>';
    }elseif($item['key1']=='pay'){
      $text='<span style="color:orange">等待生成</span>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&ac=pay').'" class="btn btn-xs btn-info">
            去生成
          </a>';
    }elseif($item['key1']=='ing'){
      $text='<span style="color:orange">正在排队，请耐心等待...</span>';
    }elseif($item['key1']=='ziping'){
      $text='<span style="color:#0099ff">正在编译...</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_zip_begin']).')</span>';
    }elseif($item['key1']=='zip'){
      $text='<span style="color:green">编译完成</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_zip_end']).')</span>';
      $text.=' <a href="'.$item['zipurl'].'">
            下载压缩包
          </a>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&copyid='.$item['id']).'" class="btn btn-xs btn-info">
            再次生成
          </a>';
    }elseif($item['key1']=='apking'){
      $text='<span style="color:#0099ff">正在打包...</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_apk_begin']).')</span>';
    }elseif($item['key1']=='apk'){
      $text='<span style="color:green">编译完成</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_apk_end']).')</span>';
      $text.=' <a href="'.$item['apkurl'].'">
            下载Apk
          </a> 
          <img src="http://cdn.onez.cn/2017/0709/2017070908415742400001.png" onclick="'.onez('qrcode.view')->click($item['apkurl'],'客户端二维码，请勿使用微信扫描').'" height="16px" style="cursor:pointer;position: relative;top: -2px;" />
          ';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&copyid='.$item['id']).'" class="btn btn-xs btn-info">
            再次生成
          </a>';
    }elseif($item['key1']=='setuping'){
      $text='<span style="color:#0099ff">正在制作安装包...</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_setup_begin']).')</span>';
      $text.=' <a href="'.$item['zipurl'].'">
            下载压缩包
          </a>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&copyid='.$item['id']).'" class="btn btn-xs btn-info">
            再次生成
          </a>';
    }elseif($item['key1']=='setup'){
      $text='<span style="color:green">安装包制作完成</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_setup_begin']).')</span>';
      $text.=' <a href="'.$item['zipurl'].'">
            下载压缩包
          </a>';
      $text.=' <a href="'.$item['setupurl'].'">
            下载安装包
          </a>';
      $text.=' <a href="'.onez()->href('/index.php?menu='.$this->buildname($item).'&copyid='.$item['id']).'" class="btn btn-xs btn-info">
            再次生成
          </a>';
    }else{
      $text=$item['key1'];
    }
    if($item['key2']=='error'){
      //$text='<span style="color:#ff0000">'.$item['error'].'</span> <span class="time">('.date('Y-m-d H:i:s',$item['time_error']).')</span>';
    }
    return $text;
  }
  function result(){
    global $G;
    $action=onez()->gp('action');
    $itemid=(int)onez()->gp('itemid');
    $A=array('status'=>'ok');
    if($action=='zip.start'){
      $item=$G['this']->data()->open('task')->one("id='$itemid'");
      $G['this']->data()->open('task')->update(array(
        'key1'=>'ziping',
        'time_zip_begin'=>time(),
      ),"id='$itemid'");
    }elseif($action=='zip'){
      $item=$G['this']->data()->open('task')->one("id='$itemid'");
      $zipurl=onez()->gp('zipurl');
      $G['this']->data()->open('task')->update(array(
        'key1'=>'zip',
        'zip_size'=>onez()->gp('filesize'),
        'zipurl'=>$zipurl,
        'time_zip_end'=>time(),
      ),"id='$itemid'");
      if($item['is_setup']){
        $G['this']->data()->open('task')->update(array(
          'key1'=>'setuping',
          'time_setup_begin'=>time(),
        ),"id='$itemid'");
        $A['setup']=1;
      }
    }elseif($action=='apk.start'){
      $item=$G['this']->data()->open('task')->one("id='$itemid'");
      $G['this']->data()->open('task')->update(array(
        'key1'=>'apking',
        'time_apk_begin'=>time(),
      ),"id='$itemid'");
    }elseif($action=='apk.ok'){
      $item=$G['this']->data()->open('task')->one("id='$itemid'");
      $keystore_url=onez()->gp('keystore_url');
      if($keystore_url){
        $keystore=$G['this']->data()->open('android_keystore')->one("id='$item[keystore_id]'");
        if(!$keystore['fileurl']){
          $G['this']->data()->open('android_keystore')->update(array(
            'fileurl'=>$keystore_url,
          ),"id='$item[keystore_id]'");
        }
      }
      
      $apkurl=onez()->gp('apkurl');
      $G['this']->data()->open('task')->update(array(
        'key1'=>'apk',
        'apk_size'=>onez()->gp('filesize'),
        'apkurl'=>$apkurl,
        'time_apk_end'=>time(),
      ),"id='$itemid'");
    }elseif($action=='setup'){
      $item=$G['this']->data()->open('task')->one("id='$itemid'");
      $setupurl=onez()->gp('setupurl');
      $G['this']->data()->open('task')->update(array(
        'key1'=>'setup',
        'setup_size'=>onez()->gp('filesize'),
        'setupurl'=>$setupurl,
        'time_setup_end'=>time(),
      ),"id='$itemid'");
    }elseif($action=='error'){
      $G['this']->data()->open('task')->update(array(
        'key2'=>'error',
        'error'=>onez()->gp('error'),
        'time_error'=>time(),
      ),"id='$itemid'");
    }
    onez()->output($A);
  }
  function payoff(){
    exit('ok');
  }
  function third_login_callback($type,$thirdinfo,$goto){
    global $G;
    
    //新版
    $T=$G['this']->data()->open('member')->one("key11='$thirdinfo[third_name]' and key12='$thirdinfo[third_token]'");
    if(!$T){
      $onez=array();
      $onez['nickname']=$thirdinfo['nickname'];
      $onez['key8']=$thirdinfo['nickname'];
      $onez['key9']=$onez['ip']=onez()->ip();
      $onez['key10']=$onez['address']=onez('ip')->init($onez['ip'])->address();
      $onez['key2']=uniqid();
      $onez['qq']=$qq;
      $onez['key3']='new';
      $onez['key1']='user';
      $onez['key11']=$thirdinfo['third_name'];
      $onez['key12']=$thirdinfo['third_token'];
      
      $G['this']->data()->open('member')->insert($onez);
      $T=$G['this']->data()->open('member')->one("key11='$thirdinfo[third_name]' and key12='$thirdinfo[third_token]'");
    }
    
    $G['userid']=$T['id'];
    onez('scookie')->call('userid',$G['userid']);
    onez('cache')->cookie($G['this']->cname,"$T[id]\t$T[username]",0);
    $G['this']->avatar_set($G['userid'],$thirdinfo['avatar']);
    
    $goto=onez()->homepage().onez()->gp('goto');
    return $goto;
  }
  function addSn($sn){
    global $G;
    if(!$sn['key1']){
      return;
    }
    $T=$G['this']->data()->open('sn')->one("key1='$sn[key1]'");
    if(!$T){
      return $G['this']->data()->open('sn')->insert($sn);
    }
  }
}