<?php


namespace Home\Controller;

use Base\Model\PromoteModel;
use Base\Service\PromoteService;
use OSS\Core\OssException;


class TestResourceController extends BaseController
{
  public function test(){
      echo  'test1';
  }

  public function supportNumberList($p = 1) {
      $page = intval($p);
      $page = $page ? $page : 1; //默认显示第一页数据
      $row=10;
      if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}

      $map = [];
      if(!empty(I('server_name'))){
          $map['tab_test_resource.server_name']=I('server_name');
      }
      if(!empty(I('game_name'))){
          $map['tab_test_resource.game_name']=I('game_name');
      }
      if(!empty(I('role_name'))){
          $map['tab_test_resource.role_name']=['like','%'.I('role_name').'%'];
      }
      if(!empty(I('user_account'))){
          $map['tab_test_resource.user_account']=['like','%'.I('user_account').'%'];
      }
      if(!empty(I('promote_id'))){
          $map['tab_test_resource.promote_id']=I('promote_id');
      }

      $map['tab_test_resource.promote_id']=session("promote_auth.pid");
      $data = M('test_resource','tab_')
          ->field('tab_test_resource.id,tab_test_resource.user_id,tab_test_resource.game_name,tab_test_resource.server_name,tab_test_resource.user_account,tab_test_resource.promote_account,tab_test_resource.role_name,tab_test_resource.create_time,device_number,lock_status as check_status')
          ->join('left join tab_user as user on tab_test_resource.user_id = user.id')
          ->where($map)
          ->page($page,$row)
          ->order('tab_test_resource.create_time DESC')
          ->select();

      foreach ($data as $key => $value) {
          $data[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
      }

      $count = M('test_resource','tab_')
          ->field('tab_test_resource.game_name,tab_test_resource.server_name,tab_test_resource.user_account,tab_test_resource.promote_account,tab_test_resource.role_name,tab_test_resource.create_time,device_number,check_status')
          ->join('left join tab_user as user on tab_test_resource.user_id = user.id')
          ->where($map)
          ->select();
      $count = count($count);

      $page = set_pagination($count,$row);
      if($page) {$this->assign('_page', $page);}
      $this->meta_title = '扶持号管理';
      $this->assign('data',$data);

      $this->display();

  }

  public function freezeSupport() {
      $supportId = I('support_id', 0);
      if ($supportId == 0) {
          $this->ajaxReturn(['status'=>0,'msg'=>"参数错误"]);
      }

      $data = [
          'lock_status' => 0
      ];

      $isFreeze = M('user','tab_')->where("id=".$supportId)->save($data);

      if ($isFreeze) {
          $this->ajaxReturn(['status'=>1, 'msg'=> '冻结成功']);
      } else {
          $this->ajaxReturn(['status'=>0, 'msg'=> '冻结失败']);
      }
  }

    public function unfreezeSupport() {
        $supportId = I('support_id', 0);
        if ($supportId == 0) {
            $this->ajaxReturn(['status'=>0,'msg'=>"参数错误"]);
        }

        $data = [
            'lock_status' => 1
        ];

        $isFreeze = M('user','tab_')->where("id=".$supportId)->save($data);

        if ($isFreeze) {
            $this->ajaxReturn(['status'=>1, 'msg'=> '启用成功']);
        } else {
            $this->ajaxReturn(['status'=>0, 'msg'=> '启用失败']);
        }
    }

    public function rechangePassward() {
        $supportId = I('support_id', 0);
        if ($supportId == 0) {
            $this->ajaxReturn(['status'=>0,'msg'=>"参数错误"]);
        }

        $password = $this->getRandomPassword(6);
        $data = [
            'password' => md5(sha1($password) . UC_AUTH_KEY)
        ];

        $passward = M('user','tab_')->where("id=".$supportId)->save($data);
        if ($passward) {
            $this->ajaxReturn(['status'=>1, 'msg'=> '新密码:'.$password]);
        } else {
            $this->ajaxReturn(['status'=>0, 'msg'=> '重置密码失败']);
        }
    }

    private function getRandomPassword($length, $special = true){
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
            'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2',
            '3', '4', '5', '6', '7', '8', '9'
        );

//        if($special){
//            $chars = array_merge($chars, array(
//                '!', '@', '#', '$', '?', '|', '{', '/', ':', ';',
//                '%', '^', '&', '*', '(', ')', '-', '_', '[', ']',
//                '}', '<', '>', '~', '+', '=', ',', '.'
//            ));
//        }

        $charsLen = count($chars) - 1;
        shuffle($chars);

        $password = '';
        for($i=0; $i<$length; $i++){
            $password .= $chars[mt_rand(0, $charsLen)];
        }
        return $password;
    }

    public function protectLogList($p = 1) {
        $promote_id = get_pid();
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row=10;
        if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}

        $map = [];
        if(!empty(I('server_name'))){
            $map['server_name']=I('server_name');
        }
        if(!empty(I('game_name'))){
            $map['game_name']=I('game_name');
        }
        if(!empty(I('nickname'))){
            $map['nickname']=['like','%'.I('nickname').'%'];
        }
        if(!empty(I('user_account'))){
            $map['user_account']=I('user_account');
        }
        if(!empty($_REQUEST['start'])&&empty($_REQUEST['end'])){
            $map['create_time']  =  array('GT',strtotime($_REQUEST['start']));
            unset($_REQUEST['start']);
        }
        if(empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('LT',strtotime($_REQUEST['end'])+24*60*60-1);
            unset($_REQUEST['end']);
        }
        if(!empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }
        if(!empty(I('types'))){
            $map['type']=I('types');
        }
        $map['promote_id']=$promote_id;

        $field = 'id,game_name,server_name,user_account,nickname,promote_account,detail';
        $order = 'id DESC';

        $data = D('protect_log')->getProtectLog($field,$map,'',$order,$page,$row);

        $count = D('protect_log')->getProtectLog($field,$map,'',$order);

        M('protect_log_read', 'tab_')->startTrans();  //事物
        try {

            $arrUserId = array_column($data,'id');
            $logId = implode(',',$arrUserId);

            if ($logId) {
                $logRead = M('protect_log_read','tab_')
                    ->where("log_id IN({$logId}) and promote_id = {$promote_id}")
                    ->select();
            }
            else {
                $logRead = [];
            }

            $upsetData = array_column($logRead,'log_id');

            $addData = [];
            $k = 0;
            foreach($arrUserId as $key => $value) {
                if (in_array($value,$upsetData)) {
                    continue;
                } else {
                    $addData[$k]['log_id'] = $value;
                    $addData[$k]['promote_id'] = $promote_id;
                    $addData[$k]['create_time'] = time();
                    $k++;
                }
            }

            M('protect_log_read','tab_')->addAll($addData);

        } catch (OssException $e) {
            M('protect_log_read', 'tab_')->rollback();//回滚
        }
        M('protect_log_read', 'tab_')->commit();    //提交事物

        $count = count($count);
        $page = set_pagination($count,$row);
        $this->meta_title = '日志管理';
        if($page) {$this->assign('_page', $page);}

        $this->assign('data',$data);

        $this->display();
    }

    protected function _initialize()
    {
        parent::_initialize();
        $map['id'] = get_pid();
        $pro = M("promote", "tab_")->where($map)->find();
        if ($pro['parent_id']!=0&&!($pro['parent_id']>0&&$pro['grand_id']==0)) {
            $this->error('无权操作!');
        }
    }

    public function index($p=0)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row=10;
        if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
        $map =array();
        if(!empty(I('role_name'))){
            $map['role_name']=['like','%'.I('role_name').'%'];
        }
        if(!empty(I('server_name'))){
            $map['server_name']=I('server_name');
        }
        if(!empty(I('game_name'))){
            $map['game_name']=I('game_name');
        }
        if(!empty(I('user_account'))){
            $map['user_account']=['like','%'.I('user_account').'%'];
        }
        if(!empty($_REQUEST['start'])&&empty($_REQUEST['end'])){
            $map['create_time']  =  array('GT',strtotime($_REQUEST['start']));
            unset($_REQUEST['start']);
        }
        if(empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('LT',strtotime($_REQUEST['end'])+24*60*60-1);
            unset($_REQUEST['end']);
        }
        if(!empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }

        $map['test.promote_id'] = get_pid();

        //
        $res = D("test_resource")->getResourceCout($map,$page,$row);
        // dump($res);
        $parameter =I('get.');
        $parameter['p']=I('get.p',1);
        $parameter['row']=I('get.row');


        $page = set_pagination($res["count"],$row,$parameter);
        if($page) {$this->assign('_page', $page);}

        $this->meta_title = '测试资源';
        $this->assign('data',$res['list']);
        $this->assign('count',$res["count"]);
        $this->display();
        # code...
    }
    /**
       * 获取区服列表
       * @param $game_id
       */
    public function getServer($game_id="")
    {
        $map['game_id']=$game_id;
        $map['start_time']=['lt',time()];
        if (I('status')==2) {
            $map['show_status']=1;
        }
        $data = M('server', 'tab_')
      ->field('tab_server.id,tab_server.server_name,support_quota')
      ->where($map)
      ->join('join tab_game tg ON tg.id=tab_server.game_id')
            ->order('server_id asc')
      ->select();

        $this->AjaxReturn($data);
    }
     //获取当前和当前子渠道的渠道id
     public function get_all_promote(){
        $pro_id=getPrmoteChlidAccount(get_pid(),"id");
        foreach ($pro_id as $key => $value) {
            $pro_id1[]=$value['id'];
        }
        if(!empty($pro_id1)){
            $pro_id2=array_merge($pro_id1,array(get_pid()));
        }else{
            $pro_id2=array(get_pid());
        }
        return $pro_id2;
    }
    /**
     * 系统非常规MD5加密方法
     * @param  string $str 要加密的字符串
     * @return string
     */
    public function think_ucenter_md5($str, $key = 'ThinkUCenter'){
        return '' === $str ? '' : md5(sha1($str) . $key);
    }
    //新增扶持
    public function add()
    {
        // dump(I('post.'));
        if (IS_POST) {
            $count=count(I('user_account'));
            session('apply_status', 0);
            (empty(I('server_id')) || I('server_id')<1) && $this->ajaxReturn(['msg'=>$i_account.'请选择区服' ,'status'=>0]);
            M('test_resource', 'tab_')->startTrans();  //事物
            for ($i=0; $i < $count ; $i++) {
                $i_account=I('user_account')[$i];
                if (!empty($i_account)) {
                    $user=M('user', 'tab_')->field('promote_id,password,phone')->where(['account'=>$i_account])->find();
                    $promote = $this->get_all_promote();
                    if (!in_array($user['promote_id'], $promote)) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>$i_account.'账号不存在' ,'status'=>0]);
                    }
                    if (empty(I('user_password')[$i])) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>I('user_account')[$i].'请输入密码' ,'status'=>0]);
                    }
                    if ($user['password']!=$this->think_ucenter_md5(I('user_password')[$i], UC_AUTH_KEY)) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>$i_account.'密码不正确' ,'status'=>0]);
                    }
                    if (empty(I('role_name')[$i])) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>I('user_account')[$i].'请输入角色名' ,'status'=>0]);
                    }

                    $supportNum = I('apply_resource')[$i];
                    if (empty($supportNum)) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>I('user_account')[$i].'请输入资源数量' ,'status'=>0]);
                    }
                    if ($supportNum<0 || !preg_match('/^[1-9]\d*$/', $supportNum)) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>I('user_account')[$i].'请输入资源数量' ,'status'=>0]);
                    }


                    $map['game_id']=I('game_id');
                    $map['server_id']=I('server_id');
                    $map['user_account']=I('user_account')[$i];
                    // $map['apply_status']=['neq',0];
                    $map['apply_type']=0;
                    $list= M('test_resource', 'tab_')->where($map)->find();
                    if ($list) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>I('user_account')[$i].'账号已存在' ,'status'=>0]);
                    }
                    //TODO:额度未进行验证

                    // $support_quota = M('game', 'tab_')->field('support_quota')->find(get_game_id(I('game_name')));
                    // if ($support_quota['support_quota'] < I('support_num')[$i]) {
                    //     M('test_resource', 'tab_')->rollback();//回滚
                    //     $this->ajaxReturn(['msg'=>'超出申请额度' ,'status'=>0]);
                    // }

                    $data['game_id']=I('game_id');
                    $data['game_name']=I('game_name');
                    $data['server_id']=I('server_id');
                    $data['server_name']=I('server_name');
                    $data['user_account']=I('user_account')[$i];
                    $data['user_id']=get_user_id(I('user_account')[$i]);
                    $data['user_password']=base64_encode(I('user_password')[$i]);
                    $data['phone']=$user['phone'];
                    $data['role_name']=I('role_name')[$i];


                    $data['apply_resource']=I('apply_resource')[$i];
                    $data['apply_remark']=I('apply_remark')[$i];

                    $data['apply_name']=$_SESSION['onethink_home']['promote_auth']['account'];
                    $data['apply_id']=$_SESSION['onethink_home']['promote_auth']['pid'];

                    $data['promote_id']=$_SESSION['onethink_home']['promote_auth']['pid'];
                    $data['promote_account']=$_SESSION['onethink_home']['promote_auth']['account'];

                    $data['create_time']=time();
                    $data['apply_type']=0;

                    $model = M('test_resource', 'tab_')->add($data);
                    if ($model) {
                        session('apply_status', 1);
                    }
                } else {
                    if (I('user_password')[$i]) {
                        M('test_resource', 'tab_')->rollback();//回滚
                        $this->ajaxReturn(['msg'=>'请输入账号' ,'status'=>0]);
                    }
                }
            }
            if (session('apply_status')==0) {
                session('apply_status', null);
                $this->ajaxReturn(['msg'=>'请输入账号' ,'status'=>0]);
            }
            M('test_resource', 'tab_')->commit();    //提交事物
            $this->ajaxReturn(['msg'=>'' ,'status'=>1]);
        } else {
            $this->meta_title = '新增测试账号';
            $this->display();
        }
    }
    //修改申请
    public function apply_edit(){
        $user=M('user','tab_')->field('password')->where(['account'=>I('user_account')])->find();
        if($user['password'] !== $this->think_ucenter_md5(I('user_password'), UC_AUTH_KEY)){
            $this->ajaxReturn(['status'=>0,'msg'=>'密码不正确']);
        }
        
        $data['user_password']=base64_encode(I('user_password'));
        $data['role_name']=I('role_name');
        $map = I("post.");
        unset($map['user_password']);
        unset($map['role_name']);
        $res=M('test_resource','tab_')->where($map)->save($data);
        if($res===false){
            $this->ajaxReturn(['status'=>0,'msg'=>'修改失败']);
        }else{
            $this->ajaxReturn(['status'=>1,'msg'=>'修改成功']);
        }
    }
    //后续申请
    public function apply(){
        $ids = explode(',', I('id'));
        foreach ($ids as $key => $value) {
            $map['id']=$value;
            $support=M('test_resource','tab_')->field('promote_id')->where($map)->find();
            if($support['promote_id'] !=session("promote_auth.pid") || empty($support) ){
                $this->error('数据错误');
            }
        }
        $this->meta_title = '申请后续';
        $this->display();
    }
    //申请新增扶持(单个或批量申请)
    public function batch_apply(){
        $ids = explode(',', I('apply_id'));

        M('test_resource','tab_')->startTrans();  //事物
        foreach ($ids as $key => $value) {

                $map['id']=$value;
                $support=M('test_resource','tab_')->where($map)->find();
                if(I('apply_resource') <0 || !preg_match('/^[1-9]\d*$/', I('apply_resource', 0))){
                    M('test_resource','tab_')->rollback();//回滚
                    $this->ajaxReturn(['status'=>0,'msg'=>'申请资源数量有误']);
                }
                if(empty($support)){
                    M('test_resource','tab_')->rollback();//回滚
                    $this->ajaxReturn(['status'=>0,'msg'=>'数据有误']);
                }
                //TODO:额度未进行验证

                // $max_quota=$this->max_quota($support['game_id'],$support['server_name']);//最大申请额度
                // if(count($ids)>1){
                //     $map_s['game_id']=$support['game_id'];
                //     $map_s['server_name']=$support['server_name'];
                //     $map_s['id']    =['in',$ids];
                //     $count=M('support','tab_')->where($map_s)->count();
                //     $max_quota = floor($max_quota/$count);
                // }
                // if(I('support_num') > $max_quota){
                //     M('support','tab_')->rollback();//回滚
                //     $this->ajaxReturn(['status'=>0,'msg'=>'扶持申请额度不足,最大额度:'.$max_quota]);
                // }

                if($support['promote_id'] !=session("promote_auth.pid") || empty($support) ){
                    M('test_resource','tab_')->rollback();//回滚
                    $this->ajaxReturn(['status'=>0,'msg'=>'申请失败']);
                }

                
                $data['game_id']=$support['game_id'];
                $data['game_name']=$support['game_name'];
                $data['server_id']=$support['server_id'];
                $data['server_name']=$support['server_name'];
                $data['user_account']=$support['user_account'];
                $data['user_id']=$support['user_id'];
                $data['user_password']=$support['user_password'];
                $data['phone']=$support['phone'];
                $data['role_name']=$support['role_name'];


                $data['apply_resource']=I('apply_resource');
                $data['apply_remark']=I('apply_remark');

                $data['apply_name']=$_SESSION['onethink_home']['promote_auth']['account'];
                $data['apply_id']=$_SESSION['onethink_home']['promote_auth']['pid'];

                $data['promote_id']=session("promote_auth.pid");
                $data['promote_account']=session("promote_auth.account");

                $data['create_time']=time();
                $data['apply_type']=1;
                //
                $model = M('test_resource','tab_')->add($data);
                if($model===false){
                    M('test_resource','tab_')->rollback();//回滚
                   $this->ajaxReturn(['status'=>0,'msg'=>'申请失败']);
                }else{
                    //成功
                }
        }
        M('test_resource','tab_')->commit();    //提交事物
        $this->ajaxReturn(['status'=>1,'msg'=>'申请成功']);
     }
     public function lists( $p = 1){
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row=10;
        if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}

        if(!empty(I('type'))||I('type')==='0'){
            $map['apply_status']=I('type');
        }

        if(!empty(I('role_name'))){
            $map['role_name']=['like','%'.I('role_name').'%'];
        }
        if(!empty(I('server_name'))){
            $map['server_name']=I('server_name');
        }
        if(!empty(I('game_name'))){
            $map['game_name']=I('game_name');
        }
        if(!empty(I('user_account'))){
            $map['user_account']=['like','%'.I('user_account').'%'];
        }
        if(!empty($_REQUEST['start'])&&empty($_REQUEST['end'])){
            $map['create_time']  =  array('GT',strtotime($_REQUEST['start']));
            unset($_REQUEST['start']);
        }
        if(empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('LT',strtotime($_REQUEST['end'])+24*60*60-1);
            unset($_REQUEST['end']);
        }
        if(!empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }

        $map['promote_id']=session("promote_auth.pid");
        $data=M('test_resource','tab_')->where($map)->order('id desc')->page($page,$row)->select();
        $count=M('test_resource','tab_')->field('id')->where($map)->select();
        $count = count($count);

        $parameter = I("get.");
        $parameter['p']=I('get.p',1);
        $parameter['row']=I('get.row');


        $page = set_pagination($count,$row,$parameter);
        if($page) {$this->assign('_page', $page);}

        $this->meta_title = '测试资源申请记录';
        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->display();
    }

    public function getChildPromoteList()
    {
        $promoteId = intval(I('post.promote_id', 0));
        $promoteId = empty($promoteId) ? PID : $promoteId;
        $promoteList = getAllPromoteListByType(3, false, $promoteId);
        $data['status'] = 1;
        $data['data'] = $promoteList;

        $this->ajaxReturn($data);
    }

}