<?php

namespace app\agent\controller;

use fastphp\base\Jwt;
use app\agent\model\AgentUser;
use app\agent\model\User as UserModel;
use alipay\AliverifyPublic as Aliverify;
use extend\alisms\Sms;
use extend\redis\Redisop;
use app\tencent\model\Agreement as AgreementModel;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Jdcloud\Credentials\Credentials;
use Jdcloud\Result;
use Jdcloud\Cloudauth\CloudauthClient;

class Index
{

    private $accessKey = 'AfRhvJoAKL24ftGcHMor1WwSpVdular7L7X97JNY';
    private $secretKey = 'OyyU-6M45oDZAlVsf8fH0RFALGxTNHAT-yR6cmtU';
    private $bucket = 'zip9';


    //代理登录
    public function login()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $jwt = new Jwt('etor_yh_lzh_20f_2020_YES');
        $agent_user_model = new AgentUser;
        $userinfo = $agent_user_model->getOne(['username'=>$data['Logincode']]);
        $userinfo['ID'] = $userinfo['id'];

        $payload = [
            'LoginName' => $userinfo['realname'],
            'RoleName' => '',
            'phone' => $userinfo['phone'],
            'OperaterID' => $userinfo['id'],
            'TenantId' => 1157,
            'iat' => time(),
            'exp' => time() + 180 * 60
        ];

        $token = $jwt::getToken($payload);

        $return_data = [
            'Manager'=>$userinfo,
            'Token'=>$token
        ];

        if (!empty($userinfo)){
            if (cToMd5($data['Password']) == $userinfo['password']){
                
                $info = [
                    'Code'=>10000,
                    'Data'=>$return_data
                ];
                echo  json_encode($info);
                
            }
        }

    }

    //----------------
    
    public function getCode() {
        $phone = json_decode(file_get_contents("php://input"), true)['phone'];
        $redis = new Redisop();
        $user_model = new UserModel();
        $is_exit = $user_model->getOne(['Phone' => $phone]);
        if($is_exit) {
            if ($is_exit['is_verify'] == 0) {
                $data_user_old = [
                    'LoginCode' => $is_exit['LoginCode'].'-del',
                    'Phone' => $is_exit['Phone'].'-del',
                ];

                $user_model->updateOne(['Id'=>$is_exit['Id']],$data_user_old);
            }
            // $return_data = [
            //     'code' => 0,
            //     'msg' => '用户已经存在'
            // ];
            // echo json_encode($return_data);die;
        }


        $getCode = $redis->get($phone);

        if (empty($getCode)) {
            $code = rand(1000,9999);
            $redis->setOfTime($phone,$code);
            $alisms = new Sms;
            $alisms::sendVerify($phone, $code);
            $return_data = [
                'code' => 1,
                'msg' => '验证码已发送'
            ];
            echo json_encode($return_data);die;
        } else {
            $return_data = [
                'code' => 0,
                'msg' => '请稍后再试'
            ];
            echo json_encode($return_data);die;
        }
        
    }
    //---------------

    //推广用户注册
    public function register()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        // dump($data);die;
        $data['LoginCode'] = trim($data['LoginCode']);

        if(empty($data['LoginCode'])){
            $info = [
                'Code' => 10003,
                'Data' => '',
                'Message' => '账号为空',
            ];
            echo json_encode($info);
            die;
        }
        $redis = new Redisop();
        $code = $redis->get($data['LoginCode']);


        if (empty($code)) {
            $return_data = [
                'code' => 0,
                'msg' => '验证码不正确'
            ];
            echo json_encode($return_data);die;
        } 
        if ($data['code'] != $code) {
            $return_data = [
                'code' => 0,
                'msg' => '验证码不正确'
            ];
            echo json_encode($return_data);die;
        }
        //----

        $data['agent_id'] = base64_decode($data['agent_id']);
        // dump($data);die;

        $data['Phone'] = $data['LoginCode'];
        $data['TenantId'] = 0;
        $data['Enabled'] = 1;
        $data['UpdateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateType'] = 4;
        $data['ProductAccountCount'] = 0;
        $data['ExpiredProductAccountCount'] = 0;
        $data['RestAmount'] = 0;
        $data['ConsumeAmount'] = 0;
        $data['DeleteTag'] = 0;
        $data['UseTestCount'] = 0;
        $data['Sex'] = 0;
        $data['Wx'] = '';
        $data['QQ'] = '';
        $data['LastLoginDate'] = date('Y-m-d H:i:s',time());
        $data['Password'] = empty($data['Password'])?cToMd5('123468455'):cToMd5(trim($data['Password']));

        $user_model = new UserModel;
        $data['ManagerId'] = 0;
        unset($data['code']);

        $has_user = $user_model->isExit("LoginCode='".$data['LoginCode']."' or Phone='".$data['Phone']."' or TaoBao='".$data['Phone']."'");
        if ($has_user){
            if ($has_user['is_verify'] == 0) {
                $data_user_old = [
                    'LoginCode' => $has_user['LoginCode'].'-del',
                    'Phone' => $has_user['Phone'].'-del',
                ];

                $user_model->updateOne(['Id'=>$has_user['Id']],$data_user_old);
            }
            // $info = [
            //     'Code' => 20000,
            //     'Data' => '',
            //     'Message' => '该账号或者手机号被注册了',
            // ];
            // echo json_encode($info);
            // die;
        }

        $has_user2 = $user_model->isExit("id_code='".$data['id_code']."' and is_verify=1");
        
        if ($has_user2){
            $info = [
                'Code' => 30000,
                'Data' => '',
                'Message' => '该身份已经进行认证，无法再次进行认证！',
            ];
            echo json_encode($info);
            die;
        }

        if ($user_model->add($data)) {

            echo json_encode($this->aliverify([
                'id_code' =>  $data['id_code'],
                'name' =>  $data['Name'],
                'phone' => $data['LoginCode']
            ]));

        }
        die;
    }

    //推广用户注册
    public function apiregister()
    {
        $data = $_GET;
        // dump($data);die;
        
        unset($data['s']);
        $data['LoginCode'] = trim($data['LoginCode']);

        if(empty($data['LoginCode'])){
            $info = [
                'Code' => 10003,
                'Data' => '',
                'Message' => '账号为空',
            ];
            echo json_encode($info);
            die;
        }
        //----

        if(empty($data['agent_id'])){
            $info = [
                'Code' => 10003,
                'Data' => '',
                'Message' => '代理id错误',
            ];
            echo json_encode($info);
            die;
        }

        $data['agent_id'] = base64_decode($data['agent_id']);

        if ($data['agent_id']<10000) {
            $info = [
                'Code' => 10003,
                'Data' => '',
                'Message' => '代理id错误',
            ];
            echo json_encode($info);
            die;
        }
        // dump($data);die;

        $data['Phone'] = $data['LoginCode'];
        $data['TenantId'] = 0;
        $data['Enabled'] = 1;
        $data['UpdateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateType'] = 4;
        $data['ProductAccountCount'] = 0;
        $data['ExpiredProductAccountCount'] = 0;
        $data['RestAmount'] = 0;
        $data['ConsumeAmount'] = 0;
        $data['DeleteTag'] = 0;
        $data['UseTestCount'] = 0;
        $data['Sex'] = 0;
        $data['Wx'] = '';
        $data['QQ'] = '';
        $data['LastLoginDate'] = date('Y-m-d H:i:s',time());
        $data['Password'] = empty($data['Password'])?cToMd5('123568'):cToMd5(trim($data['Password']));

        $user_model = new UserModel;
        $data['ManagerId'] = 0;

        $has_user = $user_model->isExit("LoginCode='".$data['LoginCode']."' or Phone='".$data['Phone']."' or TaoBao='".$data['Phone']."'");
        if ($has_user){
            if ($has_user['is_verify'] == 0) {
                $data_user_old = [
                    'LoginCode' => $has_user['LoginCode'].'-del',
                    'Phone' => $has_user['Phone'].'-del',
                ];

                $user_model->updateOne(['Id'=>$has_user['Id']],$data_user_old);
            } else {
                $info = [
                    'Code' => 20000,
                    'Data' => '',
                    'Message' => '该账号或者手机号被注册了',
                ];
                echo json_encode($info);
                die;
            }
            
        }

        if ($user_model->add($data)) {
            $info = [
                'Code' => 10000,
                'Data' => '',
                'Message' => '该账号注册成功！',
            ];
            echo json_encode($info);
            die;
        }
        die;


    }

   private function getCred(){
        $ak = "JDC_A3B38E573D7404F976472FB42F52";
        $sk = "C9BAE98F49B42DA2DC02868A75AA3AD8";
        $cred = new Credentials($ak, $sk);
        return $cred;
    }
    public function aliverify($temp)
    {
        $user = new UserModel;
        $update_one = [];

        $client = new CloudauthClient([
            'credentials'  => $this->getCred(),
            'version' => 'latest',
            'scheme' => 'http'
        ]);

        $res = $client->GetAliveUrl([
            'name'  => $temp['name'],
            'idcard'  => $temp['id_code'],
            'returnUrl'  => 'https://php-api.juip.com/taobao/Publicget/getresult?id_code='.$temp['id_code']
        ]);

        if(isset($res['result']['code']) && $res['result']['code'] == 'ok'){
            $update_one['certify_id'] = $res['result']['token'];
            $update_one['Name'] = $temp['name'];
            $update_one['id_code'] = $temp['id_code'];
            $data['url'] = $res['result']['url'];
            if($user->updateOne(['LoginCode'=>$temp['phone']],$update_one)){
                $data['Code'] = 10000;
            } else {
                $data = [
                    'Code'=>-10000
                ];
            }
        }  else {
            $data = [
                'Code'=>-10000
            ];
        }
        return $data;
    }

    public function getisverify()
    {
        $user_phone = $_GET['user'];
        $user = new UserModel;
        $user_one_info = $user->getOne(['LoginCode'=>$user_phone]);
        if($user_one_info['is_verify'] == 1){
            $data = [
                'Code'=>10000
            ];
            echo  json_encode($data);
            die;
        } else {
            $data = [
                'Code'=>-10000
            ];
        }
        echo  json_encode($data);
    }

    public function aliGetResult()
    {
        $user_phone = $_GET['user'];
        $user = new UserModel;
        $user_one_info = $user->getOne(['LoginCode'=>$user_phone]);
        $info = Aliverify::getResult2($user_one_info['certify_id']);
        $data = [];
        if($info){
            $user_data['is_verify'] = 1;
            if ($user_one_info['is_verify'] == 1) {
                $data = [
                    'Code'=>10000
                ];
                echo  json_encode($data);
                die;
            }
            if($user->updateOne(['Id'=>$user_one_info['Id']],$user_data)){
                $data = [
                    'Code'=>10000
                ];
            }
        } else {
            $data = [
                'Code'=>-10000
            ];
        }
        echo  json_encode($data);
    }
    

    public function aliGetResult2()
    {
        $user_phone = $_GET['user'];
        $user = new UserModel;
        $user_one_info = $user->getOne(['LoginCode'=>$user_phone]);
        $info = Aliverify::getResult2($user_one_info['certify_id']);
        dump($info);
        $data = [];
        if($info){
            $user_data['is_verify'] = 1;
            if ($user_one_info['is_verify'] == 1) {
                $data = [
                    'Code'=>10000
                ];
                echo  json_encode($data);
                die;
            }
            if($user->updateOne(['Id'=>$user_one_info['Id']],$user_data)){
                $data = [
                    'Code'=>10000
                ];
            }
        } else {
            $data = [
                'Code'=>-10000
            ];
        }
        echo  json_encode($data);
    }


    
    public function isverify() {
        $user_phone = $_GET['phone'];
        
        $user_model = new UserModel;

        $userinfo = $user_model->getOne(['LoginCode' => $user_phone],'is_verify');

        echo json_encode($userinfo);
    }

    public function upload()
    {

        $user_model = new UserModel;

        $data = $_POST;

        $username = $data['username'];

        $userinfo = $user_model->getOne(['LoginCode' => $username]);

        if (empty($userinfo)) {
            echo json_encode(['code' => -1,'msg'=>'手机号不存在！']);die;
        }

        $userid = $userinfo['Id'];

        $agreement_model = new AgreementModel;

        $is_ipload = $agreement_model->getOne(['user_id' => $userid]);

        if (!empty($is_ipload)) {
            echo json_encode(['code' => -1,'msg'=>'已经上传过！']);die;
        }



        $xieyi = $_FILES['xieyi'];
        
        $size_limit = 30 * 1024 * 1024;
        if ($xieyi['size']>$size_limit) {
            echo json_encode(['code' => -1,'msg'=>'文件过大，仅限30M']);
            die;
        }
        
        $agreement_data = [
            'user_id' => $userid,
            'username' => $username,
            'status' => 1,
            'describe' => $data['describe'],
        ];
        if(!$data['status']) {
            echo json_encode(['code' => -1,'msg'=>'失败']);die;
        }
        
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        // 要上传文件的本地路径
        $xieyi_filePath = $xieyi['tmp_name'];
        // 上传到存储后保存的文件名
        $xieyi_key = $username.'-'.time().'.png';

        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $xieyi_key, $xieyi_filePath, null, 'application/octet-stream', true, null, 'v2');
        $agreement_data['xieyi'] = 'http://zip.juip.com/'.$xieyi_key;

        $status = $agreement_model->add($agreement_data);
        
        if ($status) {
            echo json_encode(['code' => 1,'msg'=>'成功']);
        } else {
            echo json_encode(['code' => -1,'msg'=>'失败']);
        }
    }


}