<?php

namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public $token = '';
    public $http = 'https';

    public function _initialize()
    {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") != false) {
            $_SESSION['type'] = 'wx';
        } else {
            $_SESSION['type'] = 'app';
        }
    }

    public function getLoginAuthorizes1()
    {
        $http = 'https://';
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") != false) {
            $_SESSION['type'] = 'wx';
            $Data = I('');
            $code = $Data['code'];
            if (empty($code)) {
                $tourl = urlencode($http . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]);
                header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4eab2e3b5531d58b&redirect_uri=' . $tourl . '&response_type=code&scope=snsapi_base&state=abc123#wechat_redirect ');
            } else {
                $user_openid = $this->s_curl('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4eab2e3b5531d58b&secret=1026580a52dc89f564395113017c165b&code=' . $code . '&grant_type=authorization_code');

                $_SESSION['openid'] = $user_openid['openid'];
                $this->token = $_SESSION['openid'];
//                print_r($_SESSION);
//                exit();
                $res = M()->query("select phone,open_id from wc_user where enable=1 and registration_type='wx' and open_id='" . $user_openid['openid'] . "'");
                if (count($res) > 0) {
                    $_SESSION['phone'] = $res[0]['phone'];
                    $_SESSION['openid'] = $res[0]['open_id'];
                    $_SESSION['idopenid'] = $_SESSION['openid'];
                    $RES = M()->query("select personnel_function as permissionLabel from personnel where enable = 1 and personnel_phone='" . $_SESSION['phone'] . "' limit 1");
                    if (!empty($RES)) {
                        $_SESSION['permissionLabel'] = $RES[0]['permissionLabel'];
                        header('Location: https://wx.ewoogi.com/index.html#/pages/index/index?op=' . $res[0]['open_id']);//项目首页
                    }else{
                        header("Location: https://wx.ewoogi.com/index.html#/pages/authority/authority");//未授权页
                    }
                }else{
                    header('Location: https://wx.ewoogi.com/index.html#/pages/login/login?flag=true');//登录页
                    exit();
                }
            }
//            header('Location: https://wx.ewoogi.com/index.html#/pages/login/login?flag='.$_SESSION['openid']);//登录页
//            exit();
        } else {
            $_SESSION['type'] = 'app';
            $curl_token = $this->s_curl2($this->http . '://' . $_SERVER['SERVER_NAME'] . '/USKYOF/USKYOF.php/Home/Com/getPageAuthorization?key=38fff9e882bb58973942a16bb5bb05d005ad08d1e&secret=54cf9b2eb141284fb3974d8433e28293');
            $a = json_decode($curl_token, true);
            if (!empty($a)) {
                $a = (array)json_decode($curl_token, true);
            } else {
                $str = str_replace('{', '', $curl_token);
                $str1 = str_replace('}', '', $str);
                $var = explode(",", $str1);
                $a = '';
                foreach ($var as $key => $value) {
                    $a[str_replace('"', '', explode(":", $var[$key])[0])] = str_replace('"', '', explode(":", $var[$key])[1]);
                }
            }
            $_SESSION['app_token'] = $a['token'];
            $this->token = $a['token'];
            header('Location: https://wx.ewoogi.com/index.html#/pages/login/login?flag=true');//登录页
            exit();
        }
//        header('Location: https://wx.ewoogi.com/index.html#/pages/login/login?flag=true');//登录页
    }


    //短信验证
    public function getVerificationCode()
    {
        include('/php/api_sdk/JdMessageSend2.php');
        $Data = I('phone');
        $Verx = rand('10000', '99999');
        $_SESSION['VerificationCode'] = '';
        $_SESSION['VerificationCode'] = $Verx . ',' . date('Y-m-d H:i:s');
//        print_r($_SESSION['VerificationCode']);
        sendSms("$Data", "$Verx");
        $arr[0]['VerificationCode'] = $_SESSION['VerificationCode'];
        $res['msg'] = '发送成功';
        $res['flag'] = true;
        $res['data'] = $arr;
        echo json_encode($res);

    }

    //登录并注册
    public function setSignUp()
    {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") != false) {
            $_SESSION['type'] = 'wx';
        } else {
            $_SESSION['type'] = 'app';
        }

        $Data = I('');
        if (!isset($Data['phone']) || !isset($Data['VerificationCode']) || !isset($Data['VerificationCodeOne'])) {
            $R['msg'] = '操作失败，缺少关键参数';
            $R['flag'] = true;
            echo json_encode($R);
            exit();
        }
        $Arr = explode(",", $Data['VerificationCodeOne']);
        $Arr2 = explode(",", $_SESSION['VerificationCode']);
        $verifyTime = floor(strtotime(date('Y-m-d H:i:s'))) - floor(strtotime($Arr[1]));
        if ($verifyTime < 300) {
            if ($Arr[0] != $Data['VerificationCode']) {
                $R['msg'] = '验证码无效，请重新获取！';
                $R['flag'] = false;
                echo json_encode($R);
                exit();
            }

            $res = M()->query("select id,phone,open_id as openid,registration_type as type,create_time as addtime,enable as status from wc_user where  phone='" . $Data['phone'] . "' and registration_type='" . $_SESSION['type'] . "'");

            if ($_SESSION['type'] == 'app') {
                $data['open_id'] = $_SESSION['app_token'];
            } else {
                $data['open_id'] = $_SESSION['openid'];
            }
            $data['phone'] = $Data['phone'];
            $data['registration_type'] = $_SESSION['type'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['enable'] = 1;
            if (empty($res)) {
                $Res = M('wc_user')->add($data);
            }
            $_SESSION['phone'] = $data['phone'];
            $_SESSION['openid'] = $data['open_id'];
            $_SESSION['idopenid'] = $_SESSION['openid'];
            $res1 = M()->query("select personnel_function as permissionLabel from personnel where  personnel_phone='" . $Data['phone'] . "' limit 1");
            if (count($res1)>0){
                $_SESSION['permissionLabel'] = $res1[0]['permissionLabel'];
            }
            $R['msg'] = '验证成功，正在登录，请等待跳转------';
            $R['flag'] = true;
            echo json_encode($R);
        } else {
            $R['msg'] = '验证码超时无效，请重新获取！';
            $R['flag'] = false;
            echo json_encode($R);
        }
    }

    public function setSignUp1()
    {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") != false) {
            $_SESSION['type'] = 'wx';
        } else {
            $_SESSION['type'] = 'app';
        }

        $Data = I('');
        if (!isset($Data['phone']) || !isset($Data['VerificationCode']) || !isset($Data['VerificationCodeOne'])) {
            $R['msg'] = '操作失败，缺少关键参数';
            $R['flag'] = true;
            echo json_encode($R);
            exit();
        }
//        $Arr = explode(",", $Data['VerificationCodeOne']);
        $Arr = explode(",", $_SESSION['VerificationCode']);
        $verifyTime = floor(strtotime(date('Y-m-d H:i:s'))) - floor(strtotime($Arr[1]));
        if ($verifyTime < 300) {
            if ($Arr[0] != $Data['VerificationCode']) {
                $R['msg'] = '验证码无效，请重新获取！';
                $R['flag'] = false;
                echo json_encode($R);
                exit();
            }


            $res = M()->query("select id,phone,open_id as openid,registration_type as type,create_time as addtime,enable as status from wc_user where enable=1 and  phone='" . $Data['phone'] . "' and registration_type='" . $_SESSION['type'] . "'");

            if ($_SESSION['type'] == 'app') {
                $data['open_id'] = $_SESSION['app_token'];
            } else {

                $data['open_id'] = $_SESSION['openid'];
            }

            $data['phone'] = $Data['phone'];
            $data['registration_type'] = $_SESSION['type'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['enable'] = 1;
            if (empty($res)) {
                $Res = M('wc_user')->add($data);
            }
            $_SESSION['phone'] = $data['phone'];
            $_SESSION['openid'] = $data['open_id'];
            $_SESSION['idopenid'] = $_SESSION['openid'];
            $res1 = M()->query("select personnel_function as permissionLabel from personnel where  personnel_phone='" . $Data['phone'] . "' limit 1");
            if (count($res1)>0){
                $_SESSION['permissionLabel'] = $res1[0]['permissionLabel'];
            }
//            print_r($_SESSION);
//            exit();
            $R['msg'] = '验证成功，正在登录，请等待跳转------';
            $R['flag'] = true;
            echo json_encode($R);
        } else {
            $R['msg'] = '验证码超时无效，请重新获取！';
            $R['flag'] = false;
            echo json_encode($R);
        }
    }

    private function s_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($file_contents, true);
//        var_dump($arr);
        return $arr;
    }

    private function s_curl2($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }
}
