<?php
declare (strict_types=1);

namespace app\store\model\server;

use app\common\model\server\ServerRecovery as BaseServerRecovery;

class ServerRecovery extends BaseServerRecovery
{
    /**
     * @notes:新增
     * @param $data
     * @return bool
     * @author: wanghousheng
     */
    public function add($data): bool
    {
        $data['store_id'] = self::$storeId;
        return $this->save($data);
    }

    /**
     * @notes:编辑
     * @param $data
     * @return bool
     * @author: wanghousheng
     */
    public function edit($data): bool
    {
        // 是否删除图片
        !isset($data['image_id']) && $data['image_id'] = 0;
        return $this->save($data) !== false;
    }

    /**
     * @notes:删除
     * @param array $recoveryId
     * @return bool
     * @author: wanghousheng
     */
    public function remove(array $recoveryId): bool
    {
        return static::whereIn('server_id', $recoveryId)->delete();
    }

    /**
     * 修改回收状态
     * @param array $recoveryIds 商品id集
     * @param bool $state 为true表示上架
     * @return bool|false
     */
    public function setStatus(array $recoveryIds, bool $state): bool
    {
        // 批量更新记录
        return static::updateBase(['status' => $state ? 1 : 2], [['recovery_id', 'in', $recoveryIds]]);
    }

    public function getDetail(int $recoveryId)
    {
        return static::detail($recoveryId, ['image', 'category']);
    }

    public static function deleteRecoveryId($data, bool $force = false)
    {
                // 传入空值(包括空字符串和空数组)的时候不会做任何的数据删除操作,但传入0则是有效的
                if (empty($data) && 0 !== $data) {
                    return false;
                }
                $model = (new static());
        
                $query = $model->db(false);
        
                // 仅当强制删除时包含软删除数据
                if ($force) {
                    $query->removeOption('soft_delete');
                }
        
                if (is_array($data) && key($data) !== 0) {
                    $query->where($data);
                    $data = null;
                } elseif ($data instanceof \Closure) {
                    call_user_func_array($data, [&$query]);
                    $data = null;
                } elseif (is_null($data)) {
                    return false;
                }
        
                $resultSet = $query->select($data);
        
                foreach ($resultSet as $result) {
                    /** @var Model $result */
                    $result->force($force)->delete();
                }
        
                return true;
    }
}