<?php

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

use live\Request\V20161101 as live;

class Site extends CI_Controller {

    function __construct() {
        parent::__construct();
		$this->load->helper('curl_function');
    }

    function index() {
		$appid = "wxe5593cc4517e9532";
		 $secret = "c585613b6e0effeb149d49bef30a351d";

		if($this->input->get('code',true))
		{
			$code  = $this->input->get('code',true);
			$requesturl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
            $result = curl($requesturl,'GET','');
            $result = json_decode($result, true);
			if(!isset($result['access_token']))
			{
				 redirect('index.php/site');
			}
			$this->load->model('ser_users');
			//print_r($result);die;
			if($user = $this->ser_users->get_card_no($result['openid']))
			{
                $users = array(
					'cust_code' => $user['cust_code'],
					'card_no' => $user['card_no'],
					'tel1' => $user['tel1'],
				);
				$this->session->set_userdata($users);
				 redirect('index.php/member');
			}
			else
			{
				$this->load->view('front/login',$result);
			}
		}
		else
		{
			//$redirect_uri = "http://www.survvorder.com/lilai";
			$redirect_uri = "http://www.survvorder.com/demo/lilai";
            $redirect_uri = urlEncode($redirect_uri);
            $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	       header("Location: $url");
		}
	
	
        //$this->load->view('front/login');

    }

	function demo()
	{
		$result['access_token'] = "13_XqC5AqhWQbq2LhqPoHAzYb5pq4fKgHrxUqmSsgbl79AF3GATwTrurY9u6I732mi7nD9u1Qc9APeg-OWl-q1sIg";
		$result['openid'] = "o4zwPwsAT6ZRXwBgE-bH5-Wznqys";
		$this->load->view('front/login',$result);
	}

	function del()
	{
		$cust_code = "13311729032";
		    $this->load->model('ser_users');
			$this->ser_users->delete($cust_code);
	}


    function login()
    {
        $phone = $this->input->post('phone',true);
        $code = $this->input->post('code',true);
		$access_token = $this->input->post('access_token',true);
	    $card_no = $this->input->post('card_no',true);

        if (strlen($phone) == 0) {
            buildJSON("",103,'手机号不能为空',null);
        }
        if (strlen($code) == 0) {
            buildJSON("",103,'验证码不能为空',null);
        }

        $this->load->model('ser_users');
        $phone_code = $this->ser_users->phone_code_getOne($phone);
		
        if ($phone_code)
        {
			if($code != $phone_code["code"]) {
				buildJSON("",203,'验证码不正确',null);
			} else {
				if (time() - $phone_code['send_time'] > 60000) {
					buildJSON("",204,'验证码已过期',null);
				}
			}
            
        } else {
            buildJSON("",203,'验证码不正确',null);
        }

        $user =$this->ser_users->getOne($phone);
        if(!$user)
        {
			  //生成获取用户信息的地址
            $getuser = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$card_no.'&lang=zh_CN';
            $info = curl($getuser,'GET','');
            //最后得到$info 数
            $info = json_decode($info, true);
			//print_r($info);die;
            $data = array(
                'cust_code' => $phone,
                //'name1' => $info['nickname'],
				'name1' => null,
                'name2' => null,
                'card_no' => $card_no,
                'tel1 ' => $phone,
				'sex1 ' => $info['sex'],
				'logo ' => $info['headimgurl'],
				'addr1_l1 ' => $info['province'].$info['city'],
                //'cus_type ' => 99,
                'group_no ' => "wechat",
                'disc_id ' => null,
            );
			//print_r($data);die;	
		
            if($this->ser_users->create($data))
            {
                $users = array(
                    'cust_code' => $phone,
                    'card_no' => $card_no,
                    'tel1' => $phone,
                );
                $this->session->set_userdata($users);
                buildJSON("",200,'绑定成功',null);
            }
            else
            {
                buildJSON("",205,'绑定失败',null);
            }
        }
        else
        {
            buildJSON("",205,'该手机已经绑定',null);
        }
    }

    //发送验证码
    function send_code()
    {
        $flag = 0;
        $params='';
        $verify = rand(100000, 999999);//获取随机验证码

        $phone = $this->input->post('phone', TRUE);
        $code_type = $this->input->post('code_type', TRUE);
//        $phone = "13311729032";
//        $code_type = "reg";
        $templates = array(
            "reg" => "$verify(利莱微会员验证码，请完成验证)，如非本人操作，请忽略该短信。",
        );

        if (strlen($phone) == 0) {
            buildJSON("",103,'手机号不能为空',null);
        }
        if (!array_key_exists($code_type,$templates) ) {
            buildJSON("",103,'发送类型不合法',null);
        }

        $argv = array(
            'account'=>'nx-lilai',     //必填参数。用户账号
            'pswd'=>'NXlilai0820',     //必填参数。（web平台：基本资料中的接口密码）
            'msg'=>$templates[$code_type],   //必填参数。发送内容（1-500 个汉字）UTF-8编码
            'mobile'=>$phone,   //必填参数。手机号码。多个以英文逗号隔开
            'product'=>'',    //产品id
            'needstatus'=>'true',  //是否需要状态报告 true需要，false不需要
            'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
        );
        //print_r($argv);exit;
        //构造要post的字符串
        //echo $argv['content'];
        foreach ($argv as $key=>$value) {
            if ($flag!=0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.= urlencode($value);// urlencode($value);
            $flag = 1;
        }

        $data = array(
            'phone' => $phone,
            'code'=>$verify,
            'send_time'=>time(),
        );
        $this->load->model('ser_users');
        if($this->ser_users->phone_code_create($data)) {
            $url = "http://114.55.176.84/msg/HttpSendSM?".$params; //提交的url地址
            $success = curl($url, "GET", "");

            if(strpos($success,',0')) {
                buildJSON("",200,'发送成功',null);
            } else {
                buildJSON("",205,'发送失败',null);
            }
        } else {
            buildJSON("",205,'发送失败',null);
        }
    }

}
