<?php


namespace app\shared\model;
use app\shared\model\CouponUser;
use think\Model as ThinkModel;
//优惠券
class Coupon extends ThinkModel
{
    //茶室预订
    const TYPE_HOTEL=1;
    //茶艺师
    const TYPE_TEASPECIALIST=2;
    //茶室预订
    const TYPE_GOODS=3;
    //新人注册
    const SEND_TYPE_NEW=1;
    //转发
    const SEND_TYPE_FORWARD=2;
    //领券中心
    const SEND_TYPE_RECEIVE=3;
    // 设置当前模型对应的完整数据表名称
    protected $name = 'shared_coupon';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //给用户发放优惠券
    static public function giveUserCoupon($user_id=-1,$send_type=1,$acid=1,$ids=-1){
    	if($user_id==-1){
    		return false;
    	}
    	//type 1新人注册 2转发,4邀请好友
        if($ids!=-1){
            if(empty($ids)){
                return false;
            }
            $list=self::where(['acid'=>$acid,'status'=>1,'is_delete'=>0])->where('id','in',$ids)->select()->toArray();
        }else{
            $list=self::where(['acid'=>$acid,'send_type'=>$send_type,'status'=>1,'is_delete'=>0])->select()->toArray();
        }
		foreach ($list as $key => $value) {
            if($send_type==4){
                $form=new CouponUser();
                $form->acid=$acid;
                $form->save([
                    'user_id'=>$user_id,
                    'coupon_id'=>$value['id'],
                    'type'=>$value['type'],
                ]);
            }else{
                $form=CouponUser::where(['user_id'=>$user_id,'coupon_id'=>$value['id']])->find();
                if(!$form){
                    $form=new CouponUser();
                    $form->acid=$acid;
                }
                $form->save([
                    'user_id'=>$user_id,
                    'coupon_id'=>$value['id'],
                    'type'=>$value['type'],
                ]);
            }
            
		}
        if(count($list)){
            return true;
        }
		return false;
    }
}