<?php
namespace Mobile\Controller;
use Think\Controller;
use Lib\Alidayu\SendMSM;
class IndexController extends CoreController {
	/**
	 * [_initialize 重新初始化，判断用户是否登录等操作]
	 * @method   _initialize
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-22T10:15:58+0800
	 * @return   [type]                   [description]
	 */
	public function _initialize(){
		parent::_initialize();
		if(!session('?user'))
			$this->redirect('Public/login');
	}
	/**
	 * [index 主页]
	 * @method   index
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-30T14:18:00+0800
	 * @return   [type]                   [description]
	 */
	public function index(){
		$f=M('admin')->where(array('id'=>session('user.id')))->find();
		if(md5($f['phone'])==$f['password']||$f['anquan']==null)//||$f['shenfenzheng']==null
			$this->redirect('Index/anquan');
		$this->peixunjs = M('admin')->where(array('peixun'=>session('user.nickname')))->count();
		$this->jiedaijs = M('admin')->where(array('jiedai'=>session('user.nickname')))->count();
		$this->u=M('admin')->where(array('id'=>session('user.id')))->find();
		$this->display();
	}

	
	public function syslogs(){
		$this->list=M('admin_logs')->where(array('uid'=>session('user.id')))->order('time DESC')->select();
		$this->display();
	}

	/**
	 * [goldlogs 金币记录]
	 * @method   goldlogs
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-30T14:21:34+0800
	 * @return   [type]                   [description]
	 */
	public function goldlogs(){
		$this->list=M('admin_goldlogs')->where(array('uid'=>session('user.id')))->order('time DESC')->select();
		$this->display();
	}
	/**
	 * [cash 金币提现]
	 * @method   cash
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-30T14:21:59+0800
	 * @return   [type]                   [description]
	 */
	public function cash(){
		if(IS_POST){
			$cash=I('cash','10000',int);
			if(!cash($cash))
				$this->error('余额不足！');
			// if(session('user.shiming')!=2){
			// 	$this->error('还未进行实名认证，不可提现,如果确认通过请退出后重新登录');
			// }
			if($cash<10000){
				$this->error('提现要大于10000金币');
			}
			$uid=session('user.id');
			$d=M('admin')->where(array('id'=>$uid))->field('job')->find();
			if($d['job']==0){
				$this->error('你还没有职务，无法计算手续费和管理费，不可提现');
			}
			$nickname=session('user.nickname');
			$gold=$cash;
			$rmb=yuji($gold,true);
			$shouxu=shouxu($gold);
			if(session('user.job')==7){
				$guanli=0;
			}else{
				$guanli=$gold*0.1;
			}
			$shengyu=$gold-$shouxu-$guanli;
			// 扣除金额
			if(M('admin')->where(array('id'=>session('user.id')))->setDec('gold',$gold)){
				// 添加到提现申请
				$add=array(
					'uid'=>$uid,
					'nickname'=>$nickname,
					'gold'=>$gold,
					'shouxu'=>$shouxu,
					'guanli'=>$guanli,
					'sygold'=>$shengyu,
					'rmb'=>$rmb,
					'truename'=>session('user.truename'),
					'alipay'=>session('user.alipay'),
					'shoujihao'=>session('user.phone'),
					'sqtime'=>time(),
					'ip'=>get_ip()
					);
				if(M('cash')->add($add)){
					// wlog('申请提现，金币减少【'.$gold.'】');
					$this->success('申请成功！','cashlogs');
				}else{
					M('admin')->where(array('id'=>session('user.id')))->setInc('gold',$gold);
					$this->error(C('MSG'));
				}
			}else{
				$this->error(C('MSG'));
			}
		}else{
			$anquan=M('admin')->where(array('id'=>session('user.id')))->find();			
			if(!$anquan['anquan'])
				$this->redirect('Index/anquan');
			$this->u=M('admin')->where(array('id'=>session('user.id')))->field('gold')->find();
			$this->display();
		}
	}
	/**
	 * [cashlogs 金币提现记录]
	 * @method   cashlogs
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-30T14:22:15+0800
	 * @return   [type]                   [description]
	 */
	public function cashlogs(){
		$m=M('cash');
		$w=array('uid'=>session('user.id'));
		$p=getpage($m, $w, 10);
		$list=$m->where($w)->order('sqtime DESC')->select();
		$this->p=$p->show();
		$this->list=$list;
		$this->display();
	}
	/**
	 * [logout 退出登录]
	 * @method   logout
	 * @Author   Amen[233713821@qq.com]
	 * @DateTime 2016-05-30T14:22:29+0800
	 * @return   [type]                   [description]
	 */
	public function logout(){
		session('user',NULL);
		$this->redirect('/Public/login');
	}

	public function reg(){
        $url="www.chuangshen1314.com/ruzhi.html".makekey(session('user.nickname'));
		$durl=cn50r($url);
		$this->url=$url;
		$this->durl=$durl;

		$this->display();
	}

	public function editpassword(){
		if(IS_POST){
			if(!M('admin')->where(array('id'=>session('user.id'),'password'=>md5(I('pass'))))->find())
				$this->error('旧密码错误！');
			if(!M('admin')->where(array('id'=>session('user.id')))->setField('password',md5(I('pass1'))))
				$this->error(C('MSG'));
			$this->success('密码修改成功！','main');
		}else{
			$this->display();
		}
	}

	public function anquan(){
		if(IS_POST){
			$data=array(
				'password'=>md5(I('password')),
				'anquan'=>md5(I('anquan')),
				// 'shenfenzheng'=>I('shenfenzheng')
				);
			$rules = array(
				array('password','/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,15}$/','密码范围6-15个任意字符',1,'regex'),
				array('anquan','/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,15}$/','提现密码范围6-15个任意字符',1,'regex'),
				// array('shenfenzheng','/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{15,18}$/','身份证格式不正确'
				// 	,1,'regex'),
				);
			$User = M("admin"); // 实例化User对象
			if (!$User->validate($rules)->create()){
     // 如果创建失败 表示验证没有通过 输出错误提示信息
				$this->error($User->getError());
			}else{
				if($User->where(array('id'=>session('user.id')))->save($data)){
					$this->success('设置成功！','index');
				}else{
					session('user',null);
					$this->error(C('MSG'));
				}
			}
		}else{
			$this->display();
		}
	}

	public function editanquan(){
		if(IS_POST){
			if(!M('admin')->where(array('id'=>session('user.id'),'anquan'=>md5(I('aqpwd'))))->find())
				$this->error('旧密码错误！');
			if(!M('admin')->where(array('id'=>session('user.id')))->setField('anquan',md5(I('aqpwd1'))))
				$this->error(C('MSG'));
			$this->success('安全码修改成功！','main');
		}else{
			$this->display();
		}
	}

	public function shiming(){
		if(IS_POST){
			$up = $this->uploadimg();
			if (!$up['code'])
				$this->error($up['msg']);
			$array=array(
				'shiming'=>1,
				'sfza'=>$up['msg'][0],
				'sfzb'=>$up['msg'][1],
				'sfzc'=>$up['msg'][2],
				);
			if(M('admin')->where(array('id'=>session('user.id')))->save($array)){
				$this->success('上传文件成功！请耐心等待审核！','index');
				//exit('上传文件成功！请耐心等待审核！');
			}else{
				$this->error(C('MSG'));
			}
		}else{
			$s=M('admin')->where(array('id'=>session('user.id')))->field('shiming')->find();
			if($s['shiming']==2)
				$this->error('已通过，不需要提交');
			$this->display();
		}
	}

	//发布任务
	public function task_pub(){
		if($_SESSION['user']['job'] !=13){
			$this->error('无权限');
		}
		if(IS_POST){
			$data=array(
				'ask'=>I('ask'),
				'gdtime'=>I('gdtime'),
				'jiej'=>I('jiej'),
				'link'=>I('link'),
				'total'=>I('total'),
				'type'=>I('type'),
				'yaj'=>I('yaj'),
				'yongj'=>I('yongj'),		
			);
			$data['pbtime'] = time();
			$data['pbr'] = $_SESSION['user']['nickname'];
			$res = M('task')->add($data);

			if($res){
				$this->success('发布成功','/index/task_index');
			}
			else{
				$this->error('发布失败');
			}
		}
		$this->display();
	}

	//任务大厅
	public function task_index(){
		$m=M('task');
		//$p = getpage($m,$w,10);
		$task=$m->order('id DESC')->select();
		//$this->p=$p->show();


		foreach($task as $k=>$v){
			$admin_taskm = M('admin_task');
			$yjd = $admin_taskm->where("task_id =$v[id]")->count();
			if($v['total']>$yjd){
				$abc[] = $v;
			}
		}
		$this->task=$abc;
		$admin_id = $_SESSION['user']['id'];
		$admin_info = M('admin')->field("gold")->where("id = $admin_id")->find();
		$this->admin_gold = $admin_info['gold'];
		$this->display();
	}

	//我的任务
	public function task_my(){
		$admin_id = $_SESSION['user']['id'];
		$m = M('admin_task');
		$w = array('uid'=>$admin_id,'shenhe'=>array(0,1,2,3,4));
		//$p = getpage($m,$w,10);
		$my_task = $m
				->alias('at')
				->join("left join ".C('DB_PREFIX').'task t on t.id=at.task_id')
				->field("t.type,t.yongj,t.yaj,t.ask,t.gdtime,at.shenhe,at.task_id,at.time as jdtime,at.id as at_id")
				->where("uid=$admin_id and shenhe in(0,1,2,3,4)")
				->order("at.id desc")
				->select();
		foreach($my_task as $k=>&$v){
			$v['gdtime_s'] = $v['gdtime']*60;
			$is_cs = $v['gdtime_s'] + $v['jdtime']-time();

			$v['admin_id'] = $admin_id;
			if($is_cs<0 && $v['shenhe']==0){
				$data['shenhe'] = 2;
				M('admin_task')->where("id=$v[at_id]")->save($data);
			}
 		}

		$this->my_task=$my_task;
		//$this->p=$p->show();
		$this->display();
	}

	//提交任务
	public function task_tj(){
		$at_id = I('post.at_id');
		if(!$at_id)
			$this->error('参数错误');
		if(IS_POST){
			$data['content'] = I('post.content');
			$data['shenhe'] = 4;
			$data['tjtime'] = time();
 			$res = M('admin_task')->where("id=$at_id")->save($data);
 			if($res === false)
 				$this->error('参数错误');			
 			else
 				$this->success('成功','task_my');
		}else{
			$this->error('参数错误');
		}
	}
	//查看任务详情
	public function task_detail(){
		$at_id = I('get.at_id');
		if(! is_numeric($at_id))
			$this->error('参数错误');

		$atm = M('admin_task');

		$detail = $atm
				->alias('at')
				->join("left join ".C('DB_PREFIX').'task t on t.id=at.task_id')
				->field("t.type,t.yongj,t.yaj,t.ask,t.gdtime,t.link,t.total,t.jiej,at.shenhe,at.task_id,at.time as jdtime,at.id as at_id,at.content")
				->where("at.id=$at_id")
				->find();

		$this->detail = $detail;
		$this->display();
	}

	//任务审核
	public function task_sh(){
		if($_SESSION['user']['job'] !=13){
			$this->error('无权限');
		}
		$at_id = I('get.at_id');
		$shenhe = I('get.shenhe');
		$nickname = $_SESSION['user']['nickname'];
		if($at_id){
			if(is_numeric($at_id)){
				$atm = M('admin_task');
				if($shenhe==1){
					$data = array("shenhe"=>1,'shr'=>$nickname);
				}
				else{
					$data = array('shenhe'=>3,'shr'=>$nickname);
				}

				$res = $atm->where("id=$at_id")->save($data);
				if($res !==false){
					$info = $atm->where("id = $at_id")->find();
					$admin_info = M('admin')->where("id = $info[uid]")->find();
					if(!$admin_info)
            			exit('未找到此人');
            		$admin_id = $info['uid'];
					$admin_gold = $admin_info['gold'];

					$task_info = M('task')->where("id = $info[task_id]")->find();
					$jiej = $task_info['jiej'];
					$yongj = $task_info['yongj'];


					if($shenhe==1){
						//$gold = $admin_gold+$yongj;
						M('admin')->where(array('id'=>$admin_id))->setInc('gold',$yongj);

						//2017-03-04 08:31:17 会员 好运连连, 编号为#49的任务通过审核,金币增加20 (佣金:20,押金:0),by System
						$add=array('uid'=>$admin_id,'type'=>1,'note'=>'会员 '.$admin_info['nickname'].'编号为#'.$at_id.'的任务通过审核,金币增加'.$yongj.',(佣金：'.$yongj.',押金：'.$task_info['yaj'].'),by System','time'=>time());          			 	
					}else{
						if($admin_gold<$jiej)
            				exit('此人金币不够你的扣除');
						M('admin')->where(array('id'=>$admin_id))->setDec('gold',$jiej);
						//2017-03-04 11:05:23 会员 好运连连 任务押金,金币减少0,by System
						$add=array('uid'=>$admin_id,'type'=>0,'note'=>'会员 '.$admin_info['nickname'].' 任务押金,金币减少'.$jiej.',by System','time'=>time());
					}
					M('admin_goldlogs')->add($add);
					
					$this->success('审核完成');
				}
				else{
					$this->error('审核失败');
				}
			}else{
				$this->error('参数错误');
			}
		}else{
			$tm = M('task');
			$atm = M('admin_task');
			$w = array('shenhe'=>4,'pbr'=>$nickname);
			$p = getpage($atm,$w,10);	
			$task = $atm
					->alias('at')
					->field("at.id as at_id,t.id as task_id,t.jiej,t.ask,t.pbtime,at.tjtime,at.uid,t.yongj")
					->join(C('DB_PREFIX').'task as t on t.id=at.task_id')
					->where($w)
					->select();
			$am = M('admin');
			foreach($task as $k=>$v){
				$nickname = $am
							->field('nickname')
							->where("id = $v[uid]")
							->find();
				$task[$k]['nickname'] = $nickname['nickname'];
			}
			$this->p = $p->show();
			$this->task = $task;
			$this->display();
		}
		
	}

	//审核详
	public function shenhe_xq(){
		$at_id = I('get.at_id');
		if(!is_numeric($at_id))
			$this->error('参数错误');

		$atm = M('admin_task');

		$detail = $atm
				->alias('at')
				->join("left join ".C('DB_PREFIX').'task t on t.id=at.task_id')
				->field("t.type,t.yongj,t.yaj,t.ask,t.gdtime,t.link,t.total,t.jiej,at.shenhe,at.task_id,at.time as jdtime,at.id as at_id,at.content")
				->where("at.id=$at_id")
				->find();
		$this->detail = $detail;
		$this->display();
	}

	//接单
	public function jiedan(){
		$task_id = I('get.id');
		$user_gold = I('get.admin_gold');
		$task_m = M('task');
		$admin_task_m = M('admin_task');
		if(!$task_id)
			$this->error('参数错误');

		$total = $task_m->field('total,jiej')->where("id=$task_id")->find();
		$yjd = $admin_task_m->where("task_id=$task_id")->count();


		(int)$sy = $total['total']-$yjd;
		if($user_gold < $total['jiej']){
			$this->error('任务资格不够,请继续努力工作');
		}elseif($sy<0 || $sy==0){
			$this->error('任务已被抢完');
		}else{
			$data['uid'] 	= $_SESSION['user']['id'];
			$data['task_id'] = $task_id;
			$data['time']    = time();

			$res = $admin_task_m->add($data);
			if($res){
				$this->success('接单成功','/Mobile/Index/task_my');
			}else{
				$this->error('接单失败');
			}
		}
	}
	protected function uploadimg() {
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $upload->rootPath = './Public/index/shiming/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件 
        $info = $upload->upload();
        if (!$info) {
            // 上传错误提示错误信息
        	return array('code' => 0, 'msg' => $upload->getError());
        } else {// 上传成功
        	foreach ($info as $file) {
        		$msg[] = $file['savepath'] . $file['savename'];
        	}
        	return array('code' => 1, 'msg' => $msg);
        }
    }
	
	//任务删除
    public function task_del(){
    	$at_id = I('get.at_id');
    	
    	if(is_numeric($at_id)){
    		$at_model = M('admin_task');

			$info = $at_model->find($at_id);
			if($info['shenhe']==2 || $info['shenhe']==3){
				$res = $at_model->where("id = $at_id")->setfield("shenhe",5);
				if($res === false){
					$this->error('操作失败');
				} else{
					$this->success('操作成功','/Mobile/Index/task_my');
					exit;
				}

			}else{
				$this->error('只有超时或未通过的才可以删除');
			}



    	}else{
    		$this->error('参数有误');
    	}
    }
	/*
	 * 发送短信
	 * */
	public function send(){
		$uuid = I('get.uuid');
		$uid = I('get.uid');
		$id = I('get.id');
		mysql_query("BEGIN");
		$is_false = 0;
		if($id && $uuid && $uid){
			/*******查询要发送短信者并减去一个金币*******/
			$send = M('admin')->field('gold')->where(array('id'=>$uid))->find();
			if($send['gold']<1){
				$this->error('金币数量不足');
			}else{
				$new_gold = $send['gold']-1;
				$res = M('admin')->where(array('id'=>$uid))->setField('gold',"$new_gold");
				if($res===false){
					$is_false = 1;
					$this->error('系统错误，请稍后重试~');
				}else{
					/***************发送短信****************/
					//1.查询用户手机号
					$uuinfo = M('admin')->field('phone,nickname')->where(array('id'=>$uuid))->find();
					if(!$uuinfo['phone']){
						$this->error('用户手机号不存在~');
					}

					$msg = $this->sendMSM($recNum="$uuinfo[phone]",$setSmsTemplateCode="SMS_52270251",$smsFreeSignName="创神电商",$nickname=$uuinfo['nickname']);
					/**********更改新用户的短信状态************/
					$res1 = M('admin_goldlogs')->where(array('id'=>$id))->setDec('duanxin',1);
					if($res1===false){
						$is_false = 1;
						$this->error('系统错误，请稍后重试~');
					}else{
						$this->success('操作成功');
					}
				}


			}
		}else{
			$this->error('系统错误，请稍后重试~');
		}
		if($is_false){
			mysql_query("ROOLBACK");
		}else{
			mysql_query("COMMIT");
		}
	}

	//发送短信
	protected function sendMSM($recNum,$setSmsTemplateCode,$smsFreeSignName="创神电商",$nickname){
		$smsParam = "{'name':$nickname}";
		$alidayu = new SendMSM();
		$result = $alidayu->send($recNum,$smsParam,$setSmsTemplateCode,$smsFreeSignName="创神电商");

		if($result['result']->err_code == 0)
			return 1;
		else
			return 0;
	}
}