<?php


namespace common\services;


use common\models\DictionaryRelationship;

class DictionaryRelationshipService
{
    public static function getDictionaryDeriveInfo(): array
    {
        $data = [];
        $DictionaryRelationshipList = DictionaryRelationship::find()->alias('r')
            ->join('LEFT JOIN', 'dictionary d', 'd.id = r.relation_id')
            ->select("r.*,d.param_name")->asArray()->all();
        foreach ($DictionaryRelationshipList as $DictionaryRelationship){
            $data[$DictionaryRelationship["dictionary_id"]][] = $DictionaryRelationship;
        }
        return $data;
    }

    public static function addByDerive($deriveList, $dictionary_id): void
    {
        foreach ($deriveList as $derive) {
            $relationship = DictionaryRelationship::findOne(["dictionary_id" => $dictionary_id, "relation_id" => $derive["deriver_id"]]);
            if (!$relationship) {
                $relationship = new DictionaryRelationship();
                $relationship->dictionary_id = $dictionary_id;
                $relationship->relation_id = $derive["deriver_id"];
                $relationship->save();
            }
        }
    }

    public static function updateByDerive($deriveList, $dictionary_id): void
    {
        $relationshipList = DictionaryRelationship::find()->where(["dictionary_id" => $dictionary_id])->all();
        if ($relationshipList) {
            foreach ($relationshipList as $key => $relationship) {
                /** @var  DictionaryRelationship $relationship */
                $relationship->relation_id = $deriveList[$key]["deriver_id"];
                $relationship->save();
            }
        } else {
            self::addByDerive($deriveList, $dictionary_id);
        }
    }
}