<?php


namespace common\services;


use common\components\AjaxException;
use common\models\AccidentCases;
use common\models\AccidentCasesRelateToDictionary;
use Yii;
use yii\db\Exception;

class AccidentCasesRelateToDictionaryService
{
    public static function add(AccidentCases $AccidentCases): void
    {
        $param = [
            "dictionary_id", "accident_cases_id",
        ];
        $data = [];
        //事件性质（等级）
        $data[] = ["dictionary_id" => $AccidentCases->level];
        //事件类型—基本选项 数组
        $typeBaseArray = json_decode($AccidentCases->type_base);
        foreach ($typeBaseArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //事件类型-一级字段 数组
        $typeFirstArray = json_decode($AccidentCases->type_first);
        foreach ($typeFirstArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //事件类型-二级字段 数组
        $typeSecondArray = json_decode($AccidentCases->type_second);
        foreach ($typeSecondArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //事件类型-三级字段 数组
        $typeThirdArray = json_decode($AccidentCases->type_third);
        foreach ($typeThirdArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //事件类型—复合选项 数组
        $typeExtraArray = json_decode($AccidentCases->type_extra);
        foreach ($typeExtraArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //责任专业—事件归因
        $dutyCategoryArray = json_decode($AccidentCases->duty_category);
        foreach ($dutyCategoryArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //责任专业—原因
        $dutyReasonArray = json_decode($AccidentCases->duty_reason);
        foreach ($dutyReasonArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //日期特征
        $data[] = ["dictionary_id" => $AccidentCases->day_type];
        //时间特征
        $data[] = ["dictionary_id" => $AccidentCases->time_type];
        //所属线路
        $data[] = ["dictionary_id" => $AccidentCases->line];
        //自动化程度
        $data[] = ["dictionary_id" => $AccidentCases->automation_level];
        //信号供应商
        $data[] = ["dictionary_id" => $AccidentCases->signal_supplier];
        //车号
        $data[] = ["dictionary_id" => $AccidentCases->train_number];
        //列车编组
        $data[] = ["dictionary_id" => $AccidentCases->train_group];
        //列车型号
        $data[] = ["dictionary_id" => $AccidentCases->train_model];
        //发生位置-基本分类-二级字段  数组
        $positionBaseSecondArray = json_decode($AccidentCases->position_base_second);
        foreach ($positionBaseSecondArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //发生位置-派生-二级字段  数组
        $positionExtraSecondArray = json_decode($AccidentCases->position_extra_second);
        foreach ($positionExtraSecondArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //变电站类型
        $substation_typeArray = json_decode($AccidentCases->substation_type);
        foreach ($substation_typeArray as $value) {
            $data[] = ["dictionary_id" => $value];
        }
        //影响范围
        $data[] = ["dictionary_id" => $AccidentCases->incidence];
        //重组，添加上accident_cases_id
        foreach ($data as $key => $value) {
            if ($value["dictionary_id"] == 0 || $value["dictionary_id"] == "" || $value["dictionary_id"] == "[]" || $value["dictionary_id"] == [] || $value["dictionary_id"] == null) {
                unset($data[$key]);
            } else {
                $data[$key]["accident_cases_id"] = $AccidentCases->id;
            }
        }
        //需要改造成batchInsert来节约资源
        Yii::$app->db->createCommand()->batchInsert(AccidentCasesRelateToDictionary::tableName(), $param, $data)->execute();
    }

    /**
     * @param AccidentCases $AccidentCases
     * @return void
     * @throws Exception
     */
    public static function update(AccidentCases $AccidentCases): void
    {
        $relationData = [];
        $needUpdateZero = [];
        $needUpdate = [];
        $needAdd = [];
        $zeroList = [];
        $AccidentCasesRelationshipList = AccidentCasesRelateToDictionary::find()
            ->where(["accident_cases_id" => $AccidentCases->id])
            ->asArray()->all();
        foreach ($AccidentCasesRelationshipList as $AccidentCasesRelationship) {
            if ($AccidentCasesRelationship["dictionary_id"] == 0) {
                $zeroList[] = $AccidentCasesRelationship["id"];
            } else {
                $relationData[$AccidentCasesRelationship["dictionary_id"]] = [$AccidentCasesRelationship["id"], $AccidentCasesRelationship["dictionary_id"]];
            }
        }
        //事件性质（等级）
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "level");
        //事件类型—基本选项 数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "type_base");
        //事件类型-一级字段 数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "type_first");
        //事件类型-二级字段 数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "type_second");
        //事件类型-三级字段 数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "type_third");
        //事件类型—复合选项 数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "type_extra");
        //责任专业—事件归因
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "duty_category");
        //责任专业—原因
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "duty_reason");
        //日期特征
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "day_type");
        //时间特征
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "time_type");
        //所属线路
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "line");
        //自动化程度
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "automation_level");
        //信号供应商
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "signal_supplier");
        //车号
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "train_number");
        //列车编组
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "train_group");
        //列车型号
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "train_model");
        //发生位置-基本分类-二级字段  数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "position_base_second");
        //发生位置-派生-二级字段  数组
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "position_extra_second");
        //变电站类型
        self::dealWithNeedArrayData($needAdd, $relationData, $AccidentCases, "substation_type");
        //影响范围
        self::dealWithNeedUpdateSingleData($needAdd, $relationData, $AccidentCases, "incidence");
        //根据needAdd的数量将needUpdateZero和zeroList变为needUpdate
        foreach ($needAdd as $key => $value) {
            if ($relationData != []) {
                unset($needAdd[$key]);
                $AccidentCasesRelationshipData = array_shift($relationData);
                $needUpdate[] = [$AccidentCasesRelationshipData[0], $value["dictionary_id"]];
            } elseif ($zeroList != []) {
                unset($needAdd[$key]);
                $needUpdate[] = [array_shift($zeroList), $value["dictionary_id"]];
            } else {
                break;
            }
        }
        //多余的数据$relationData转成needUpdateZero
        foreach ($relationData as $value) {
            $needUpdateZero[] = $value[0];
        }
        //都更新完了还不够用，那就存储$needAdd
        if ($needAdd != []) {
            $param = [
                "accident_cases_id", "dictionary_id"
            ];
            Yii::$app->db->createCommand()->batchInsert(AccidentCasesRelateToDictionary::tableName(), $param, $needAdd)->execute();
        }
        //执行needUpdateZero
        if ($needUpdateZero != []) {
            AccidentCasesRelateToDictionary::updateAll(["dictionary_id" => 0], ["id" => $needUpdateZero]);
        }
        //执行needUpdate
        foreach ($needUpdate as $value) {
            Yii::$app->db->createCommand()->update(AccidentCasesRelateToDictionary::tableName(), ['dictionary_id' => $value[1]], ["id" => $value[0]])->execute();
        }
    }

    public static function delete(AccidentCases $AccidentCases): void
    {
        //关系真删除
        AccidentCasesRelateToDictionary::deleteAll(["accident_cases_id" => $AccidentCases->id]);
    }

    protected static function dealWithNeedUpdateSingleData(&$needAdd, &$relationData, AccidentCases $AccidentCases, $param_name): void
    {
        if ($AccidentCases->$param_name != "" && $AccidentCases->$param_name != null) {
            if (isset($relationData[$AccidentCases->$param_name])) {
                //老数据存在的，就不做处理
                unset($relationData[$AccidentCases->$param_name]);
            } else {
                //老数据不存在,塞到添加列表里面
                $needAdd[] = ["accident_cases_id" => $AccidentCases->id, "dictionary_id" => $AccidentCases->$param_name];
            }
        }
    }

    /**
     * @param $needAdd
     * @param $relationData
     * @param AccidentCases $AccidentCases
     * @param $param_name
     * @return void
     * @throws AjaxException
     */
    protected static function dealWithNeedArrayData(&$needAdd, $relationData, AccidentCases $AccidentCases, $param_name): void
    {
        $array = json_decode($AccidentCases->$param_name);
        if (!is_array($array)) {
            throw new AjaxException("{$param_name}数据传入错误，不是数组！");
        }
        foreach ($array as $value) {
            if ($value !== null && $value !== "") {
                if (isset($relationData[$AccidentCases->$param_name])) {
                    //老数据存在的，就不做处理
                    unset($relationData[$AccidentCases->$param_name]);
                } else {
                    //老数据不存在,塞到添加列表里面
                    $needAdd[] = ["accident_cases_id" => $AccidentCases->id, "dictionary_id" => $value];
                }
            }
        }
    }

    /**
     * @throws AjaxException
     */
    protected static function dealWithNeedArrayDataOld(&$needUpdateZero, &$needAdd, $relationData, AccidentCases $AccidentCases, $param_name): void
    {
        $array = json_decode($AccidentCases->$param_name);
        if (!is_array($array)) {
            throw new AjaxException("{$param_name}不是数组！");
        }
        if (isset($relationData[$param_name])) {
            foreach ($relationData[$param_name] as $key => $value) {
                $arrayKey = array_search($relationData[$param_name][$key][1], $array);
                if ($arrayKey !== false) {
                    unset($array[$arrayKey]);
                } else {
                    $needUpdateZero[] = $value[0];
                }
            }
        }
        foreach ($array as $value) {
            if ($value !== null && $value !== "") {
                $needAdd[] = ["accident_cases_id" => $AccidentCases->id, "dictionary_id" => $value];
            }

        }
    }

    protected static function dealWithNeedDeleteData(&$needUpdateZero, $relationData, $param_name): void
    {
        if (isset($relationData[$param_name])) {
            foreach ($relationData[$param_name] as $key => $value) {
                $needUpdateZero[] = $value[0];
            }
        }
    }


    protected static function dealWithNeedUpdateSingleDataOld(&$needUpdate, &$needUpdateZero, &$needAdd, $relationData, AccidentCases $AccidentCases, $param_name): void
    {
        if (isset($relationData[$param_name])) {
            foreach ($relationData[$param_name] as $key => $value) {
                if ($key < 1) {
                    if ($relationData[$param_name][$key][1] != $AccidentCases->$param_name) {
                        if ($AccidentCases->$param_name !== null && $AccidentCases->$param_name !== "") {
                            $needUpdate[] = [$value[0], $AccidentCases->$param_name];
                        } else {
                            $needUpdateZero[] = $value[0];
                        }
                    }
                } else {
                    $needUpdateZero[] = $value[0];
                }
            }
        } else {
            if ($AccidentCases->$param_name !== null && $AccidentCases->$param_name !== "") {
                $needAdd[] = ["accident_cases_id" => $AccidentCases->id, "dictionary_id" => $AccidentCases->$param_name];
            }
        }
    }
}