<?php
namespace app\index\controller;

use app\index\controller\Commone;
use \think\Db;
use \think\Cookie;
use \think\Session;
use \think\Cache;
class Index extends Commone
{
    
    //商户登录
    public function login(){
         if(Session::has('user_id') == false) { 
            if($this->request->isPost()) {
                
                //是登录操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['username', 'require|alphaDash', '用户名不能为空|用户名格式只能是字母、数字、——或_'],
                    ['password', 'require', '密码不能为空'],
                   // ['captcha','require|captcha','验证码不能为空|验证码不正确'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $name = Db::name('user')->where('name',$post['username'])->find();
                if(config('cate') == '0'){
                    if($name['cate_id'] == '0'){
                        return $this->error('暂时无法登陆');
                    }
                }
                if(empty($name)) {
                    //不存在该用户名
                    return $this->error('用户名不存在');
                } else {
                    //验证密码
                    $post['password'] = $this->password($post['password']);
                    if($name['password'] != $post['password']) {
                        return $this->error('密码错误');
                    } else {
                        //是否记住账号
                        if(!empty($post['remember']) and $post['remember'] == 1) {
                            //检查当前有没有记住的账号
                            if(Cookie::has('usermember')) {
                                Cookie::delete('usermember');
                            }
                            //保存新的
                            Cookie::forever('usermember',$post['username']);
                        } else {
                            //未选择记住账号，或属于取消操作
                            if(Cookie::has('usermember')) {
                                Cookie::delete('usermember');
                            }
                        }
                        Session::set("user_id",$name['id']); //保存新的账户ID
                        Session::set("cate_id",$name['cate_id']); //保存新的账户类型
                        //记录登录时间和ip
                        Db::name('user')->where('id',$name['id'])->update(['login_ip' =>  $this->request->ip(),'login_time' => time()]);
                       
                        return $this->success('登录成功,正在跳转...','index/member');
                    }
                }
            } else {
                if(Cookie::has('usermember')) {
                    $this->assign('usermember',Cookie::get('usermember'));
                }
              
                $this->assign('cate',config('cate'));
                return $this->fetch();
            }
        } else {
            $this->redirect('index/member');
        }   
        
    }
    
     public function reg(){
        $web_config = Db::name('config')->where('id',1)->find();
        $this->INDEX_AI();
        if($web_config['reg_status'] == '0'){
             exit($this->fetch('/error')); 
        }
        if($this->request->isPost()) {
            if($web_config['reg_status'] == '0'){
             exit($this->fetch('/error')); 
            }
            $post = $this->request->post();
            if($post['name']==''){
                return $this->error('用户名不可为空'); 
            }
            if($post['pwd']==''){
                return $this->error('密码不可为空'); 
            }
            
            $validate = new \think\Validate([
                    
                    ['captcha','require|captcha','验证码不能为空|验证码不正确'],
                ]);
                //验证部分数据合法性
            if (!$validate->check($post)) {
                    $this->error($validate->getError());
            }
            $user = Db::name('user')->where('name',$post['name'])->find();
            if($user){
                return $this->error('用户名已被注册'); 
            }
            
            if(!isuser($post['name'])){
                return $this->error('请输入正确的用户名,字母+数字且大于6个字符');
            }
            
            if(!ispwd($post['pwd'])){
                return $this->error('密码输入错误,请输入6-26位的字符密码');
            }
            
            //生成key
            $api_key = substr(md5(mt_rand(10000,99999) . mt_rand(1000,9999)), 0,32);
		
		    //生成api_id(商户ID）
            $api_id = substr(md5(mt_rand(10000,99999) . mt_rand(1000,9999)), 0,16);
		
            //生成密码
            $pwd = $this->password($post['pwd']);
             //初始化默认手续费
            $web_config = Db::name('config')->where('id',1)->find();
            
            $add = Db::name('user')->insert(array(
            "name"=>$post['name'],
            "password"=>$pwd,
            "create_time"=>time(),
            'update_time'=>0,
            'login_time'=>0,
            'login_ip'=>0,
            'cate_id'=>0,
            'balance'=>$web_config['reg_money'],
            'api_key'=>$api_key,
			'pay_sxf'=>$web_config['reg_sxf'],
			'api_id'=>$api_id
			
        ));
        
        if($add){
           
            return $this->success('注册成功');
        }else{
            return $this->error('注册失败'); 
        }
        }
        

        return $this->fetch(); 
    }
    
    //商户中心框架
    public function member(){
        $this->AI();
        $this->INDEX_AI();
        $user_name = $this->get_user('name');
        $user_cate_id =  $this->get_user('cate_id');
        if($user_cate_id=='1'){
              $cate = config('cate');//取系统类型
        }else{
              $cate = 0;//取系统类型
        }
        $game_type = Db::name('game_type')->select();
	    $this->assign('game_type',$game_type);
        $this->assign('user',$user_name);
        $this->assign('cate',$cate);
        $this->assign('cate_1',config('cate'));
        return $this->fetch();
    }
    
    //商户中心首页
    public function home(){
        
        $this->AI();
        $this->INDEX_AI();
        $where['userid'] = $this->get_user('id');
        $where['state'] = 2;
        $news_data = Db::name('news')->order('zd desc')->order('id desc')->limit(8)->select();
        $user_cate_id = $this->get_user('cate_id');
        $user_game_id = $this->get_user('game_id');
        if($user_game_id == 0){
             $user_game_id = config('game_id');
        }
       
        $money['jr'] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'today')->sum('money');
        $money['zr'] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'yesterday')->sum('money');
        $count['jr'] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'today')->count();
        $count['zr'] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'yesterday')->count();
        $nowTime = strtotime(date("Y-m-d",time()) . ' 00:00:00');
        for ($i = 0; $i < 8; $i++) {
             $time[] = date("m-d",time()-86400*$i);
             
             $time_1 = date("Y-m-d 00:00:00",$nowTime-86400*$i);
             $time_2 = date("Y-m-d 00:00:00",$nowTime-86400*($i - 1));
             
             $biao_money[] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'between', [$time_1, $time_2])->sum('money');
             $biao_count[] = Db::name('orders')->where('payc','in',$user_game_id)->where($where)->whereTime('pay_time', 'between', [$time_1, $time_2])->count();
        }
        
        $cate = $user_cate_id;//取系统类型
        $user_cate_type = '普通商户';
        if($user_cate_id=='1'){
            $user_cate_type = '平台主';
            $cate = config('cate');//取系统类型
        }else{
            if(config('cate')=='1'){
            $cate = '1';//取系统类型
            }
        }
        
      
        
        
        $this->assign('user_cate_type',$user_cate_id);
        $this->assign('cate',$cate);
        $this->assign('user',$this->get_user('name'));
        $this->assign('balance',$this->get_user('balance'));
        $this->assign('pay_sxf',$this->get_user('pay_sxf'));
        $this->assign('news_data',$news_data);
        $this->assign('user_type',$user_cate_type);
        $this->assign('money',$money);
        $this->assign('count',$count);
        $this->assign('time',json_encode(array_reverse($time)));
        $this->assign('biao_money',json_encode(array_reverse($biao_money)));
        $this->assign('biao_count',json_encode(array_reverse($biao_count)));
        return $this->fetch();
    }
    
    public function info()
    {
        $this->AI();
        $this->INDEX_AI();
        return view();
    }
    
    public function info_save()
    {
        $this->AI();
        $this->INDEX_AI();
        $post = $this->request->post();
        $user = Db::name('user')->where('id',$this->get_user('id'))->find();
       
        if($this->password($post['oldPsw'])==$user['password']){
              $update['password'] = $this->password($post['newPsw']);
              $save = Db::name('user')->where('id',$this->get_user('id'))->update($update);
              if($save){
                  $this->success("修改成功");
              }else{
                  $this->error("修改失败");
              }
         }else{
              $this->error("原密码错误");
         }
       
    }
    
    
    //管理员退出
    public function logout()
    {
        Session::delete('user_id');
        Session::delete('cate_id');
        if(Session::has('user_id') or Session::has('cate_id')) {
            return $this->error('退出失败');
        } else {
            return $this->success('正在退出...');
        }
    }
    
    public function api_index(){
        $this->AI();
        $this->INDEX_AI();
        $web_config = Db::name('config')->where('id',1)->find();
        $pay_news = Db::name('news')->where('id',$web_config['pay_txtid'])->find();
        $this->assign('user_pid',$this->get_user('api_id'));
        $this->assign('user_key',$this->get_user('api_key'));
        $this->assign('web_pay1',$web_config['pay_url']);
        $this->assign('news_txt',$pay_news['text']);
        return view();
    }
    
    
    public function GeneratingKey(){
        $this->AI();
        $this->INDEX_AI();
        $keyid = substr(md5(mt_rand(10000,99999) . mt_rand(1000,9999)), 0,32);
        $update_Key = Db::name("user")->where('id',$this->get_user('id'))->update(array("api_key"=>$keyid));
       if ($update_Key){
             $this->json_success("已成功重新生成",$keyid); 
        }else{
             $this->error("发生错误,生成失败");
        }
    }
    
    public function news(){
     
        $post = $this->request->get('id');
        $news = Db::name('news')->where('id',$post)->find();
        $this->assign('news',$news);
        return view();
    }
    
    public function pays(){
        $this->AI();
        $this->INDEX_AI();
        $user_name = $this->get_user('name');
        $web_config = Db::name('config')->where('id',1)->find();
        $user_config = Db::name('user')->where('cate_id',1)->find();
        $pay_Set = config_set('pay_set');
        $pay_msg = config_set('pay_msg');
        $this->assign('pay_Set',$pay_Set['value']);
        $this->assign('pay_msg',$pay_msg['value']);
        $this->assign('name',$user_name);
        
        if($this->request->isPost()) {
            $post = $this->request->post();
            $api_id = $user_config['api_id'];
            $key = $user_config['api_key'];
            $url = $web_config['pay_url'];
            
            
            $data = [
                    'api_id' => $api_id,
                    'record' => $this->get_user('name'),
                    'money' => sprintf("%.2f",$post['money']),
            ];

            ksort($data);
                $str1 = '';
                foreach ($data as $k => $v) {
                    $str1 .= '&' . $k . "=" . $v;
            }

            $sign = md5(trim($str1) . $key);

            $data['refer']=url('index/index/member');

            $data['notify_url']=url('index/notify');

            $data['sign']=$sign;
            
            $data['mid'] = $web_config['land_pay'];
            
            $htmls = "<form id='ckpay' name='ckpay' action='" . $url . "' method='post' target='_blank'>";
            foreach ($data as $key => $val) {
                 $htmls .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
            }
            $htmls .= "</form>";
            $htmls .= "<script>document.forms['ckpay'].submit();</script>";
            return $this->success($htmls);
            }
        return view();
    }
    
    
    public function notify(){
        $post = $this->request->post();
        $user_config = Db::name('user')->where('cate_id',1)->find();
        if ($post['key'] == $user_config['api_key']){
         
            $amount = sprintf("%.2f",$post['money']);
            $record = $post['record'];
			$num = $post['order'];
			$sign = $post['sign'];
            $api_id = '86a3b2bd1f1571ed';
            $data = [
                   'api_id' => $api_id,
                   'record' => $record,
                   'money' => $amount
  
           ];
           
            ksort($data);
                $str1 = '';
                foreach ($data as $k => $v) {
                    $str1 .= '&' . $k . "=" . $v;
            }
            
          	$sign_ok = md5(trim($str1) . $post['key']);
            
            
           if($sign!=$sign_ok) exit('签名验证失败');
           
            $users = Db::name('user')->where('name',$record)->find();
            if (!$users) exit('充值失败,用户不存在');
            //增加金额
            Db::name('user')->where('id',$users['id'])->update(array("balance"=>($users['balance']+$amount)));

            echo $record . '充值成功';
        }else{
            exit('密钥错误');
        }
    
    }
}

if(!defined("A____AA"))define("A____AA","A___A__");$GLOBALS[A____AA]=explode("|{|t|]", "H*|{|t|]414141415F5F");if(!defined("AAAAAA"))define("AAAAAA","A______");$GLOBALS[AAAAAA]=explode("|D|~|{", "H*|D|~|{414141415F41|D|~|{66696C655F657869737473|D|~|{41414141415F|D|~|{6469726E616D65|D|~|{2F7777772E396E772E63632E75726C|D|~|{3C7370616E207374796C653D22666F6E742D73697A653A323470783B223EE6BA90E7A081E69DA5E887AA3C2F7370616E3E3C6120687265663D2268747470733A2F2F7777772E396E772E636322207461726765743D225F626C616E6B223E3C7370616E207374796C653D22666F6E742D73697A653A323470783B223EE4B99DE7899BE7BD913C2F7370616E3E3C2F613E3C7370616E207374796C653D22666F6E742D73697A653A323470783B223EE58886E4BAABEFBC8CE8AFB7E58BBFE588A0E999A4E6A0B9E79BAEE5BD95E4B88BE79A84266E6273703B207777772E396E772E636320266E6273703B20E5BFABE68DB7E696B9E5BC8F2020200D0A09093C2F7370616E3E");if(!defined(pack($GLOBALS[A____AA][00],$GLOBALS[A____AA][01])))define(pack($GLOBALS[A____AA][00],$GLOBALS[A____AA][01]), ord(37));$GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][0x1])]=pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][2]);$GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][03])]=pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][04]);if(!$GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][0x1])]($GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][03])]($GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][03])]($GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][03])]($GLOBALS[pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][03])](__FILE__)))). pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][0x5]))){echo pack($GLOBALS[AAAAAA][0],$GLOBALS[AAAAAA][06]);exit;}