<?php
namespace Common\Controller;

use Think\Controller;
use Org\XiguSDK\Xigu;
use Think\Exception;

/**
 * 短信类
 * @author  鹿文学
 */
class SmsController extends Controller {
	
	private $prefix = ''; /*session前缀*/

	private static $count_down = 1; /*倒计时时间(分钟)*/

  private static $minute_cn = ['零','一','两','三','四','五','六','七','八','九','十'];
	
	/**
	 * 构造函数
	 * @param  array 		$config 	    配置
     *   配置  string        prefix          session_name 前缀
     *   配置  boolean 		use_module  	是否强制使用模型名作前缀,true强制使用,false不使用
     *   配置  integer 		count_down      倒计时时间(分钟)
	 * @author 鹿文学
	 */
	public function __construct($config=null) {

		if(!empty($config)) {
            if($config['use_module']) {
                $this->prefix = strtolower(MODULE_NAME) . '_';
            } else {
                $this->prefix = $config['prefix']?(strtolower($config['prefix']) . '_'):'';
            }
            self::$count_down = $config['count_down'];
        }
	}
	
	/**
	 * 初始化系统配置
	 * @author 鹿文学
	 */
	protected function _initialize(){

			$config = api('Config/lists');

			C($config); 

	}

    /**
     * @函数或方法说明
     * @发送拉黑信息
     * @param string $phone
     * @param string $user_account
     *
     * @author: 郭家屯
     * @since: 2019/5/6 9:08
     */
	public function send_sms_block($phone='',$user_account=''){
        if (empty($phone)) {
            return false;
        }
        $sms_model = M('Short_message');
        $data = array(
                'pid'=>0,
                'phone'=>$phone,
                'create_time'=>time(),
        );

        $sms_id = $sms_model->add($data);
        if(get_tool_status('sms_set')) {
            $xigu = new Xigu(C('sms_set.smtp'));

            $result = json_decode($xigu->sendSMMessage(C('sms_set.smtp_account'),$phone,C('sms_set.smtp_port'),$user_account),true);

            if ($result['send_status'] == '000000') {
                /* 存储到数据库 */
                $result['send_status'] = '000000';
                $result['phone'] = $phone;
                $result['create_time'] = time();
                $result['pid']=0;
                $result['create_ip']=get_client_ip();
                if($sms_id>0) {
                    $map['id'] = $sms_id;
                    $sms_model->where($map)->save($result);
                } else {
                    $sms_model->add($result);
                }
            }
            return true;

        }
    }

    /**
     * 发送短信验证码
     * @param  string $phone 手机号
     * @param  integer $delay 数据有效时间段,默认10分钟
     * @param  boolean $flag 是否ajax返回,默认true ajax返回
     * @param  integer $pid 渠道编号,默认0 官方渠道
     * @return mixed
     * @author 鹿文学
     */
	public function send_sms_code($phone='',$delay=10,$flag=true,$pid=0) {

		if (empty($phone)) {
			
			$sms_return = ['code'=>1001,'msg'=>'数据不能为空'];
			
		} else {
			
			$session_name = $this->prefix . $phone;

			$sms_model = M('Short_message');

			/*检查数据库中的此号码最新一条记录是否存在,存在是否间隔超过几分钟*/
			$data_code = $sms_model->field('max(create_time) as time')->where(['pid'=>$pid,'phone'=>$phone])->order('create_time desc')->find();
			
			if(!empty($data_code) && ((time() - $data_code['time'])/60 < self::$count_down) ) {
				
				$sms_return = ['code'=>1139,'msg'=>'请'.self::$minute_cn[self::$count_down].'分钟后再次尝试'];
				
			} else {

				$sms_code = session($session_name);
				/*检查session中是否存在有效分钟内的短信验证码信息,有则直接使用,无需生成新的验证码*/
				if($sms_code && (time()-$sms_code['time'])/60<$sms_code['delay']) {

						$rand = $sms_code['code'];
						
						$new_rand = false;

				} else {

						session($session_name,null);

						$rand = rand(100000,999999);
						
						$new_rand = true;

				}

        $param = $rand.",".$delay;
				
				$data = array(
					'pid'=>$pid,
					'phone'=>$phone,
					'create_time'=>time(),
				);
				
				$sms_id = $sms_model->add($data);
				if(get_tool_status('sms_set')) {
					
					$this->check_sms($phone,C('sms_set.limit'),true,$pid);
					
					$xigu = new Xigu(C('sms_set.smtp'));
					
					$result = json_decode($xigu->sendSM(C('sms_set.smtp_account'),$phone,C('sms_set.smtp_port'),$param),true);
					
					
					if ($result['send_status'] != '000000') {
						file_put_contents(dirname(__FILE__).'/'.date('Ymd').'sms.log', date('Y-m-d H:i:s') . ' ---- ' . json_encode($result) . PHP_EOL, FILE_APPEND);
						$sms_return = ['code'=>1010,'msg'=>'发送失败,请重新获取'];
					}
					
				} elseif(get_tool_status("alidayu")) {
					
					$this->check_sms($phone,C('alidayu.limit'),true,$pid);
						
					$xigu = new Xigu('alidayu');
						
					$result = $xigu->alidayu_send($phone,$rand,$delay);
					
					$result['send_time'] = time();
						
					if($result == false) {
						
						$sms_return = ['code'=>1010,'msg'=>'发送失败,请重新获取'];
						
					}
					
				} elseif(get_tool_status('jiguang')) {
					
					$this->check_sms($phone,C('jiguang.limit'),true,$pid);
					
					$xigu = new Xigu('jiguang');
					
					$result = $xigu->jiguang($phone,$rand,$delay);
					
					$result['send_time'] = time();
					
					if($result == false) {
						
						$sms_return = ['code'=>1010,'msg'=>'发送失败,请重新获取'];
						
					}
				} elseif(get_tool_status('alidayunew')) {
					
					$this->check_sms($phone,C('alidayunew.limit'),true,$pid);
					
					$xigu = new Xigu('alidayunew');
					
					$result = $xigu->alidayunew_send($phone,$rand,$delay);
					
					$result['send_time'] = time();
					
					if($result == false) {
						
						$sms_return = ['code'=>1010,'msg'=>'发送失败,请重新获取'];
						
					}
						
				} else {
					
					$sms_return = ['code'=>1008,'msg'=>'没有配置短信发送'];
					
				}
				
				if(empty($sms_return)) {
					
					/* 存储到数据库 */
					$result['send_status'] = '000000';
					$result['phone'] = $phone;
					$result['create_time'] = time();
					$result['pid']=$pid;
					$result['create_ip']=get_client_ip();
					
					if($sms_id>0) {
						$map['id'] = $sms_id;
            $sms_model->where($map)->save($result);
					} else {
						$sms_model->add($result);
					}
					
					/* 记录短信发送记录用于验证 */
					$safe_code['code']=$rand;
					$safe_code['phone']=$phone;
					$safe_code['time']=$new_rand?time():$sms_code['time'];
					$safe_code['delay']=$delay;
					$safe_code['create']=$result['create_time'];
					session($session_name,$safe_code);

					$sms_return = ['code'=>200,'msg'=>'验证码已发送,请查收','data'=>$safe_code];
					
				}
				
			}			
			
		}


		if ($flag) {
			
			echo json_encode($sms_return);exit;
			
		} else {
			
			return $sms_return;
			
		}
		
	}	
		
		
	/**
	 * 验证短信验证码
	 * @param  string 		$phone 			手机号
	 * @param  string 		$vcode  		要验证的验证码
	 * @param  boolean 		$flag  			是否ajax返回,默认true ajax返回
	 * @param  boolean 		$destroy  	是否销毁session,默认true 销毁
	 * @return mixed
	 * @author 鹿文学
	 */
	public function verify_sms_code($phone,$vcode,$flag=true,$destroy=true) {
		
		$session_name = $this->prefix . $phone;
		
		$safe_code = session($session_name);
		
		if(empty($safe_code)) {
			
			$sms_return = ['code'=>1020,'msg'=>'请先获取验证码'];
			
		} else {
			
			$time = (time() - $safe_code['time'])/60;
			
			if ($time<=$safe_code['delay']) {
				
				if (($safe_code['code'] == $vcode) && ($safe_code['phone'] == $phone)) {
					
					unset($safe_code);
					
					if($destroy) {
						
						session($session_name,null);
						
						$sms_return = ['code'=>200,'msg'=>''];
						
					} else {
						
						$sms_return = ['code'=>200,'msg'=>'','session_name'=>$session_name];
						
					}
					
				} else {
					
					$sms_return = ['code'=>1022,'msg'=>'验证码输入有误'];				
					
				}
				
			} else {
				
				if($destroy) {
					
					session($session_name,null);unset($safe_code);
				
					$sms_return = ['code'=>1021,'msg'=>'时间超时,请重新获取'];
					
				} else {
					
					$sms_return = ['code'=>1021,'msg'=>'时间超时,请重新获取','session_name'=>$session_name];
					
				}
				
			}

		}		
		
		if ($flag) {
			
			echo json_encode($sms_return);exit;
			
		} else {
			
			return $sms_return;
			
		}		
		
	}
	
	/**
	 * 检查短信验证码
	 * @param  string 		$phone 					手机号
	 * @param  integer 		$limit  				条数限制
	 * @param  boolean 		$ischecktime  	是否验证时间,默认true 验证
	 * @param  integer 		$pid  					渠道编号,默认0 官方渠道
	 * @param  boolean 		$flag  					是否ajax返回,默认true ajax返回
	 * @return mixed
	 * @author 鹿文学
	 */
	public function check_sms($phone,$limit,$ischecktime=true,$pid=0,$flag=true) {

        $sms_model = M('Short_message');
		
		$number = $sms_model->where(array('pid'=>$pid,'create_ip'=>get_client_ip(),'send_status'=>'000000','send_time'=>array(array('egt',strtotime('today')),array('elt',strtotime('tomorrow')))))->count();
    
		if (!empty($limit) && $number>=$limit) {

			$sms_return = ['code'=>1138,'msg'=>'每天发送数量不能超过'.$limit.'条'];
				
        } else {
			
			if($ischecktime) {
				
				$request_time = time();
				
				$map = array('phone'=>$phone);
				
				$map['create_time']=array(array('egt',($request_time-self::$count_down*60)),array('elt',$request_time));
				
				$number = $time = $sms_model->where($map)->count();
				
				if ($number>1){
					
					$sms_return = ['code'=>1139,'msg'=>'请'.self::$minute_cn[self::$count_down].'分钟后再次尝试'];
						
				}
			
			}
			

		}

	
		if(!empty($sms_return)) {
			
			if($flag) {
				
				echo json_encode($sms_return);exit;		
				
			} else {
				
				return $sms_return;
				
			}
		
		}
		
	}
		
}