<?php
namespace app\store\model\bargain;
use app\common\model\bargain\Active as ActiveModel;
use app\store\service\Goods as GoodsService;
class Active extends ActiveModel
{
public function getList($search = '')
{
$this->setBaseQuery($this->alias, [
['goods', 'goods_id'],
]);
if (!empty($search)) {
$this->where('goods.goods_name', 'like', "%{$search}%");
}
$list = $this->where("{$this->alias}.is_delete", '=', 0)
->order(["{$this->alias}.sort" => 'asc', "{$this->alias}.create_time" => 'desc'])
->paginate(15, false, [
'query' => \request()->request()
]);
if (!$list->isEmpty()) {
$list = GoodsService::setGoodsData($list);
}
return $list;
}
public function add($data)
{
if (!$this->onValidate($data, 'add')) {
return false;
}
$data = $this->createData($data);
return $this->allowField(true)->save($data) !== false;
}
public function edit($data)
{
if (!$this->onValidate($data, 'edit')) {
return false;
}
$data = $this->createData($data);
return $this->allowField(true)->save($data) !== false;
}
private function createData($data)
{
$data['wxapp_id'] = static::$wxapp_id;
$data['start_time'] = strtotime($data['start_time']);
$data['end_time'] = strtotime($data['end_time']);
return $data;
}
private function onValidate($data, $scene = 'add')
{
if ($scene === 'add') {
if (!isset($data['goods_id']) || empty($data['goods_id'])) {
$this->error = '请选择商品';
return false;
}
}
if (empty($data['start_time']) || empty($data['end_time'])) {
$this->error = '请选择活动的开始时间与截止时间';
return false;
}
$data['start_time'] = strtotime($data['start_time']);
$data['end_time'] = strtotime($data['end_time']);
if ($data['end_time'] <= $data['start_time']) {
$this->error = '活动结束时间必须大于开始时间';
return false;
}
return true;
}
public function setDelete()
{
return $this->allowField(true)->save(['is_delete' => 1]);
}
public static function isExistGoodsId($goodsId)
{
return !!(new static)->where('goods_id', '=', $goodsId)
->where('is_delete', '=', 0)
->value('active_id');
}
}