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

class Index extends CI_Controller {
	
	public function __construct() {
        parent::__construct();
		$this->load->model('ding_value_model');
		$this->load->helper('cookie');
	}
	
	public function test_session(){
		$unionid = 'JbHXZ0DtTj2fOwkk4nfLpgiEiE';
		$user = $this->ding_value_model->get_dingding_user($unionid);
		//$this->session->set_userdata('dingdinguserinfo',$user);
		//echo get_cookie('ci_session');
		print_r($this->session->userdata('dingdinguserinfo'));
	}
	
	public function index($unionid = null,$type = null){
		if(get_cookie('dingunionid') == ''){
			redirect('http://www.mycht.cn/info.php/apps/dinglogin/login/?returnurl=http://www.mycht.cn/webht.php/apps/dingmail/index/');
		}else{
			 if($unionid != null && $type != null){
				 $data['type'] = $type;
				 $data['user'] = get_cookie('dingname');
				 $data['user_unionid'] = get_cookie('dingunionid');
				 if($this->ding_value_model->get_dingding_user($unionid) == null){
					 echo '该用户还未登录过，请告知他登录后才能对他点赞或拍砖！<br>';
					 echo '有问题请联系：CYC!';
					 exit;
				 }
				 $data['comment_name'] = $this->ding_value_model->get_dingding_user($unionid)->ddu_Name;
				 $data['comment_unionid'] = $unionid;
				 $data['content'] = $type;
				 $data['mail_identify'] = $this->ding_value_model->get_dingding_user($unionid)->ddu_Sn.'_'.time();
				 $data['createtime'] = time();
				 if($data['user'] == $data['comment_name']){
					 echo '<script>alert("不能对自己点赞或拍砖！")</script>';
					 $this->index($unionid);
				 }else{
					 $obj = $this->ding_value_model->get_user_time($data['comment_unionid'],$data['user_unionid']);
					 $last_time = $obj->ddv_Createtime;
					 $time_diff = ($data['createtime'] - $last_time) / 3600;
					 if($time_diff > 3){
						  $flag = $this->ding_value_model->add_value($data);
						  if(!$flag){
							exit($type.'失败');
						  }else{
							redirect(site_url('apps/dingmail/index/index/'.$unionid));
						  }
					 }else{
						 echo '<script>alert("不能频繁对一个人点赞或拍砖！")</script>';
						 $this->index($unionid);
					 }
				 }
			 }else{
				 //访问自己的主页
				 if($unionid == null){
					 $unionid = get_cookie('dingunionid');
				 }
				 
				 $mdata['user'] = $this->ding_value_model->get_dingding_user($unionid);
				 $mdata['user_unionid'] = $unionid;
				 $mdata['like_count'] = $this->ding_value_model->count_like($unionid);
				 $mdata['unlike_count'] = $this->ding_value_model->count_unlike($unionid);
				 $mdata['whos_like'] = $this->ding_value_model->whos_like($unionid);
				 $mdata['whos_unlike'] = $this->ding_value_model->whos_unlike($unionid);
				 $mdata['all_comment'] = $this->ding_value_model->all_comment($unionid);
				 //print_r($this->session->userdata('dingdinguserinfo'));
				 //如果传入的unionid和cookie的相等就再存一个userinfo的cookie，访问个人主页，反之不存就是访问他人主页
				 if($unionid == get_cookie('dingunionid')){
					 $this->session->set_userdata('dingdinguserinfo', $mdata['user']);
				 }
				 $this->load->view('user',$mdata);
			 }
		}
	 }
	 
	//value邮件页面
	public function mail_index(){
		 if($this->session->userdata('dingdinguserinfo') === false){
			 redirect('http://www.mycht.cn/webht.php/apps/dingmail/index/');
		 }else{
			 //print_r($this->session->userdata('dingdinguserinfo'));
			 $this->load->view('mail');
		 }
	 }
	 
	//发送邮件
	public function send_mail(){
		 if(!$this->input->post('emaillist')){
            echo -1;
            return;			 
		 }
		 $user_info = $this->session->userdata('dingdinguserinfo');
		 $data['mail_content'] = htmlspecialchars($this->input->post('emailcontent'));
         $data['mail_fromuser'] = $user_info->ddu_Name;
         $data['mail_subject'] = $this->input->post('mail_subject');
         $data['mail_touser'] = $this->input->post('emaillist');
         $data['mail_ccuser'] = $this->input->post('cs_emaillist');
         $data['mail_value_key'] = $this->input->post('whm_value_key');
         $data['mail_createtime'] = time();
         $data['mail_identify'] = $user_info->ddu_Sn.'_' . time();
		 $ddm_id = $this->ding_value_model->add_mail($data);
		 //邮件所有人，如果是value邮件，则属于被value的人，如果不是，则属于发邮件的人
         if ($this->input->post('whum_value_user')) {
            $value_user_array = explode(';', $this->input->post('whum_value_user'));
            foreach ($value_user_array as $vu) {
                if (!empty($vu)) {
                    $vudata['value_user_name'] = $vu;
                    $vudata['value_user_identify'] = $data['mail_identify'];
                    $vudata['value_user_createtime'] = $data['mail_createtime'];
                    $ddum_id = $this->ding_value_model->add_value_user($vudata);
                }
            }
         } else {
            $vudata['value_user_name'] = '陈宇超';//$user_info->ddu_Name;
            $vudata['value_user_identify'] = $data['mail_identify'];
            $vudata['value_user_createtime'] = $data['mail_createtime'];
            $ddum_id = $this->ding_value_model->add_value_user($vudata);
         }
		 
         //收件人
		 $tostring = '';
         
		 $tostring = substr($data['mail_touser'],0,-1);
		 $tostring = "'".$tostring."'";
		 
		 if(!empty($tostring)){
			 $tomail = $this->ding_value_model->all_email($tostring)['0']->ddu_Email;
		 }else{
			 $tomail = null;
		 }

		$mailheader = '<p style="font-size:20px">FROM:'.$user_info->ddu_Name.'</p><br>';
		$mailbody = '<div style="overflow:hidden"> 
						<a style="height:auto;text-decoration: none;" href="http://' . $_SERVER['HTTP_HOST'] . '/webht.php/apps/dingmail/index/like/' . $data['mail_identify'] . '/like" > 
						<img src="http://' . $_SERVER['HTTP_HOST'] . '/css/images/like.png" /> 
						</a> 
						<a style="height:auto;text-decoration: none;" href="http://' . $_SERVER['HTTP_HOST'] . '/webht.php/apps/dingmail/index/like/' . $data['mail_identify'] . '/unlike" > 
						<img src="http://' . $_SERVER['HTTP_HOST'] . '/css/images/unlike.png" />
						</a> 
				   </div>';		
		
		$fromuser = $user_info->ddu_Name;
		$subject = $this->input->post('mail_subject');
		
		//是否为value邮件，如果不是value邮件，不在邮件下放置点赞按钮
		if($this->input->post('whum_value_user')){
			$body = $mailheader.$this->input->post('emailcontent').$mailbody;
		}else{
			$body = $mailheader.$this->input->post('emailcontent');
		}
		
		//提交到其他服务器发送
		$url = 'https://cht.mycht.cn/webht.php/apps/dingmail/index/do_sendmail/';
		$post_data = array();
		$post_data['tomail'] = $tomail;
		$post_data['subject'] = $subject;
		$post_data['mailbody'] = $body;
		$flag = $this->GetPost_http($url,$post_data);
		
		if (!$flag) {
			$result = 0; //"邮件发送有误: " . $mail->ErrorInfo;
		} else {
			//是value邮件的话，默认发送人点赞
			if ($this->input->post('whum_value_user')) {
				$obj = explode(';', $this->input->post('whum_value_user'));
				foreach(array_filter($obj) as $value){
					$data['comment_name'] = $value;
					$data['comment_unionid'] = $this->ding_value_model->get_dingding_unionid($data['comment_name'])->ddu_Unionid;
					$data['type'] = 'like';
					$data['mail_identify'] = $data['mail_identify'];
					$data['user'] = $user_info->ddu_Name;
					$data['user_unionid'] = $user_info->ddu_Unionid;
					$data['content'] = $this->ding_value_model->get_mail($data['mail_identify'])->ddm_Content;
					$data['createtime'] = time();
					$whc_id = $this->ding_value_model->add_value($data);
				}
			}
			$result = 1;
		}
		echo $result;
		return;
	}
	 
	//ajax发送邮件
	public function ajax_sendmail(){
		header('Access-Control-Allow-Origin:*');
	    header('Access-Control-Allow-Methods:POST, GET');
	    header('Access-Control-Max-Age:0');
	    header('Access-Control-Allow-Headers:x-requested-with, Content-Type');
	    header('Access-Control-Allow-Credentials:true');
		
		$data = array();
		$data['position'] = $this->input->get_post('position');
		$data['phone'] = $this->input->get_post('phone');
	
		$data['name'] = $this->input->get_post('name'); 
		$data['sex'] = $this->input->get_post('sex');
		// $data['email'] = $this->input->get_post('email');
		// $data['school'] = $this->input->get_post('school');
		// $data['education'] = $this->input->get_post('education');
		// $data['currentcompany'] = $this->input->get_post('currentcompany');
		// $data['from_time'] = $this->input->get_post('from_time');
		// $data['to_time'] = $this->input->get_post('to_time');
		
		$mailnody = '';
		$mailnody .= '应聘职位：'.$data['position'].'<br>';
		$mailnody .= '手机号码：'.$data['phone'].'<br>';
		
		$mailnody .= '姓名：'.$data['name'].'<br>';
		if($data['sex'] == 0){
			$data['sex'] = '女';
		}else{
			$data['sex'] = '男';
		}
		// $mailnody .= '电子邮箱：'.$data['email'].'<br>';
		// $mailnody .= '性别：'.$data['sex'].'<br>';
		// $mailnody .= '毕业院校：'.$data['school'].'<br>';
		// $mailnody .= '最高学历：'.$data['education'].'<br>';
		// $mailnody .= '当前公司：'.$data['currentcompany'].'<br>';
		// $mailnody .= '任职时间开始：'.$data['from_time'].'<br>';
		// $mailnody .= '任职时间结束：'.$data['to_time'].'<br>';
		
		$post_data = array();
		$post_data['tomail'] = 'hr@chinahighlights.net';
		$post_data['subject'] = '应聘简历';
		$post_data['mailbody'] = $mailnody;
		$flag = $this->GetPost_http($url,$post_data);
		
		if($flag){
			echo '{"status":1}';
		}else{
			echo '{"status":0}';
		}
	}
	 
	//执行邮件发送功能
	public function do_sendmail() {
		header('Access-Control-Allow-Origin:*');
	    header('Access-Control-Allow-Methods:POST, GET');
	    header('Access-Control-Max-Age:0');
	    header('Access-Control-Allow-Headers:x-requested-with, Content-Type');
	    header('Access-Control-Allow-Credentials:true');
		
		require 'email.class.php';
		$tomail = $this->input->get_post('tomail');
		$mailsubject = $this->input->get_post('subject');
		$mailbody = $this->input->get_post('mailbody');
		
		$smtpserver     = "smtp.qiye.aliyun.com";
		$smtpserverport = 25;
		$smtpusermail   = "admin@hainatravel.com";
		// 发件人的账号，填写控制台配置的发信地址,比如xxx@xxx.com
		$smtpuser       = "admin@hainatravel.com";
		// 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置)
		$smtppass       = "Guilinhaina2019";
		$mailsubject    = "=?UTF-8?B?" . base64_encode($mailsubject) . "?=";
		$mailtype       = "HTML";
		//可选，设置回信地址
		$smtpreplyto    = "***";
		$smtp           = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);
		$smtp->debug    = true;
		$cc   ="";
		$bcc  = "";
		$additional_headers = "";
		//设置发件人名称，名称用户可以自定义填写。
		$sender  = "value系统";
		$smtp->sendmail($tomail,$smtpusermail, $mailsubject, $mailbody, $mailtype, $cc, $bcc, $additional_headers, $sender, $smtpreplyto);
    }
	
	//钉邮群体点赞功能
	public function like($identify = null,$type = null){
		if($this->session->userdata('dingdinguserinfo') === false){
			$this->session->set_userdata('identify',$identify);
			$this->session->set_userdata('mail_type',$type);
			redirect('http://www.mycht.cn/webht.php/apps/dingmail/index/');
		}else{
			$user_info = $this->session->userdata('dingdinguserinfo');
			if(!empty($user_info)){
				$data['user'] = $user_info->ddu_Name;
				if(($type == 'like' || $type == 'unlike') && $identify){
					$data['type'] = $type;
					$data['mail_identify'] = $identify;
					$data['user_unionid'] = $user_info->ddu_Unionid;
					$has_like = $this->ding_value_model->is_liked($data);
					if(!$has_like){
						$data['createtime'] = time();
						$data['content'] = $this->ding_value_model->get_mail($data['mail_identify'])->ddm_Content;
						$data['comment_name'] = 'value邮件';
						$data['comment_unionid'] = $this->ding_value_model->get_mail($identify)->ddm_Sn;
						//对邮件点赞
						$whc_id = $this->ding_value_model->add_value($data);
					}
					//对value对象点赞
					$valuedata['type'] = $type;
					$valuedata['mail_identify'] = $identify;
					$valuedata['user'] = $user_info->ddu_Name;
					$valuedata['user_unionid'] = $user_info->ddu_Unionid;
					$valuedata['createtime'] = time();
					$valuedata['content'] = $this->ding_value_model->get_mail($identify)->ddm_Content;
					$obj = $this->ding_value_model->get_value($identify,$valuedata['user_unionid']);
					if(!empty($obj)){
						//这里没有判空
						foreach($obj as $value){
							
							$valuedata['comment_name'] = $value->ddum_Name;
							$valuedata['comment_unionid'] = $value->ddu_Unionid;
							$obj = $this->ding_value_model->get_user_time($valuedata['comment_unionid'],$valuedata['user_unionid'],$identify);
							if($obj){
								$last_time = $obj->ddv_Createtime;
							}else{
								$last_time = 0;
							}
							$time_diff = ($valuedata['createtime'] - $last_time) / 3600;
							if($time_diff > 100000){
								$flag = $this->ding_value_model->add_value($valuedata);
								
								if(!$flag){
									continue;
								}
								
							 }else{
								 echo '<script>alert("你已经对这封邮件的value对象点过赞或拍砖了！")</script>';
							}
						}
						//sleep(3);
						//redirect(site_url('apps/dingmail/index/like/'.$identify));
					}
					
				}
			}
			$tpldata['value_mail'] = $this->ding_value_model->get_mail($identify);
			$tpldata['whos_like'] = $this->ding_value_model->value_whos_like($identify);
			$tpldata['whos_unlike'] = $this->ding_value_model->value_whos_unlike($identify);
			$this->load->view('like',$tpldata);
		}
	}
	
	//增加评论
	public function add_comment(){
		$data = array();
		if($this->input->post('hidden_name')){
			$data['user'] = '猜猜我是谁';
			$data['user_unionid'] = 'xxxxxxx';
			$data['type'] = 'hidden_comment';
		}else{
			$data['user'] = $this->session->userdata('dingdinguserinfo')->ddu_Name; 
			$data['user_unionid'] = $this->session->userdata('dingdinguserinfo')->ddu_Unionid;
			$data['type'] = 'comment';
		}
		
		$data['comment_name'] = $this->input->post('user_name');
		$data['comment_unionid'] = $this->input->post('user_unionid'); 
		$data['content'] = str_replace(PHP_EOL, '', $this->input->post('comment'));
		
		$data['createtime'] = time();
		$data['mail_identify'] = $this->input->post('user_sn').'_'.$data['createtime'];
		
		$obj = $this->ding_value_model->get_last_comment($data['comment_name'],$data['comment_unionid']);

		if(empty($obj)){
			$time = 0;
		}else{
			$time = $obj[0]->ddv_Createtime;
		}
		
		$tolist_array = $this->ding_value_model->all_email("'".$data['comment_name']."'");
		$difftime = time() - $time;
		if($difftime / 3600 > 24){
			$this->do_sendmail($data['user'], $tolist_array, null, '今天有人评论你了哟！', '快去看看吧：http://www.mycht.cn/webht.php/apps/dingmail/index/index/'.$data['comment_unionid']);
		}
		
		$comment_id = $this->ding_value_model->add_value($data);
		
		echo $comment_id;
	}
	
	public function test(){
		$this->ding_value_model->test();
	}
	
	//点赞排行榜	
	public function rank_person() {
        if($this->session->userdata('dingdinguserinfo') === false){
			redirect('http://www.mycht.cn/webht.php/apps/dingmail/index/');
		}else{
			$data = array();
			$user_info = $this->session->userdata('dingdinguserinfo');
			if (!empty($user_info)) {
				$data['uname'] = $user_info->ddu_Name;
			}
			//$data['current_user'] = $current_user;
			//周榜
			$monday = strtotime('this week');
			$sunday = strtotime('last day this week +7 day');
			$data['rank_week'] = $this->ding_value_model->get_person_rank($monday, $sunday);
			
			//月榜
			$from_date = strtotime(date('Y-m-01', time()));
			$firstday = date('Y-m-01', time());
			$to_date = strtotime("$firstday +1 month -1 day");
			$data['rank_month'] = $this->ding_value_model->get_person_rank($from_date, $to_date);
			//年榜
			$year_start = strtotime(date('Y-01-01', time()));
			//echo strtotime(date('2017-12-31', time()));
			
			//$year_start = strtotime(date('2016-01-01'));
			$year_end = strtotime(date('Y-12-31', time()));
			//$year_end = strtotime(date('2016-12-31'));
			$data['rank_year'] = $this->ding_value_model->get_person_rank($year_start, $year_end);
			//获取全年点赞次数
			$data['click_like'] = $this->ding_value_model->get_click_liek($year_start, $year_end);

			$this->load->view('rank_person',$data);
		}
    }
	
	//钉钉扫码登录
	public function auth_login(){
		//获取code
		$code = $_REQUEST['code'];
		//请求access_token,并且打印出来
		$url = 'https://oapi.dingtalk.com/sns/gettoken?appid=dingoagxeeheunc0p95eu8&appsecret=R3fhIY1zWw5wJZNWeszXg0VNpxzU5i95T4tUuboTQBEWAaQyg3mGC-ssskeyt9DY';
		$access_token = json_decode($this->get_http($url,$data = '',$method = 'GET'));
		//请求接口获取persistent_code
		$url_info = 'https://oapi.dingtalk.com/sns/get_persistent_code?access_token='.$access_token->access_token;
		$tmp_auth_code = '{"tmp_auth_code":"'.$code.'"}';
		$info = json_decode($this->get_http($url_info,$data = $tmp_auth_code,$method = 'POST'));
		//请求sns_token
		$url_sns = 'https://oapi.dingtalk.com/sns/get_sns_token?access_token='.$access_token->access_token;
		$sns_code = '{"openid":"'.$info->openid.'","persistent_code":"'.$info->persistent_code.'"}';
		$sns_token = json_decode($this->get_http($url_sns,$sns_code,$method = 'POST'));
		//获取个人信息
		$url_person = 'https://oapi.dingtalk.com/sns/getuserinfo?sns_token='.$sns_token->sns_token;
		$person = json_decode($this->get_http($url_person,$data = '',$method = 'GET'));
		$unionid = $person->user_info->unionid;
		$username = $person->user_info->nick;
		$check_login = $this->ding_value_model->get_dingding_user($unionid);
		if(!$check_login){
			$data = $this->get_user_info($unionid);
			$flag = $this->ding_value_model->add_dingding_user($data['ddu_Name'],$data['ddu_Unionid'],$data['ddu_Mobile'],$data['ddu_Email'],$data['ddu_Position'],$data['ddu_Avatar'],$data['ddu_Datetime']);
			if(!$flag){
					exit('新增用户失败！');
				}else{
					$user_info = $this->ding_value_model->get_dingding_user($data['ddu_Unionid']);
					$this->session->set_userdata('dingdinguserinfo',$user_info);
					if($this->session->userdata('unionid') && $this->session->userdata('type')){
						redirect(site_url('apps/dingmail/index/index/'.$this->session->userdata('unionid').'/'.$this->session->userdata('type')));
					}elseif($this->session->userdata('identify') && $this->session->userdata('mail_type')){
						redirect(site_url('apps/dingmail/index/like/'.$this->session->userdata('identify').'/'.$this->session->userdata('mail_type')));
					}else{
						redirect(site_url('apps/dingmail/index/index/'.$user_info->ddu_Unionid));
					}
				}
		}
		$now_time = time();
		if($check_login->ddu_Datetime == null){
			$check_login->ddu_Datetime = 0;
		}
		$last_time = $check_login->ddu_Datetime;
		$time_diff = ($now_time - $last_time) / 86400;
		if($time_diff > 30){
			$data= $this->get_user_info($unionid);
			$this->ding_value_model->update_dingding_user($data['ddu_Name'],$data['ddu_Unionid'],$data['ddu_Mobile'],$data['ddu_Email'],$data['ddu_Position'],$data['ddu_Avatar'],$data['ddu_Datetime']);
			$check_login = $this->ding_value_model->get_dingding_user($unionid);
		}
		$this->session->set_userdata('dingdinguserinfo', $check_login);
		if($this->session->userdata('unionid') && $this->session->userdata('type')){
			redirect(site_url('apps/dingmail/index/index/'.$this->session->userdata('unionid').'/'.$this->session->userdata('type')));
		}elseif($this->session->userdata('identify') && $this->session->userdata('mail_type')){
			redirect(site_url('apps/dingmail/index/like/'.$this->session->userdata('identify').'/'.$this->session->userdata('mail_type')));
		}else{
			redirect(site_url('apps/dingmail/index/index/'.$check_login->ddu_Unionid));
		}
		
	}
	
	//通过钉钉获取用户详细信息
	public function get_user_info($unionid){
		//公司的access_token.
		//unionid是通过扫码获取到
		//获取公司access_token，用access_token和unionid获取userid，利用userid获取成员详细信息。
		$url_access_token = 'https://oapi.dingtalk.com/gettoken?corpid=ding48bce8fd3957c96b&corpsecret=4I_TlkOUtWQ60tUYX_447WXM5mNX41q_Q03xtZJgvBOzMPzGbNKZZz_Bsv-0B9I1';
		$company_info = json_decode($this->get_http($url_access_token,$data='',$method='GET'));
		$url_unionid = 'https://oapi.dingtalk.com/user/getUseridByUnionid?access_token='.$company_info->access_token.'&unionid='.$unionid;
		$userid = json_decode($this->get_http($url_unionid,$data='',$method='GET'));
		$url_userid = 'https://oapi.dingtalk.com/user/get?access_token='.$company_info->access_token.'&userid='.$userid->userid;
		$person_details = json_decode($this->get_http($url_userid,$data='',$method='GET'));
		$data['ddu_Name'] = $person_details->name;
		$data['ddu_Unionid'] = $person_details->unionid;
		$data['ddu_Mobile'] = $person_details->mobile;
		$data['ddu_Email'] = $person_details->orgEmail;
		$data['ddu_Position'] = $person_details->position;
		$data['ddu_Avatar'] = $person_details->avatar;
		$data['ddu_Datetime'] = time();
		return $data;
	}
		
	//发送请求
	public function get_http($url, $data = '', $method = 'GET') {
		$curl = curl_init(); // 启动一个CURL会话  
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在  
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
		if ($method == 'POST' && !empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
		}
		curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环  
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
		$tmpInfo = curl_exec($curl); // 执行操作  
		$errno = curl_errno($curl);
		if ($errno !== 0) {
			return false;
			echo $errno . curl_error($curl); //记录错误日志
		}
		curl_close($curl); //关闭CURL会话  
		return $tmpInfo; //返回数据
	}
	
	public function GetPost_http($url, $data = '',$format='') {
		if(!isset($_SERVER['HTTP_USER_AGENT'])){
			$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400';
		}
		$curl = curl_init(); // 启动一个CURL会话  
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在  
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
			if($format == 'json'){
				curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
			}
		}
		curl_setopt($curl, CURLOPT_TIMEOUT, 40); // 设置超时限制防止死循环  
		curl_setopt($curl, CURLOPT_TIMEOUT_MS, 40000); // 设置超时限制防止死循环  
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
		$tmpInfo = curl_exec($curl); // 执行操作  
		$errno = curl_errno($curl);
		if ($errno !== 0) {
			log_message('error', 'ctripost'.$errno.curl_error($curl));
		}
		curl_close($curl); //关闭CURL会话  
		return $tmpInfo; //返回数据
	}

	//自动提示
	public function get_user_list(){
		$q = $this->input->get('q');
        $str_array = explode(';', $q);
        $q = end($str_array);
        if (!$q)
            return;

        $showcount = 1;
        $tmp = $this->ding_value_model->all_email();
        foreach ($tmp as $value) {
            if ($showcount > 8)
                break;
            if (strstr($value->ddu_Name, $q)) {
                echo $value->ddu_Name . ';' . "\n";
                $showcount++;
            }
        }
	}
	
	//检测是否有value
	public function check_value_user() {
		$value_user_array = explode(';', $this->input->post('value_user'));
		foreach ($value_user_array as $vu) {
		if (!empty($vu)) {
			$result = $this->ding_value_model->has_user($vu);
			if (empty($result)) {
				echo 0;
				return;
				}
			}
		}
		echo 1;
		return;
    }
	
	public function upload_photos() {
        $save_path = date('Y-m-d');
        $jsfunction = 'get_photo_url';
        $upload_id = 'Profile_file';
        $config['upload_path'] = APPPATH . 'upload/' . $save_path;
        if (!is_dir($config['upload_path'])) {
            @mkdir($config['upload_path'], 0777, true);
        }
        $config['allowed_types'] = 'gif|jpg|png';
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);
        if (!$this->upload->do_upload($upload_id)) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);
        } else {
            $data = array('upload_data' => $this->upload->data());
            $file_name = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $config['upload_path'] . '/' . $data['upload_data']['file_name'];
            echo "<script>parent.$jsfunction('$file_name');</script>";
        }
    }
	
	//退出
	public function logout(){
        $this->session->unset_userdata('dingdinguserinfo');
		$this->session->unset_userdata('unionid');
		$this->session->unset_userdata('type');
		$this->session->unset_userdata('identify');
		$this->session->unset_userdata('mail_type');
        $this->input->set_cookie('userdata', '', '');
		delete_cookie('dingunionid');
		delete_cookie('dingname');
        redirect(site_url('apps/dingmail/index/index/'));
    }
	
	public function valuemail_list(){
		header("Content-type:text/html;charset=utf-8");
		$data = $this->ding_value_model->get_valuemail_list();
		for($i=0;$i<count($data);$i++){
			echo '<h2>时间：'.date('y-m-d',$data[$i]->ddm_Createtime).'</h2><br>';
			echo '<h2>标题：</h2>'.$data[$i]->ddm_Subject.'<br>';
			echo '<h2>value邮件内容：</h2>'.htmlspecialchars_decode($data[$i]->ddm_Content).'<br>';
			echo '<hr/>';
		}
		
	}
	
	//查询那条value使用的次数最多
	public function count_valueitems(){
		//获取所有的item条目
		$obj = $this->ding_value_model->get_allvalueitems();
		//定义变量存储数据
		$data = array();
		$data['team1_cn'] = '心存谦卑，发现并欣赏他人的长处';
		$data['team2_cn'] = '人比事更重要，爱能包容一切过错';
		$data['team3_cn'] = '相信一群平凡的人，能组成一个不平凡的团队';
		$data['team4_cn'] = '人人平等，在爱里说诚实话';	
		$data['team1_num'] = 0;$data['team2_num'] = 0;$data['team3_num'] = 0;$data['team4_num'] = 0;
		
		$data['chengxin1_cn'] = '行真善美，恨不义财';
		$data['chengxin2_cn'] = '诚实可信，说到做到，不隐藏真相';
		$data['chengxin3_cn'] = '做人一诺千金，做事全力以赴';
		$data['chengxin4_cn'] = '勇于承担责任使你更优秀';
		$data['chengxin1_num'] = 0;$data['chengxin2_num'] = 0;$data['chengxin3_num'] = 0;$data['chengxin4_num'] = 0;
		
		$data['customer1_cn'] = '穿客户的鞋，客户是我们最好的老师';
		$data['customer2_cn'] = '细节展现专业，多走一里路';
		$data['customer3_cn'] = '客户的独特性就是我们存在的理由';
		$data['customer4_cn'] = '不让一点瑕疵破坏客人一生中唯一的旅程，一眚能掩大德';
		$data['customer1_num'] = 0;$data['customer2_num'] = 0;$data['customer3_num'] = 0;$data['customer4_num'] = 0;
		
		$data['discovery1_cn'] = '好奇心，好头脑风暴';
		$data['discovery2_cn'] = '第一个行动的，失败了也光荣；行动太迟，正确的决策也可能变成错误';
		$data['discovery3_cn'] = '以往的成功经验未必是今天问题的解决方案';
		$data['discovery4_cn'] = 'Do Without，自己创造条件达到目标';
		$data['discovery1_num'] = 0;$data['discovery2_num'] = 0;$data['discovery3_num'] = 0;$data['discovery4_num'] = 0;
		
		foreach ($obj as $item){
			$items = explode(',',$item->ddm_value_key);
			foreach($items as $value){
				if(!empty($value)){
					switch ($value){
						case 'team1':
							$data['team1_num']++;
							break;
						case 'team2':
							$data['team2_num']++;
							break;
						case 'team3':
							$data['team3_num']++;
							break;
						case 'team4':
							$data['team4_num']++;
							break;
						case 'chengxin1':
							$data['chengxin1_num']++;
							break;
						case 'chengxin2':
							$data['chengxin2_num']++;
							break;
						case 'chengxin3':
							$data['chengxin3_num']++;
							break;
						case 'chengxin4':
							$data['chengxin4_num']++;
							break;	
						case 'customer1':
							$data['customer1_num']++;
							break;
						case 'customer2':
							$data['customer2_num']++;
							break;
						case 'customer3':
							$data['customer3_num']++;
							break;
						case 'customer4':
							$data['customer4_num']++;
							break; 	
						case 'discovery1':
							$data['discovery1_num']++;
							break;
						case 'discovery2':
							$data['discovery2_num']++;
							break;
						case 'discovery3':
							$data['discovery3_num']++;
							break;
						case 'discovery4':
							$data['discovery4_num']++;
							break; 		
					}
				}
			}
		}
		
		//输出内容
		echo '使用条目:'.$data['team1_cn'].' | 使用次数:'.$data['team1_num'].'<br>'; 
		echo '使用条目:'.$data['team2_cn'].' | 使用次数:'.$data['team2_num'].'<br>'; 
		echo '使用条目:'.$data['team3_cn'].' | 使用次数:'.$data['team3_num'].'<br>'; 
		echo '使用条目:'.$data['team4_cn'].' | 使用次数:'.$data['team4_num'].'<br>'; 
		echo '使用条目:'.$data['chengxin1_cn'].' | 使用次数:'.$data['chengxin1_num'].'<br>';
		echo '使用条目:'.$data['chengxin2_cn'].' | 使用次数:'.$data['chengxin2_num'].'<br>'; 
		echo '使用条目:'.$data['chengxin3_cn'].' | 使用次数:'.$data['chengxin3_num'].'<br>'; 
		echo '使用条目:'.$data['chengxin4_cn'].' | 使用次数:'.$data['chengxin4_num'].'<br>'; 
		echo '使用条目:'.$data['customer1_cn'].' | 使用次数:'.$data['customer1_num'].'<br>';
		echo '使用条目:'.$data['customer2_cn'].' | 使用次数:'.$data['customer2_num'].'<br>'; 
		echo '使用条目:'.$data['customer3_cn'].' | 使用次数:'.$data['customer3_num'].'<br>'; 
		echo '使用条目:'.$data['customer4_cn'].' | 使用次数:'.$data['customer4_num'].'<br>'; 
		echo '使用条目:'.$data['discovery1_cn'].' | 使用次数:'.$data['discovery1_num'].'<br>';
		echo '使用条目:'.$data['discovery2_cn'].' | 使用次数:'.$data['discovery2_num'].'<br>'; 
		echo '使用条目:'.$data['discovery3_cn'].' | 使用次数:'.$data['discovery3_num'].'<br>'; 
		echo '使用条目:'.$data['discovery4_cn'].' | 使用次数:'.$data['discovery4_num'].'<br>'; 
		
	}
	
	public function ajax_get_data(){
		header("Content-Type: text/html;charset=utf-8");
		$from_time = $this->input->get_post('from_time');
		$to_time = $this->input->get_post('to_time');
		$type = $this->input->get_post('type');
		
		if($type == 'week'){
			$from_time = strtotime($from_time);
			$to_time = strtotime($to_time);
		}else if($type == 'month'){
			$firstday = $from_time;
			$from_time = strtotime($from_time);
			$to_time = strtotime("$firstday +1 month -1 day");
		}else if($type == 'year'){
			$from_time = strtotime($from_time);
			$to_time = strtotime($to_time);
		}
		
		$rank_data = $this->ding_value_model->get_person_rank($from_time, $to_time);
		
		$return_html = '';
		foreach($rank_data as $key=>$value){
			$return_html .= '<li class="col-xs-24 nopadding">';
			$num = $key+1;
			$return_html .= '<span class="text-danger'.$num.'">No.'.$num.'</span> ';
			$return_html .= '<span><a href="'.site_url('apps/dingmail/index/index/'.$value->ddv_Comment_Unionid).'">'.$value->ddv_Comment_Name.'</a></span>';
		    $return_html .= '<span class="badge pull-right">'.$value->like_count.' like</span></li>'; 		  	
		}
		print_r($return_html);
	}
	
	public function delete_value($sn=null){
		if(empty($sn)){
			exit('传参错误');
		}else{
			$this->ding_value_model->delete_value($sn);
		}
		
	}
}


?>