// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\common\model\bargain; use cores\BaseModel; use app\common\library\helper; /** * 砍价任务模型 * Class Task * @package app\common\model\bargain */ class Task extends BaseModel { // 定义表名 protected $name = 'bargain_task'; // 定义主键 protected $pk = 'task_id'; // 定义别名 protected string $alias = 'task'; // 强制类型转换 protected $type = [ 'is_floor' => 'integer', 'is_buy' => 'integer', 'status' => 'integer', 'is_delete' => 'integer', ]; /** * 追加的字段 * @var array $append */ protected $append = [ 'is_end', // 是否已结束 'surplus_money', // 剩余砍价金额 'bargain_rate', // 砍价进度百分比(0-100) ]; /** * 关联用户表 * @return \think\model\relation\BelongsTo */ public function user() { $module = self::getCalledModule(); return $this->BelongsTo("app\\{$module}\\model\\User"); } /** * 获取器:任务结束时间 * @param $value * @return false|string */ public function getEndTimeAttr($value) { return \format_time($value); } /** * 获取器:活动是否已结束 * @param $value * @param $data * @return false|string */ public function getIsEndAttr($value, $data) { return $value ?: $data['end_time'] <= time(); } /** * 获取器:剩余砍价金额 * @param $value * @param $data * @return false|string */ public function getSurplusMoneyAttr($value, $data) { $maxCutMoney = helper::bcsub($data['goods_price'], $data['floor_price']); return $value ?: helper::bcsub($maxCutMoney, $data['cut_money']); } /** * 获取器:砍价进度百分比 * @param $value * @param $data * @return string */ public function getBargainRateAttr($value, $data) { $maxCutMoney = helper::bcsub($data['goods_price'], $data['floor_price']); $rate = helper::bcmul(helper::bcdiv($data['cut_money'], $maxCutMoney), 100); return $value ?: $rate; } /** * 获取器:砍价金额区间 * @param $value * @return mixed */ public function getSectionAttr($value) { return helper::jsonDecode($value); } /** * 修改器:砍价金额区间 * @param $value * @return string */ public function setSectionAttr($value) { return helper::jsonEncode($value); } /** * 砍价任务详情 * @param int $taskId * @param array $with * @return static|array|null */ public static function detail(int $taskId, array $with = []) { // 砍价任务详情 $model = static::get($taskId, $with); // 标识砍价任务过期 return static::autoSetEnd($model); } /** * 检测并标识砍价任务过期状态 * @param Task $model * @return Task */ private static function autoSetEnd(self $model): Task { if (!empty($model) && $model['status'] == 1 && $model->getData('end_time') <= time()) { $model->save(['status' => 0]); } return $model; } }