<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Index extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    //获取钉钉用户授权信息
    public function auth($agentId) {
        $data = array();

        //$agentId 应用ID，如果没有传进来跳到错误页面
        if (empty($agentId)) {
            echo 'agentId不能为空';
            return false;
        }

        //生成签名
        $url = $this->curPageURL();
        $nonceStr = 'abcdefg&cits@123#';
        $timeStamp = time();
        $corpId = 'ding48bce8fd3957c96b';
        $secret = '4I_TlkOUtWQ60tUYX_447WXM5mNX41q_Q03xtZJgvBOzMPzGbNKZZz_Bsv-0B9I1';

        //缓存accessToken。accessToken有效期为两小时，需要在失效前请求新的accessToken（注意：以下代码没有在失效前刷新缓存的accessToken）。
        $cookie_accessToken = 'Token_' . $agentId;
        $accessToken = isset($_COOKIE[$cookie_accessToken]) ? $_COOKIE[$cookie_accessToken] : false;
        if (empty($accessToken)) {
            $response = GET_HTTP("https://oapi.dingtalk.com/gettoken?corpid=$corpId&corpsecret=$secret");
            if (empty($response)) {
                log_message('error', "accessToken gethttp");
                return false;
            }
            $accessToken = json_decode($response)->access_token;
            setcookie($cookie_accessToken, $accessToken, time() + 7140, '/');
        }

        $cookie_jsapi_ticket = 'Ticket_' . $agentId;
        $jsapi_ticket = isset($_COOKIE[$cookie_jsapi_ticket]) ? $_COOKIE[$cookie_jsapi_ticket] : false;
        if (empty($jsapi_ticket)) {
            $response = GET_HTTP("https://oapi.dingtalk.com/get_jsapi_ticket?type=jsapi&access_token=$accessToken");
            if (empty($response)) {
                log_message('error', "jsapi_ticket gethttp");
                return false;
            }
            $jsapi_ticket = json_decode($response)->ticket;
            setcookie($cookie_jsapi_ticket, $jsapi_ticket, time() + 7140, '/');
        }

        $signature = sha1('jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $nonceStr . '&timestamp=' . $timeStamp . '&url=' . $url);

        $config = array(
            'url' => $url,
            'nonceStr' => $nonceStr,
            'agentId' => $agentId,
            'timeStamp' => $timeStamp,
            'corpId' => $corpId,
            'signature' => $signature,
            'accessToken' => $accessToken,
        );

        $data['auth_config'] = json_encode($config);
        $this->load->view('welcome', $data);
		//print_r($data);
    }

    public function curPageURL() {
        $pageURL = 'http';

        if (array_key_exists('HTTPS', $_SERVER) && $_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    //$agentId 应用ID，用来判断应该跳转到哪里去
    //$user_code 用户code，需要再次请求接口来获取用户详细信息
    public function authOnSuccess($agentId,$accessToken, $user_code) {
		$response =GET_HTTP("https://oapi.dingtalk.com/user/getuserinfo?access_token=$accessToken&code=$user_code");
		  if (empty($response)) {
                log_message('error', "getuserinfo gethttp");
                return false;
           }
            $userid = json_decode($response)->userid;
			$response =GET_HTTP("https://oapi.dingtalk.com/user/get?access_token=$accessToken&userid=$userid");	
		  if (empty($response)) {
                log_message('error', "user gethttp");
                return false;
           }
		   $response= json_decode($response);
		   if(!empty($response) && $response->errcode==0){
			   	$username= $response->name;
				redirect("http://doc.mycht.cn/index.php?user/loginSubmit&name=$username&password=9Q7gJ3239aK_8LA");
		   }else{
				print_r($response);
		   }
    }

}
