<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 优惠券管理
 */
namespace app\smartbc\model;
use think\Model;

class SmartbcCoupon extends Model{

    protected $pk = 'id';
    protected $table = 'ai_smartbc_coupon';

    /**
     * 好店信息
     * @return void
     */
    public function store(){
        return $this->hasOne('SmartbcStore','id','store_id');
    }
    
    /**
     * 用户已领油
     * @return void
     */
    public function couponuser(){
        return $this->hasOne('SmartbcCouponUser','coupon_id','id');
    }


    //搜索好店名称
    public function searchNameAttr($query,$value){
        if(!empty($value)){
            $query->where('name','like', '%'.$value .'%');
        }
    }

    //添加或编辑
    public function edit($param){
        $data['store_id']    = trim($param['store_id']);
        $data['name']        = trim($param['name']);
        $data['pay_price']   = trim($param['pay_price']);
        $data['img']         = trim($param['img']);
        $data['update_time'] = time();
        if(isset($param['id'])){
            $condition['id'] = $param['id'];
            $condition['member_miniapp_id'] = $param['miniapp_id'];
            return self::save($data,$condition);
        }else{
            $data['create_time']         = time();
            $data['member_miniapp_id']   = $param['miniapp_id'];
            return self::insert($data);
        }
    } 

     /**
     * 店铺和优惠券联查(API) 带翻页,不包含店铺信息
     * VIP\Coupon
     * @return void
     */
    public static function couponList(array $condition,int $page = 6){
        return self::where($condition)->order('is_top desc,sort desc,sort desc')->paginate($page,true);
    } 

    /**
     * 店铺和优惠券联查(API) 带翻页,包含店铺信息
     *  VIP\Coupon
     * @return void
     */
    public static function storeCoupon(array $condition,int $page = 6){
        return self::with('store')->where($condition)->order('is_top desc,sort desc,size desc')->paginate($page,true);
    } 
}