<?php
namespace Mobile\Controller;
use Think\Controller;
use User\Api\SuserApi;

/**
* 首页
*/
class ShopController extends BaseController {

    /**
	 * 积分商城首页
	 * @return [type] [description]
	 * @author wyr <840186209@qq.com>
	 */
    public function index(){
    	$page = $page ? $page : 1; //默认显示第一页数据
		$row = C('LIST_ROWS');
		$map['status'] = 1;
		if(is_cache() &&S('mobile_shop_data') ){
            $data=S('mobile_shop_data');
        }else{
			$data = M('point_shop','tab_')
				->field("id,cover,price,good_name")
				->where($map)
				->order('create_time desc')
				->page($page, $row)
				->select();
			foreach ($data as $key => $value) {
				$data[$key]['url'] = U('Shop/shopdetail',array('id'=>$value['id']));
				$data[$key]['cover'] = get_cover($value['cover'],'path');
			}
			if(is_cache()){
                S('mobile_shop_data',$data);
            }
		}
		if(!$this->islogin()){
			$total = 0;
		}else{$member = new SuserApi;
			$user_id = $member->login_info("user_id");
			$point = D('User')->find($user_id);
			$total = $point['point'];
		}

		$this->assign('point',$total);
		$this->assign('data',$data);
		$this->assign('page',$page);
		$this->display();
	}

    /**
	 * 积分商城列表
	 * @return [type] [description]
	 * @author wyr <840186209@qq.com>
	 */
    public function ajaxlists(){
    	$p = I('post.p');
        $status=0;
		$row = C('LIST_ROWS');
		$map['status'] = 1;
		$lists = M('point_shop','tab_')
			->field("id,cover,price,good_name")
			->where($map)
			->order('create_time desc')
			->page($p, $row)
			->select();
		foreach ($lists as $key => $value) {
			$lists[$key]['url'] = U('Shop/shopdetail',array('id'=>$value['id']));
			$lists[$key]['cover'] = get_cover($value['cover'],'path');
		}
		if (!empty($lists) && is_array($lists)) {
            $status = 1;
        }
		echo json_encode(array('status'=>$status,'page'=>$p,'lists'=>$lists));
	}


	/**
	 * 详情页
	 * @return [type] [description]
	 * @author wyr <@qq.com>
	 */
	public function shopdetail(){
$member = new SuserApi;
		if(IS_POST){
			if(!$this->islogin()){$this->error('请先登录');}
			$user_id  = $member->login_info("user_id");
			$good_id  = $_REQUEST['good_id'];
			$good_num = $_REQUEST['number'];

			if($good_num<1) {
                $this->error("兑换数量有误");
            }
			if(!preg_match('/^[1-9]\d*$/', $good_num)) {
                $this->error("兑换数量有误");
            }
			$good_num = intval(abs($good_num));

			$map['user_id'] = $user_id;
		    $address = D('UserAddress')->field("id,name,city,address,phone")->where($map)->order("is_default desc")->find();
		    $address_id  = $address['id'];
			$result = D('PointShopRecord')->buy($good_id,$user_id,$good_num,$address_id);
			if($result !== false){
				$this->success('兑换成功',U('Shop/index'));
			}else{
				$this->error("兑换失败:".D('PointShopRecord')->getError());
			}
		}else{
			$id = I('get.id');
			$data = M('point_shop','tab_')
				->field("*")
				->where(array('id'=>$id))
				->find();
			$data['cover'] = get_cover($data['cover'],'path');
			$user = M('user','tab_')->field('id,account,point')->find($member->login_info('user_id'));
			$this->assign('point',empty($user['point'])?0:$user['point']);
			$this->assign('user',$user);
			$this->assign('data',$data);
			$this->display();
		}
	}

	/**
	 * 兑换平台币
	 * @return [type] [description]
	 * @author wyr <840186209@qq.com>
	 */
	public function exchangecoin(){
       $member = new SuserApi;
		$user_id = $member->login_info("user_id");
        if(IS_POST){
			if(!$this->islogin()){$this->error('请先登录');}
			$num = abs(I('num',0,'intval'));
			if($num<1){
			    $this->error('兑换数量错误');
            }
			$model = D('PointShopRecord');
			$result = $model->PointConvertCoin($user_id,$num);
			if($result){
				$this->success("兑换成功");
			}else{
				$this->error("兑换失败:".$model->getError());
			}
		}else{
			if($user_id<=0){
				redirect(U('User/login',array('back'=>'-1')));
			}
			$point = D('User')->find($user_id);
			$this->assign('point',$point['point']);
			$this->display();
		}
	}

	/**
	 * 兑换记录
	 * @return [type] [description]
	 * @author wyr <840186209@qq.com>
	 */
	public function exchangerecord(){
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}
		$page = intval($p);
		$page = $page ? $page : 1; //默认显示第一页数据
		$row = C('LIST_ROWS');$member = new SuserApi;
		$map['user_id'] = $member->login_info("user_id");//$user_id;
		$type = $_REQUEST['type'];
		if ($type == 2){
			$map['good_type'] = ['in',[1,2]];//商品
		}elseif ($type == 3) {
			$map['good_type'] = 3;//平台币
		}
		$data = D("PointShopRecord")
				->field("id,good_id,good_name,good_type,number,pay_amount,create_time")
				->where($map)
				->order('create_time desc')
				->page($page, $row)
				->select();
		$totalMap['user_id'] = $member->login_info("user_id");
		$total = D("PointShopRecord")->where($totalMap)->sum("pay_amount");
		$this->assign('total',empty($total)?0:$total);
		$this->assign('data',$data);
		$this->assign('page',$page);
		$this->display();
	}

	/**
 	 * AJAX 兌換記錄加载更多
 	 * @return [type] [description]
 	 */
	public function ajaxExchangeRecord() {
		$page = I('post.p');
		$row  = C('LIST_ROWS');
		$type = I('post.type');$member = new SuserApi;
		$map['user_id'] = $member->login_info("user_id");//$user_id;
		if ($type == 2){
			$map['good_type'] = ['in',[1,2]];//商品
		}elseif ($type == 3) {
			$map['good_type'] = 3;//平台币
		}
		$data = D("PointShopRecord")
				->field("id,good_name,good_type,number,pay_amount,create_time")
				->where($map)
				->order($order)
				->page($page, $row)
				->select();
		foreach ($data as $key => $value) {
			$data[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
		}
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status'=>$status,'page'=>$page,'lists'=>$data));
	}

	/**
	 * 兑换商品记录详情
	 * @return [type] [description]
	 * @author wyr <840186209@qq.com>
	 */
	public function exchangerecorddetail($id=0){
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}
		$map['sr.id'] = $id;$member = new SuserApi;
		$map['sr.user_id'] = $member->login_info('user_id');
		$data = D("PointShopRecord")->table("tab_point_shop_record as sr")
			->field("sr.good_name,sr.good_type,ps.good_info,ps.good_usage,ps.cover,sr.number,sr.good_key,sr.user_name,sr.address,sr.phone")
			->join("left join tab_point_shop ps on ps.id = sr.good_id")
			->where($map)
			->find();
		$data['cover'] = get_img_url($data['cover']);
		$data['good_key'] = json_decode($data['good_key']);

		$this->assign('data',$data);
		$this->display();
	}

	public function shoporder($id=0){
		if(!$this->islogin()){
		    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		    $this->redirect('User/login',array('url'=>base64_encode(base64_encode($url))));
		}
			$member = new SuserApi;
		if(IS_POST){
			$user_id  = $member->login_info("user_id");
			$good_id  = $_REQUEST['good_id'];
			$good_num = $_REQUEST['number'];

            if($good_num<1) {
                $this->error("兑换数量有误");
            }
            if(!preg_match('/^[1-9]\d*$/', $good_num)) {
                $this->error("兑换数量有误");
            }
            $good_num = intval(abs($good_num));

			$map['user_id'] = $user_id;
			$map['is_default'] = 1;
		    $address = D('UserAddress')->field("id,name,city,address,phone")->where($map)->order("is_default desc")->find();

		    $address_id  = $address['id'];
			$result = D('PointShopRecord')->buy($good_id,$user_id,$good_num,$address_id);
			if($result !== false){
				$this->success('兑换成功',U('Shop/index'));
			}else{
				$this->error("兑换失败:".D('PointShopRecord')->getError());
			}
		}else{
			$id = I('get.id');
			$data = M('point_shop','tab_')
				->field("*")
				->where(array('id'=>$id))
				->find();
			if(empty($data)){
				echo "<script>alert('没有商品')</script>";
			}
			$map['user_id'] = $member->login_info("user_id");
			$map['is_default'] = 1;
			$address = D('UserAddress')->field("id,name,city,address,phone")->where($map)->order("is_default desc")->find();
			$data['cover'] = get_cover($data['cover'],'path');
			$data['price'] = I('num',1) * $data['price'];
			$user = M('user','tab_')->field('id,account,point')->find($member->login_info('user_id'));
			$this->assign('point',empty($user['point'])?0:$user['point']);
			$this->assign('user',$user);
			$this->assign('data',$data);
			$this->assign('address',$address);
			$this->display();
		}

	}

	/**
	 * 个人中心->编辑资料->收货管理
	 * @return [type] [description]
	 * @author 小纯洁
	 */
	public function useraddresslist() {
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}$member = new SuserApi;
		$logininfo = $member->login_info();
		$userData = M('UserAddress','tab_')->where(array('user_id'=>$logininfo['user_id']))->select();
		$this->assign('list_data',$userData);
        $this->display();
	}

	/**
	 * 个人中心->编辑资料->收货管理->新增收货地址
	 * @return [type] [description]
	 * @author 小纯洁
	 */
	public function useraddressadd() {
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}$member = new SuserApi;
		$logininfo = $member->login_info();
		$userData = M('UserAddress','tab_')->where(array('user_id'=>$logininfo['user_id']))->select();
		if(IS_POST){
			$model = M('UserAddress','tab_');
			$data = $_POST;
			$data['user_id'] = $logininfo['user_id'];
			$data['create_time'] = time();
			if(empty($userData)){
				$data['is_default'] = 1;
			}else{
				$data['is_default'] = 0;
			}
			if(!empty($data['is_default'])){
				$model->where('user_id='.$logininfo['user_id'])->save(array('is_default'=>0));
			}
			if($model->create($data) && $model->add()){

				$this->success('添加成功!',U('Shop/useraddresslist',array('id'=>$_POST['good_id'],'num'=>$_POST['num'])));//
			}else{
				$this->error('添加失败');
			}
		}else{
			$this->assign('userData',$userData);
			$this->display();
		}

	}

	/**
	 * 个人中心->编辑资料->收货管理->编辑收货地址
	 * @return [type] [description]
	 * @author 小纯洁
	 */
	public function useraddressedit($addid=0) {
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}$member = new SuserApi;
		$logininfo = $member->login_info();
		$model = M('UserAddress','tab_');
		if(IS_POST){
			$data = $_REQUEST;
			$data['user_id'] = $logininfo['user_id'];
			$data['id'] = $addid;
			if(!empty($data['is_default'])){
				$model->where('user_id='.$logininfo['user_id'])->save(array('is_default'=>0));
			}
			if($model->save($data) !== false){
				$this->success('编辑成功',U('Shop/useraddresslist',array('id'=>I('good_id'),'num'=>I('num'))));
			}else{
				$this->error('编辑失败');
			}
		}else{
			$data = $model->find($addid);
			$this->assign("data",$data);
			$this->display();
		}

	}

	/**
	 * 个人中心->编辑资料->收货管理->删除收货地址
	 * @return [type] [description]
	 * @author 小纯洁
	 */
	public function useraddressdel($id=0) {
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}

		$model = M('UserAddress','tab_');
		$result = $model->where("id=".$id)->delete();
        if($result !== false){
        	$this->success('地址删除成功',U('Shop/useraddresslist',array('id'=>I('good_id'),'num'=>I('num'))));
        }else{
        	$this->error("地址删除失败");
        }
	}

	/**
	 * 个人中心->编辑资料->收货管理->设置默认收货地址
	 * @return [type] [description]
	 * @author 小纯洁
	 */
	public function setDefaultAddress($id=0,$type='setting') {
		if(!$this->islogin()){$this->redirect('Mobile/User/login');}
		$model = M('UserAddress','tab_');$member = new SuserApi;
		$logininfo = $member->login_info();
		switch ($type) {
			case 'setting':
				$map['id'] = array('neq',$id);
				$map['user_id'] = $logininfo['user_id'];
				$model->where($map)->save(array('is_default'=>0));
				$result = $model->where('id = '.$id)->save(array('is_default'=>1));
				break;
			case 'cancel':
				$result = $model->where('id = '.$id)->save(array('is_default'=>0));
				break;
		}
        if($result !== false){
        	$this->success('地址删除成功');
        }else{
        	$this->error("地址删除失败");
        }
	}


}