<?php
/** 
 * 线下优惠券
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <zhaoh@qq.com>
 */

namespace Shop\Model;
use Think\Model;
class CouponsGetModel extends Model{
    /*
     * 检查线下优惠券是否有效
     * @param $sn
     * @param $type =0 紧检测 1 检测后返回优惠信息
     * @param $checktype 0  编号 1 ID
     */
	public function check($sn,$type=1,$checktype=0,$shop_id=0){
	    $return =array('status'=>0,'info'=>'');
        if(empty($sn)){$return['info']='参数错误';return $return;}
        if(empty($shop_id))$shop_id=I('shop_id');
        $map=array();
        $map['status']=0;
        $map['confirm_time']=0;
        if($checktype==1){
           $map['id']=$sn;
        }else{
            $Weixin = new \Common\Vendor\WeixinCoupon();
            $cancel = $Weixin->cancel($sn);
            if($cancel['errcode']==0 && $cancel['card']['card_id']){
                $map['card_id']=$cancel['card']['card_id'];
            }else{
                $return['info']='优惠券无效';return $return;
            }
        }
        $map['begin_timestamp']=array('lt',NOW_TIME);
        $map['end_timestamp']=array('gt',NOW_TIME);
        $map['_string'] = "shop_id like '%,".$shop_id.",%' or shop_id='".$shop_id."' or shop_id= '0'";
        $check=$this->where($map)->count();
        if(empty($check)){
            $return['info']='优惠券无效';return $return;
        }
        $return['status']=1;
        if($type){
           $type_array=array('CASH'=>1,'DISCOUNT'=>2);
           $info=$this->where($map)->field('id,coupons_id,rank_id,discount,reduce_cost,least_cost')->find();
           $data=array();
           if(!empty($info['rank_id']) && array_key_exists($info['rank_id'],$type_array)){//线下满减满折
                $data['type']=intval($type_array[$info['rank_id']]);
                $data['discount']=$data['type']==1?floatval($info['reduce_cost']):(100-floatval($info['discount']))/100;
                $data['min']=floatval($info['least_cost']);
                $data['cash_id']=$info['id'];
                $goodsids=M('PromotExt')->where('style=6 and act_id='.$info['coupons_id'])->getField('style_ext_id',true);if(empty($goodsids))$goodsids='';
                $data['cash_goodsids']=$goodsids;
           }else{
                $data['type']=0;//线下优惠券 无优惠
           }
           $return['info']=$data;
        }else{
           $return['info']='优惠券有效';
        }
        return $return;
	}
    /**
     * 核销
     * @param $sn 编号或ID
     * @param $shop_id
     * @param $type 0  编号 1 ID
     */
    public function confirm_coupons($sn,$shop_id=0,$type=0,$code){
        $shop_id=intval($shop_id);
        $return =array('status'=>0,'info'=>'');
        if(empty($sn)){$return['info']='优惠券错误';return $return;}
        if(empty($shop_id)){$return['info']='核销门店错误';return $return;}
        $map=array();
        $map['status']=0;
        $map['confirm_time']=0;
        if($type==1){
            $map['id']=$sn;
        }else{
            $map['code']=$sn;
        }        
        $map['begin_timestamp']=array('lt',NOW_TIME);        
        $map['end_timestamp']=array('gt',NOW_TIME);
        $data=array();
        $data['confirm_time']=NOW_TIME;
        $data['confirm_shopid']=$shop_id;
        $data['status']=1;
        $id = M('CouponsGet')->where($map)->getfield('id');
        $res=$this->where($map)->save($data);
        if($res!==false){//同步到微信核销

            $Weixin = new \Common\Vendor\WeixinCoupon();
            $query_code = $Weixin->query_code($id,$code);
            
            $return['status']=1;
            $return['info']='核销成功';
            return $return;
        }else{            
            $return['info']='核销失败';
            return $return;
        }
    }
    
    /**
     * 优惠券列表
     * @param $param 分页
     */
    public function coupons_list($param){
        $shop_id=get_wxsmall_shop_id();
        $return =array('status'=>0,'info'=>'');
        if(empty($param['page'])){
            $param['page'] = 1;
        }
        $map=array();
        $map['status'] = 1;
        // $map['coupons_type'] = 1;  
        $map['is_inside'] = 0;
        $map['is_check'] = array("elt",1);
		
		if($param['use_num'] > 0){
			if(intval($param['use_num'] == 1)) $map['coupons_type'] = 1;
			else $map['coupons_type'] = 2;
		}
		if($param['discount_num'] > 0){
			if(intval($param['discount_num'] == 1)) $map['rank_id'] = 'CASH';
			else $map['rank_id'] = 'DISCOUNT';
		}
		if($param['receive_num'] > 0){
			if(intval($param['receive_num'] == 1)) $map['buy_type'] = 0;
			elseif(intval($param['receive_num'] == 2)) $map['buy_type'] = 2;
			else $map['buy_type'] = 1;
		}
		
        $map['_string'] = "(is_show like '%,".$shop_id.",%' or is_show='0') and (type = 2 or (type = 1 and end_timestamp >".NOW_TIME."))";
        //$map['_string'] = 'type = 2 or (type = 1 and end_timestamp > '.NOW_TIME.')';
        $order = 'add_time desc';
        $pagesize=empty($pagesize)?C('WEB_DEFAULT_PAGE'):$pagesize;
		// $pagesize=2;
        $list = page_list('Coupons', $map, $order, true, $pagesize,'', $param['page']);
        if($list['count'] > $pagesize*$param['page']){
            $return['show'] = 1;
        }else{
            $return['show'] = 0;
        }
        if($list['list']){   
            $return['status']=1;
            $return['info']=$list['list'];
        }else{
            $return['status']=0;
        }
        return $return;
    }
    /**
     * 收银会员优惠券列表
     * @param $param 分页
     */
    public function cashier_coupons_list($user_id=0){
        $user_id=intval($user_id);
        $return =array('status'=>0,'info'=>'');
        $where=array();
        $where['status'] = 0;
        $where['coupons_type'] = 1;
        if($user_id){//获取已领取优惠券
            $map=$where;
            $map['uid']=$user_id;
            $map['end_timestamp']=array('gt',NOW_TIME);
            $user_list=$this->where($map)->field('coupons_id,id')->select();
            
            $user_coupons=format_array2select($user_list,'coupons_id','id');
            $getlist=array_values($user_coupons);
            if(empty($getlist))$getlist=0;
            $where['id']=is_array($getlist)?array('in',$getlist):$getlist;
            
        }            
        $list = M('Coupons')->where($where)->field(true)->order('sort,add_time desc')->select();        
        foreach($list as $k=>$v){
            $list[$k]['coupons_get']=array_search($v['id'],$user_coupons);
        }
        $return['status']=1;
        $return['info']=$list;
        return $return;
    }
    /**
     * 优惠券领取
     * @param $id 优惠券id
     * @param $uid领取人
     * @param $code会员卡号
     * @param $order_id 关联订单ID;
     */
    function get_coupons($id,$uid=0,$code='',$order_id=0,$from=0,$from_temp='',$type=0){
        if(empty($uid)) {
            $memberinfo = checkuserauthtype();
            $uid = $memberinfo['id'];
        }
            if(!$uid){
                cookie('forward',U('Mobile/Index/kaquan'));
                $return['status'] = 0;
                $return['url'] = U('Mobile/Login/index');
                return $return;
            }
            $map=array();
            $map['id']=$uid;
            $member_info=M("Member")->where($map)->field(true)->find();
        $where=array();
            $where['uid'] = $uid;
            $where['coupons_id'] = $id;
            $get_coupons = M('CouponsGet')->where($where)->count();
            $coupons = M('Coupons')->where('id='.$id)->field('quantity,get_limit,end_timestamp,buy_money,buy_type')->find();
            if($coupons['quantity']<=0){
                $return['status'] = 2;
                $return['msg'] = '库存不足';
                return $return;
            }else if($get_coupons >= $coupons['get_limit']){
                $return['status'] = 2;
                $return['msg'] = '领取次数已够';
                return $return;
            }elseif (NOW_TIME > $coupons['end_timestamp'] && $coupons['end_timestamp']) {
                $return['status'] = 2;
                $return['msg'] = '优惠券已过期';
                return $return;
            }

        if($coupons['buy_type']==1) {
            if ($coupons['buy_money'] > $member_info['usepoints']) {
                $return['msg'] = '积分不足，不能购买';
                $return['status'] = 2;
                return $return;
            }
            $from=5;
            if(empty($from_temp))$from_temp='积分兑换';
        }
        if($coupons['buy_type']==2 || $type==1 || $type==2 || $type==4){
            if(empty($order_id)){
                $return['msg'] = '订单不存在';
                $return['status'] = 2;
                return $return;
            }
            $where=array();
            $where['uid'] = $uid;
            $where['coupons_id'] = $id;
            $where['order_id'] = $order_id;
            $order_coupons = M('CouponsGet')->where($where)->count();
            if($order_coupons){
                $return['msg'] = '您已经领取，不能再次领取';
                $return['status'] = 2;
                return $return;
            }
            $map=array();
            $map['id']=$order_id;
            $where['uid'] = $uid;
            $order_info=M("OrderInfo")->where($map)->field('id,pay_status')->find();
            if(empty($order_info) || $order_info['pay_status']<3){
                $return['msg'] = '您没有支付，不能领取';
                $return['status'] = 2;
                return $return;
            }
            $from=6;
            if(empty($from_temp))$from_temp='购买';
        }
        if($type==1 && empty($from_temp)){
            $from_temp='系统发放（消费有礼）';
        }if($type==2 && empty($from_temp)){
            $from_temp='小票抽奖赠品';
        }if($type==3 && empty($from_temp)){
            $from_temp='会员关怀赠券';
        }if($type==4 && empty($from_temp)){
            $from_temp='全民发券赠券';
        }
        if($from==1 && empty($from_temp))$from_temp='免费领取';
        $data = M('Coupons')->where('id='.$id)->field(true)->find();
        $add_data['coupons_id'] = $data['id'];
        $add_data['uid'] = $uid;
        $add_data['card_id'] = $data['card_id'];
        $add_data['rank_id'] = $data['rank_id'];
        $add_data['discount'] = $data['discount'];
        $add_data['reduce_cost'] = $data['reduce_cost'];
        $add_data['least_cost'] = $data['least_cost'];
        $add_data['shop_id'] = $data['is_show'];
        if($data['type'] == '1'){//固定日期
            $add_data['begin_timestamp'] = $data['begin_timestamp'];
            $add_data['end_timestamp'] = $data['end_timestamp'];
        }else{//固定时长
            $add_data['begin_timestamp'] =  NOW_TIME+$data['fixed_begin_term']*24*60*60;
            $tian = $data['fixed_term']+$data['fixed_begin_term'];
            $add_data['end_timestamp'] = NOW_TIME+$tian*24*60*60;
        }
        $add_data['add_time'] = NOW_TIME;
        $add_data['code'] = $code;
        $add_data['buy_type'] = $data['buy_type'];
        $add_data['buy_money'] = $data['buy_money'];
        $add_data['order_id'] = $order_id;
        $add_data['from'] = $from;
        $add_data['from_temp'] = $from_temp;
        if($uid)$add = M('CouponsGet')->add($add_data);
        if($add){
            if($from!=2) {//转赠的券不扣积分和库存
                switch ($data['buy_type']) {
                    case 1:
                        $msg = '使用' . floatval($data['buy_money']) . '积分兑换卡券' . $code;
                        account_change($uid, -$data['buy_money'], 4, 4, $msg);
                        break;
                }

                M('Coupons')->where('id=' . $id)->setDec('quantity', 1);
            }
            if($type==2){//小票抽奖
                D("Common/Member")->change_win_gift($order_id,$uid,1);
            }
            if($type==4) {//全民发券
                D("Common/Member")->change_win_gift($order_id, $uid, 2);
            }
            $return['data']['begin_timestamp'] = date('Y-m-d',$add_data['begin_timestamp']);
            $return['data']['end_timestamp'] = date('Y-m-d',$add_data['end_timestamp']);
            $return['data']['description'] = idtoname($id,'Coupons','description');
            $return['data']['notice'] = idtoname($id,'Coupons','notice');
            $return['data']['title'] = idtoname($id,'Coupons','title');
            $return['data']['brand_name'] = idtoname($id,'Coupons','brand_name');
            $return['data']['url'] = U('Home/qrcode/index',array('data' => $add_data['code'],'size' => '4'));
            $return['status'] = 1;
        }
        return $return;
    }
}

?>