<?php


namespace common\services;


use common\components\AjaxException;
use common\models\Rules;
use common\util\RulesObj;
use common\util\RulesWithContentObj;
use yii\db\ActiveQuery;

class RulesService
{
    /**
     * @param $id
     * @return Rules
     * @throws AjaxException
     */
    public static function getRulesById($id): Rules
    {
        /** @var Rules $Rules */
        $Rules = self::getQuery()->andWhere(["id" => $id])->one();
        if (!$Rules) {
            throw new AjaxException("该规章不存在！");
        }
        return $Rules;
    }

    /**
     * @return ActiveQuery
     */
    public static function getQuery(): ActiveQuery
    {
        return Rules::find()->where(["delete_time" => 0]);
    }

    /**
     * @param $query
     * @return RulesObj[]
     */
    public static function getAllList($query): array
    {
        return self::dealWithList($query->select("id,rule_name,rule_content,rule_category,rule_status,create_time,end_time,update_time,version")->all());
    }

    /**
     * @param $query
     * @param $point_content
     * @return RulesWithContentObj
     */
    public static function getRuleWithContent($query, $point_content): RulesWithContentObj
    {
        $data = new RulesWithContentObj($query);
        $data->setRuleContent($point_content);
        return $data;
    }

    /**
     * @param $data
     * @return RulesObj[]
     */
    public static function dealWithList($data): array
    {
        $newData = [];
        foreach ($data as $key => $value) {
            /** @var Rules $value */
            $newData[] = new RulesObj($value);
        }
        return $newData;
    }
}