<?php


namespace common\services;


use common\models\EmergencyResponse;
use common\models\EmergencyResponseRelateToRulesPoints;
use common\models\OperationalAdjustments;
use common\models\OperationalAdjustmentsRelateToRulesPoints;
use Yii;

class RulesPointsRelationshipService
{
    public static function addEmergencyResponseRelationship(EmergencyResponse $model): void
    {
        self::add($model, "EmergencyResponse");
    }

    public static function addOperationalAdjustmentsRelationship(OperationalAdjustments $model): void
    {
        self::add($model, "OperationalAdjustments");
    }

    public static function updateEmergencyResponseRelationship(EmergencyResponse $model): void
    {
        self::update($model, "EmergencyResponse");
    }

    public static function updateOperationalAdjustmentsRelationship(OperationalAdjustments $model): void
    {
        self::update($model, "OperationalAdjustments");
    }

    protected static function add($model, $type): void
    {
        $data = [];
        //规章 数组
        $rulesPointIds = [];
        /**
         * [
         *      {"rule_id":1,"point":["1"]},
         *      {"rule_id":2,"point":["1","2"]}
         * ]
         */
        /** @var  OperationalAdjustments $model */
        /** @var  EmergencyResponse $model */
        $rulesArray = json_decode($model->rules, true);
        foreach ($rulesArray as $rules) {
            $ids = array_column(RulesPointsService::getRulesPointsQuery()->select("id")->andWhere(["rule_id" => $rules["rule_id"], "point" => $rules["point"]])->all(), "id");
            $rulesPointIds = array_merge($rulesPointIds, $ids);
        }
        foreach ($rulesPointIds as $rules_point_id) {
            if ($type === "OperationalAdjustments") {
                $data[] = [
                    "operational_adjustments_id" => $model->id,
                    "rules_point_id" => $rules_point_id,
                ];
            } else {
                $data[] = [
                    "emergency_response_id" => $model->id,
                    "rules_point_id" => $rules_point_id,
                ];
            }
        }
        if ($type === "OperationalAdjustments") {
            $param = [
                "operational_adjustments_id", "rules_point_id",
            ];
            $tableName = OperationalAdjustmentsRelateToRulesPoints::tableName();
        } else {
            $param = [
                "emergency_response_id", "rules_point_id",
            ];
            $tableName = EmergencyResponseRelateToRulesPoints::tableName();
        }
        //需要改造成batchInsert来节约资源
        Yii::$app->db->createCommand()->batchInsert($tableName, $param, $data)->execute();
    }

    protected static function update($model, $type): void
    {
        $relationData = [];
        $needUpdate = [];
        $needUpdateZero = [];
        $needAdd = [];
        $zeroList = [];
        //查询关系表
        /** @var  OperationalAdjustments $model */
        /** @var  EmergencyResponse $model */
        if ($type === "OperationalAdjustments") {
            $RelationshipList = OperationalAdjustmentsRelateToRulesPoints::find()
                ->where(["operational_adjustments_id" => $model->id])
                ->select("id,rules_point_id")->asArray()->all();
            $tableName = OperationalAdjustmentsRelateToRulesPoints::tableName();
        } else {
            $RelationshipList = EmergencyResponseRelateToRulesPoints::find()
                ->where(["emergency_response_id" => $model->id])
                ->select("id,rules_point_id")->asArray()->all();
            $tableName = EmergencyResponseRelateToRulesPoints::tableName();
        }
        foreach ($RelationshipList as $Relationship) {
            if ($Relationship["rules_point_id"] == 0) {
                $zeroList[] = $Relationship["id"];
            } else {
                $relationData[] = [$Relationship["id"], $Relationship["rules_point_id"]];
            }
        }
        //规章 数组
        self::dealWithNeedArrayData($needUpdateZero, $needAdd, $relationData, $model, $type);
        //处理数据
        //根据needAdd的数量将needUpdateZero和zeroList变为needUpdate
        foreach ($needAdd as $key => $value) {
            if ($needUpdateZero != []) {
                unset($needAdd[$key]);
                $needUpdate[] = [array_shift($needUpdateZero), $value["rules_point_id"]];
            } elseif ($zeroList != []) {
                unset($needAdd[$key]);
                $needUpdate[] = [array_shift($zeroList), $value["rules_point_id"]];
            } else {
                break;
            }
        }
        //都更新完了还不够用，那就存储$needAdd
        if ($needAdd != []) {
            if ($type === "OperationalAdjustments") {
                $param = [
                    "operational_adjustments_id", "rules_point_id"
                ];
            } else {
                $param = [
                    "emergency_response_id", "rules_point_id"
                ];
            }
            Yii::$app->db->createCommand()->batchInsert($tableName, $param, $needAdd)->execute();
        }
        //执行needUpdateZero
        if ($needUpdateZero != []) {
            if ($type === "OperationalAdjustments") {
                OperationalAdjustmentsRelateToRulesPoints::updateAll(["rules_point_id" => 0], ["id" => $needUpdateZero]);
            } else {
                EmergencyResponseRelateToRulesPoints::updateAll(["rules_point_id" => 0], ["id" => $needUpdateZero]);
            }
        }
        //执行needUpdate
        foreach ($needUpdate as $value) {
            Yii::$app->db->createCommand()->update($tableName, ['rules_point_id' => $value[1]], ["id" => $value[0]])->execute();
        }
    }
    protected static function dealWithNeedArrayData(&$needUpdateZero, &$needAdd, $relationData, $model, $type): void
    {
        $rulesPointIds = [];
        /** @var  OperationalAdjustments $model */
        /** @var  EmergencyResponse $model */
        $rulesArray = json_decode($model->rules, true);
        foreach ($rulesArray as $rules) {
            $ids = array_column(RulesPointsService::getRulesPointsQuery()->select("id")->andWhere(["rule_id" => $rules["rule_id"], "point" => $rules["point"]])->all(), "id");
            $rulesPointIds = array_merge($rulesPointIds, $ids);
        }
        foreach ($relationData as $key => $value) {
            $arrayKey = array_search($relationData[$key][1], $rulesPointIds);
            if ($arrayKey !== false) {
                unset($rulesPointIds[$arrayKey]);
            } else {
                $needUpdateZero[] = $value[0];
            }
        }
        foreach ($rulesPointIds as $value) {
            if ($type === "OperationalAdjustments") {
                $needAdd[] = ["operational_adjustments_id" => $model->id, "rules_point_id" => $value];
            } else {
                $needAdd[] = ["emergency_response_id" => $model->id, "rules_point_id" => $value];
            }
        }
    }
}