<?php
// +----------------------------------------------------------------------
// | 首页控制器
// +----------------------------------------------------------------------
// | ThinkOAO （Online And Offline）
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.hanchao9999.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaogg <xiaogg@sina.cn>
// +----------------------------------------------------------------------
namespace Mobile\Controller;
class IndexController extends BaseController{
    public function _initialize(){
        parent::_initialize ();
    }
    public function clearlocation(){
        session('siteinfo',null);echo '<a href="'.U('index').'">首页</a>';
    }
    public function index(){
        $member_info=session('member_info');
        $siteinfo=session('siteinfo');
//		 echo "<pre>";var_dump($siteinfo);EXIT;
        $siteinfo['temp_name']=$siteinfo['temp_name']?$siteinfo['temp_name']:$siteinfo['site_name'];
        $this->assign('temp_name',$siteinfo['temp_name']?$siteinfo['temp_name']:'请选择');
        $this->get_index_area_cache();
        
        $param = I('param.');
        $map['is_default'] = 1;
        $map['is_wxsmall'] = 0;
        if($param['id']&&$param['key']){
            //验证预览模板是否合法
            if(base64_encode(C('HANCHAO_KEY').$param['id'])==$param['key']){
                $map = array();
                $map['id'] = $param['id'];
            }
        }
        $content = M('Dragedit')->where($map)->cache('tpl_mobile_default0')->getField('value');
        if($content){
            $flist = D('Common/Dragedit')->formatdiylist($content);
        }else{
            $flist='{}';
        }
        $this->assign('HCinitlist', $flist);
        $this->judge();
        if($siteinfo){
            $ret = D('Wxsmall/Login')->bind_shop_param($siteinfo['temp_lng'],$siteinfo['temp_lat'],1);
            if($ret['status'] == 1){
                $shop_data['count'] = count($ret['data']);
                $shop_data['list'] = $ret['data'];
            }else{
                $shop_data['count'] = 0;
            }
        }
        //jxr start 2018.11.08
        if(intval(C('IS_LOCK_USER'))==1){
            $memberinfo = checkuserauthtype();
            if($memberinfo['user_shop']){
                $user_shop=intval($memberinfo['user_shop']);
                session('main_shop_id',$user_shop);
                $this->assign('user_shop',$user_shop);
            }
        }
        //jxr end 2018.11.08
		$main_shop_id = get_wxsmall_shop_id();//用户选中的门店id
		$this->assign('shop_list',$shop_data);
		$this->assign('main_shop_id',$main_shop_id);
        $this->display();
    }
    public function get_goods_list(){
        $return=array('status'=>3,'msg'=>'暂无数据');
        $param=I('param.');
        $map['is_default'] = 1;
        $map['is_wxsmall'] = 0;
        if($param['id']&&$param['key']){
            //验证预览模板是否合法
            if(base64_encode(C('HANCHAO_KEY').$param['id'])==$param['key']){
                $map = array();
                $map['id'] = $param['id'];
            }
        }
        $content = M('Dragedit')->where($map)->cache('tpl_mobile_default0')->getField('value');
        if($content){
            $flist = D('Common/Dragedit')->formatdiylist($content);
        }else{
            $flist=array();
        }
        $list=$goodsaddlist=$goods_data=array();
        $layout=0;
        if($flist)$list=json_decode($flist,true);
        if($list){
            foreach ($list as $key => $value) {
                if($value['data_type']==4){
                    $goodsaddlist=array();
                    $goodsaddlist=$value;
                    if($value['content']['goodslist']){
                        foreach ($value['content']['goodslist'] as $k => $v) {
                            if($v){
                                $goodsaddlist['content']['goodslist'][$k]['showName']=$value['content']['showName'];
                                $goodsaddlist['content']['goodslist'][$k]['showPrice']=$value['content']['showPrice'];
                            }                            
                        }
                    }
                    
                }
            }
        }
        $list_html='';
        if($goodsaddlist && !empty($goodsaddlist['content']['goodslist'])){
            $fetch = 'index_goods_list_'.$goodsaddlist['content']['layout'];
            $goods_num=$goodsaddlist['content']['goodsNum'];
            $goods_cont=count($goodsaddlist['content']['goodslist']);
            $return['is_down']=0;
            if($goods_num>$goods_cont){
                $return['is_down']=1;
            }
            if($param['p']==1)$goodsaddlist['content']['goodslist']=array();
            $this->assign('goods_data',$goodsaddlist['content']['goodslist']);
            $list_html=$this->fetch($fetch);
            $return['status']=1;
            $return['data']=$list_html;
        }  
        $this->ajaxReturn($return);
    }
    public function get_index_area_cache(){
        $tree = get_arearegion_cache(3);
        $city_tree = get_arearegion_cache(0);
        ksort($tree);
        $this->assign('json_city', json_encode($city_tree));
        $this->assign('json_provinces', json_encode($tree));
        if (cookie('dingwei_address')) {
            $address_info = cookie('dingwei_address');//获取定位信息
        } elseif (session('dingwei_address')) {
            $address_info = session('dingwei_address');
        }
        //$address_info = session('dingwei_address');//获取定位信息
        if ($address_info && $address_info['city']) {
            $cityname = idtoname($address_info['city'], 'Area', 'name');
            $this->assign('index_cityname', $cityname);
        }
    }

    // 微信立即领取
    public function get_coupons_wx(){
        $memberinfo = checkuserauthtype();
        $uid = $memberinfo['id'];
        $map=array();
        $map['id']=$uid;
        $member_info=M("Member")->where($map)->field(true)->find();
        if(!$uid){
            cookie('forward',U('Mobile/Index/kaquan',array('eid'=>MID)));
            $return['status'] = 0;
            $return['url'] = U('Mobile/Login/index');  
            $this->ajaxReturn($return);
        }
        $coupons_id = I('get.id');
        /*$map = array();
        $map['id'] = $coupons_id;
        $coupons_get_limit = M('Coupons')->where($map)->getfield('get_limit');
        $map = array();
        $map['coupons_id'] = $coupons_id;
        $map['uid'] = $uid;
        $coupons_get = M('CouponsGet')->where($map)->count();
         if($coupons_get>=$coupons_get_limit){
             $data['msg'] = '领取次数到达上限!';
             $data['status'] = '2';
             $this->ajaxReturn($data);
         }
        $map=array();
        $map['id']=$coupons_id;
        $map['is_inside'] = 0;
        $coupons = M('Coupons')->where($map)->field('quantity,get_limit,end_timestamp,buy_money,buy_type')->find();
        if($coupons['quantity']<=0){
            $data['status'] = 2;
            $data['msg'] = '库存不足';
            $this->ajaxReturn($data);
        }elseif (time() > $coupons['end_timestamp'] && $coupons['end_timestamp']) {
            $data['status'] = 2;
            $data['msg'] = '优惠券已过期';
            $this->ajaxReturn($data);
        }
        if($coupons['buy_type']==1) {
            if ($coupons['buy_money'] > $member_info['usepoints']) {
                $data['msg'] = '积分不足，不能购买';
                $data['status'] = 2;
                $this->ajaxReturn($data);
            }
        }
        $map=array();
        $map['uid'] = $uid;
        $map['coupons_id'] = $coupons_id;
        $map['add_time'] = array('gt',(NOW_TIME-60));
        $check = M('CouponsGet')->where($map)->count();
        if($check>0){
            $return['status'] = 2;
            $return['msg'] = '优惠券领取太快了请稍后再领取';
            return $return;
        }*/

        if(is_weixin()){
            $Weixin = new \Common\Vendor\WeixinCoupon();
            $map = array();
            $map['id'] = $coupons_id;
            $card_id = M('Coupons')->where($map)->getfield('card_id');
            $AddCartParam = $Weixin->AddCartParam($card_id);
            $data['cardId'] = $AddCartParam['cardId'];
            $data['cardExt'] = $AddCartParam['cardExt'];
            $data['wx'] = 1;
        }else{
            $data['wx'] = 0;
        }
        $this->ajaxReturn($data);
    }
    // 立即领取
    function get_coupons(){
        $id = I('get.id');
        $code = I('get.code');
        $order_id = I('order_id');
        $type = I('type');
        if($type==1){//消费有礼
            $from=3;//系统
        }elseif($type==2){//小票抽奖
            $from=4;//奖品
        }elseif($type==3){//会员关怀
            $from=3;//奖品
        }elseif($type==4){//全名发券
            $from=4;//奖品
        }else{
            $from=1;
        }
        $data = D('Shop/CouponsGet')->get_coupons($id,'',$code,$order_id,$from,'',$type);
        $this->ajaxReturn($data);
    }
    function employ(){
        $id = I('get.id');
        $data = M('Coupons')->where('id='.$id)->field(true)->find();
        if($data){
            $data['begin_timestamp'] = date('Y-m-d',$data['begin_timestamp']);
            $data['end_timestamp'] = date('Y-m-d',$data['end_timestamp']);
            $return['status'] = 1;
            $memberinfo = checkuserauthtype();
            $where['uid'] = $memberinfo['id'];
            $where['coupons_id'] = $data['id'];
            $where['status'] = 0;
            $coupons_get = M('CouponsGet')->where($where)->count('id');
            $data['coupons_get'] = 1;//未领取
            if(!$coupons_get)$data['coupons_get'] = 0;//已领取
            $return['data'] = $data;
        }else{
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }
    //卡券列表页
    public function kaquan($type=0){
        $member_info=session('member_info');
        $param=I('param.');
        $list = D('Shop/CouponsGet')->coupons_list($param);
        //echo "<pre>";print_r($list);exit;
        if($list['info']){
			foreach($list['info'] as $k=>$v){
				$list['info'][$k]['reduce_cost'] = Intval($v['reduce_cost']);
				$list['info'][$k]['least_cost'] = Intval($v['least_cost']);
				if($v['rank_id'] == 'DISCOUNT'){
					$list['info'][$k]['discount'] = (100-$v['discount'])/10;
				}
				if(!empty($list['info'][$k]['is_show'])){
					$list['info'][$k]['is_show'] = array_filter(explode(',',$list['info'][$k]['is_show']));
				}
                if($v['buy_type']==1){
                    $list['info'][$k]['buy_money']=floatval($v['buy_money']);
                }
                $list['info'][$k]['uid'] = $member_info['id'];
			}
		}
        if($type==1)return $list;
		//分享设置
        $title="领券中心";
        $description='领券中心'.'_'.C('WEB_SITE_TITLE');
        $share_url=U('Mobile/Index/kaquan',array('eid'=>MID));
        $this->assign("title",$title);
        $this->assign("description",$description);
        $this->assign("share_url",$share_url);
        $this->display();
    }
     public function get_quan_list(){
        $return['status']=0;
        $data=$this->kaquan(1);
        if(empty($data['info']))$this->ajaxReturn($return);
        $return['status']=1;
        $this->assign('list',$data['info']);
        $list_html=$this->fetch('quan_list');
        $return['data']=$list_html;
        $return['show'] = $data['show'];
        $this->ajaxReturn($return);
    }
    public function share(){
        $id = I('get.id');
        $map = array();
        $map['id'] = $id;
        $map['is_inside'] = 0;
        $data = M('Coupons')->where($map)->field(true)->find();
        if($data['type'] == 1){
            $data['validity'] = date('Y-m-d',$data['begin_timestamp']).'-'.date('Y-m-d',$data['end_timestamp']);
        }elseif($data['type'] == 2){
            $data['validity'] = "领取".$data['fixed_begin_term']."天后生效,有效期".$data['fixed_term']."天";
        }
        $this->assign('data',$data);
        $this->display();
    }
    public function cancel(){
        $map = array();
        $map['name'] = 'FIXED_SIGNATURE';
        $sign = M('Config')->where($map)->getField('value');
        $member['mobile'] = '17798112151';
        $userid = 66;
        $sms_theme = '尊敬的会员eeee，您在2018-02-10 11:13:28使用余额成功消费￥47.5元，当前账户余额为￥63.00元。';
        if(strpos($sms_theme,'[') !== false){
            $sms_theme = $sms_theme.'【'.$sign.'】';
        }else{
            $sms_theme = $sms_theme.'退订回N'.'【'.$sign.'】';
        }
        sendsms($member['mobile'],$sms_theme,'',$userid);
    }

    /**
     * 
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * 
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {//print_r($this->config);
        $urlObj["appid"] = $this->config['config_account'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    /**
     * 
     * 拼接签名字符串
     * @param array $urlObj
     * 
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }


//    public function card(){
//        $code_data['first'] = '订单发货通知';
//        $code_data['to'] = '13100000000';
//        $code_data['order_sn'] = '13100000000131';
//        $code_data['status'] = '已发货';
//        sendbytheme($code_data,'SEND_GOODS');
//    }
    public function decca(){
        $wx = new \Common\Vendor\WeixinCard;
        $result=$wx->activateuserform();
    }
	public function change_mainshopid(){
		$id = I('id');
		session('main_shop_id',$id);
		$return = array('status'=>1,'msg'=>'');
		$this->ajaxReturn($return);
	}
	public function kaquan_cont(){
		$id = I('param.id');
     /*   $type=I('type')?I('type'):0;
        $order_id=I('order_id');
       $this->assign('type',$type);
       $this->assign('order_id',$order_id);*/
		if(!$id){
			$this->error('数据错误',U('Mobile/Index/index',array('eid'=>MID)));
		}
        if(I('param.uid')){
            cookie('ExtensionId',I('param.uid'));
        }
		$map = array();$map['id'] = $id;$map['is_inside'] = 0;
		$kaquan_info = M('Coupons')->where($map)->field(true)->find();
		if(!$kaquan_info){
            $this->redirect("Mobile/Index/index");
			//$this->error('暂无法领取此卡券',U('Mobile/Index/index',array('eid'=>MID)));
		}
		
		//微信分享相关配置
		$wx = new \Common\Vendor\Jssdk();
		$signPackage = $wx->getSignPackage();
		$this->assign('signPackage',$signPackage);
		
		$share_url = U('Mobile/Index/kaquan_cont',array('id'=>$kaquan_info['id'],'uid'=>MID,'eid'=>MID));
		$title = $kaquan_info['title'];
		$description = '卡券分享';
		$goods_img = C('WEB_SMALL_LOGO');
		$this->assign('title',$title);
		$this->assign('description',$description);
		$this->assign('goods_img',$goods_img);
		$this->assign('share_url',$share_url);
		
		$kaquan_info['reduce_cost'] = Intval($kaquan_info['reduce_cost']);
		$kaquan_info['least_cost'] = Intval($kaquan_info['least_cost']);
		if($kaquan_info['rank_id'] == 'DISCOUNT'){
			$kaquan_info['discount'] = (100-$kaquan_info['discount'])/10;
		}
		if(!empty($kaquan_info['is_show'])){
			$kaquan_info['is_show'] = array_filter(explode(',',$kaquan_info['is_show']));
		}
        if($kaquan_info['buy_type']==1){
            $kaquan_info['buy_money']=floatval($kaquan_info['buy_money']);
        }
		$this->assign('info',$kaquan_info);
		$this->display();
	}
    public function coupon_pay(){
        $id=I('id');
        if($id){
            session('quan_id',$id);
        }else{
            $id=session('quan_id');
        }
        $uid=$this->member_info['id'];
        if(empty($uid)){
            $this->redirect("Mobile/Login/Index");
        }
        $res=D("Common/Coupons")->get_index($id,$uid);
        if($res['status']==3){
            $this->error($res['msg'], U('Mobile/Index/kaquan_cont',array('id'=>$id)));
        }

        $page_title='购买卡券';
        $map['id']=$uid;
        $user_info=M("Member")->where($map)->field(true)->find();
        if(empty($user_info['paypassword'])){
            $userpaypass=1;
        }else{
            $userpaypass=0;
        }
        $this->assign('member_info',$user_info);
        $this->assign('kaquan_info',$res['data']);
        $this->assign('page_title',$page_title);
        $this->assign('userpaypass',$userpaypass);
        session('jump_paypass',4);
        $this->display();
    }
    public function count_total(){
        $paramdata=I('post.');
        $memberinfo=checkuserauthtype();
        $paramdata['uid']=$memberinfo['id'];
        $result=D("Common/Coupons")->count_total($paramdata);
        $this->assign($result['total_info']);
        $html=$this->fetch('cart_total');
        $return['html']=$html;
        $return['total_info']=$result['total_info'];
        //print_r($result);
        $this->ajaxReturn($return);
    }
    public function sub_order(){
        $paramdata=I('post.');
        $memberinfo=checkuserauthtype();

        $paramdata['uid']=$memberinfo['id'];
        $result=D("Common/Coupons")->sub_order($paramdata);
        $this->ajaxReturn($result);
    }

    /**
     * 领券
     */
    public function coupons_give(){
        $id = I('param.id');
        $type=I('type')?I('type'):0;//0，领券中心，1消费有礼，2小票抽奖3会员关怀4，全名发券，
        $order_id=I('order_id');
        $this->assign('type',$type);
        $this->assign('order_id',$order_id);
        $this->assign('id',$id);
        $memberinfo = checkuserauthtype();
        if($memberinfo){
            $uid=$memberinfo['id'];
        }
        $where=array();
        $where['uid'] = $uid;
        $where['coupons_id'] = $id;
        if($order_id) {
            $where['order_id'] = $order_id;
        }
        $where['code']='';
        $order_coupons = M('CouponsGet')->where($where)->count();
        $this->assign('coupons_count',$order_coupons);
        //微信分享相关配置
        $wx = new \Common\Vendor\Jssdk();
        $signPackage = $wx->getSignPackage();
        $this->assign('signPackage',$signPackage);
        $map = array();$map['id'] = $id;
        $kaquan_info = M('Coupons')->where($map)->field(true)->find();
        $kaquan_info['reduce_cost'] = Intval($kaquan_info['reduce_cost']);
        $kaquan_info['least_cost'] = Intval($kaquan_info['least_cost']);
        if($kaquan_info['rank_id'] == 'DISCOUNT'){
            $kaquan_info['discount'] = (100-$kaquan_info['discount'])/10;
        }
        if(!empty($kaquan_info['is_show'])){
            $kaquan_info['is_show'] = array_filter(explode(',',$kaquan_info['is_show']));
        }
        if($kaquan_info['buy_type']==1){
            $kaquan_info['buy_money']=floatval($kaquan_info['buy_money']);
        }
        $this->assign('info',$kaquan_info);
        $this->display();
    }
}