<?php
/**
 * 礼品卡
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class GiftCardController extends BaseController{
    public function _initialize(){
        parent::_initialize();
        $shops=M('Shops')->where('status=1')->field('id,name')->select();
        foreach ($shops as $key => $value) {
        	$shops_arr[$value['id']]=$value['name'];
        }
        $this->assign('shops_arr',$shops_arr);
        $this->card_status=array('0'=>'未激活','1'=>'已激活','2'=>'已作废','3'=>'已售出');$this->assign('card_status',$this->card_status);
    }
    public function index(){
    	$name = CONTROLLER_NAME;
    	$postdata=I('param.');
    	
		$map=array();
		$keyword=$postdata['keyword']; 
        if($keyword){    
            $map['id|card_sn'] = array('like','%'.$keyword.'%');
        }
		if(is_numeric($postdata['status'])){
			if($postdata['status'] == 3){
				$map['sell_time']=array('gt',0);
			}else{
				$map['status']=$postdata['status'];
			}
		}
        if($postdata['shop_id'])$map['shop_id']=$postdata['shop_id'];
        if($postdata['reg_from'])$map['addtime'][] = array('egt',strtotime($postdata['reg_from']));
        if($postdata['reg_to'])$map['addtime'][] = array('elt',strtotime($postdata['reg_to'])+24*3600);
		
    	$list=page_list('GiftCard',$map,'id desc',true,20);
		$all_money = M('GiftCard')->where($map)->sum('card_money');
		$all_price = M('GiftCard')->where($map)->sum('shop_price');
		
    	$this->assign($list);
		$this->assign('all_money',$all_money);
		$this->assign('all_price',$all_price);
    	$this->assign($postdata);
        $this->display();
    }
    /**
     * 添加礼品卡
     */
    public function view(){
        $this->display();
    }
    /**
    *编辑里礼品卡
    */
    public function edit(){
    	$id=I('id');
        if(empty($id))$this->error('参数不正确');
        $info=M(CONTROLLER_NAME)->where('id='.$id)->find();
        $this->assign($info);
        $this->display();
    }
    /**
    *批量生成礼品卡
    */
    public function insert(){
    	$name = CONTROLLER_NAME;
    	$postdata=I('post.');
		if($postdata){
			if($postdata['card_money'] <= 0){
				$this->error('面值必须大于零');exit;
			}
			if(floatval($postdata['shop_price']) <= 0){
				$this->error('售价必须大于零');exit;
			}
			if(intval($postdata['start_sn']) > intval($postdata['end_sn'])){
				$this->error('结束卡号必须大于等于开始卡号');exit;
			}
			$end_time = $shop_id = 0;
			if($postdata['end_time']) $end_time = strtotime($postdata['end_time']);
			if($postdata['shop_id']) $shop_id = strtotime($postdata['shop_id']);
			
			$start = $end = 0;
			$start = $postdata['start_sn'];$end = $postdata['end_sn'];
			$num = intval($end)-intval($start);
			if($num > 1000) {$this->error('一次最多只能生产1千张卡');exit;}
			$sn_arr = array();
			for($i=$start;$i<=$end;$i++){
				$sn_arr[] = str_pad($i,strlen($end),0,STR_PAD_LEFT);
			}
			$map = array();$map['card_sn']=array('in',$sn_arr);
			$count = M($name)->where($map)->count();
			if($count){
				$this->error('卡号已存在');exit;
			}else{
				foreach($sn_arr as $v){
					$arr['shop_id'] = $shop_id;
					$arr['addtime'] = NOW_TIME;
					$arr['end_time'] = $end_time;
					$arr['card_money'] = $postdata['card_money']?$postdata['card_money']:1;
					$arr['shop_price'] = floatval($postdata['shop_price']);
					$arr['status'] = 0;//未激活
					$arr['card_sn'] = $v;
					$arr['password'] = $this->get_pass();
					$card = M($name)->add($arr);
				}
				if($card !== false){
					$this->success('添加成功',U('index'));
				}else{
					$this->error('添加失败');
				}
			}				
		}else{
			$this->error('参数错误');exit;
		}
    }
    /**
    *编辑礼品卡
    */
    public function update(){
    	$postdata=I('post.');
    	if(!empty($postdata)){
    		if(empty($postdata['id']))$this->error('参数错误',U('index'));
    		$map=$save=array();
    		if($postdata['card_sn']){
    			$map['card_sn']=$postdata;
    		    $map['id']=array('neq',$postdata['id']);
    		    $count=M('GiftCard')->where($map)->count();
    		    if($count)$this->error('该卡号已被使用');
    		}		
    		$save=$postdata;
    		$save['id']=$postdata['id'];
			$result = M('GiftCard')->save($save);
			if($result!==false){
				$this->success('修改成功',U('index'));
			} else {
				$this->error('修改失败',U('index'));
			}
		}
    }

    public function delete(){
    	$postdata=I('param.');
    	$ids=$postdata['id'];
        empty($ids) && $this->error('参数错误！');
        if(is_array($ids)){
            $map['id'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }
        $res = M('GiftCard')->where($map)->delete();
        if($res !== false){
            $this->success('删除成功！');
        }else {
            $this->error('删除失败！');
        }
    }

    //随机生成8位数字密码
	private function get_pass(){
		$pass=randStr(8,'0123456789');
		return $pass;
	}

    //导出列表
    public function export(){

        $postdata=I('param.');       
        $name = CONTROLLER_NAME;
        $list=D('Common/GiftCard')->all_gift_card($postdata,$postdata['status'],1,'','',3);
        $result=$list['list'];
        if($postdata['status']==0 && is_numeric($postdata['status'])){
        	$export_data=$this->easy_exprot($result);
        }else{
        	$export_data=$this->hard_exprot($result);
        }        
        export_xls($export_data['title'],$export_data['data'],'utf8');
        unset($title,$data);exit;
    }
    public function hard_exprot($result=array()){
    	$return=array('title'=>'','data'=>'');
        $title=array('礼品卡号','激活码','面值','激活会员','售价','绑定店铺','店铺收银员','店铺导购员','购买会员','卡片状态','激活时间','销售时间','有效时间（截止时间）','添加时间');
        foreach($result as $k => $v){
            $data[$k][]=$v['card_sn'];
            $data[$k][]='#'.$v['password'];
            $data[$k][]=$v['card_money'];
            if($v['bind_uid']) $data[$k][] = idtoname($v['bind_uid'],'Member','mobile','id',false);
            else $data[$k][] = '暂无';            
            $data[$k][]=$v['shop_price'];

            if($v['shop_id']) $data[$k][]=idtoname($v['shop_id'],'Shops','name','id',false);
            else $data[$k][]= '暂无';

            if($v['cashier']) $data[$k][]=idtoname($v['cashier'],'ShopsAccount','name','id',false);
            else $data[$k][]= '暂无';


            if($v['daogou']) $data[$k][]=idtoname($v['daogou'],'ShopsAccount','name','id',false);
            else $data[$k][]= '暂无';

            if($v['buy_uid']) $data[$k][] = idtoname($v['buy_uid'],'Member','mobile','id',false);
            else $data[$k][] = '暂无';

            if($v['status']==0) $data[$k][] = '未激活';
            if($v['status']==1) $data[$k][] = '已激活';
            if($v['status']==2) $data[$k][] = '已作废';

            
            if($v['bind_time']) $data[$k][]=time_format($v['bind_time'],'Y-m-d');
            else $data[$k][]= '暂无';

            if($v['sell_time']) $data[$k][]=time_format($v['sell_time'],'Y-m-d');
            else $data[$k][]= '暂无';

            if($v['end_time']) $data[$k][]=time_format($v['end_time']);
            else $data[$k][]= '长期有效';
            if($v['addtime']) $data[$k][]=time_format($v['addtime']);
            else $data[$k][]= '暂无';
        }
        $return['title']=$title;
        $return['data']=$data;
        return $return;
    }
    public function easy_exprot($result=array()){
    	$return=array('title'=>'','data'=>'');
        $title=array('礼品卡号','激活码','面值');
        foreach($result as $k => $v){
            $data[$k][]=$v['card_sn'];
            $data[$k][]=$v['password'];
            $data[$k][]=$v['card_money'];
        }
        $return['title']=$title;
        $return['data']=$data;
        return $return;
    }
    //end
}