<?php
/**
 * Created by PhpStorm.
 * User: sunmoon<i@liming.me>
 * Date: 2019/07/29
 * Time: 上午9:39
 */


namespace common\libs\logging\operate\provider;


use yii\base\Exception;

class SingleProvider extends AbstractProvider {

    /**
     * 标准化
     * @param null $data
     * @return bool
     */
    public function normalize($data = null){
        if(!$data){
            return false;
        }
        if(!$this->getLabels()){
            return false;
        }
        $this->result = [];
        foreach($data as $key => $value){
            if(!isset($this->attrLabels[$key])) continue;
            if($this->needCompose($this->attrLabels[$key])){
                $value = [$value];
                foreach($this->attrLabels[$key]['compose'] as $field){
                    if(isset($data[$field])){
                        $value[] = $data[$field];
                    }
                }
            }
            $this->result[$key] = $this->handleData($this->attrLabels[$key], $value);
        }
        return true;
    }

    /**
     * @return bool
     */
    public function singleGetData(){
        if(!$this->data){
            return false;
        }
        // 说明传入的是delete id
        // data必须和dateType对应
        if(is_string($this->data)){
            if(!$this->dataType){
                return false;
            }
            $fetchClass = $this->fetchClass;
            if($this->select){
                $row = $fetchClass::find()->select($this->select)->is($this->data, $this->dataType)->asArray()->one();
            }else{
                $row = $fetchClass::find()->selectNoText()->is($this->data, $this->dataType)->asArray()->one();
            }
            $this->normalize($row);
            unset($fetchClass, $row);
        }else{
            $this->normalize($this->data);
        }
        return true;
    }

    public function beforeUpdate(){
        $this->singleGetData();
    }

    public function afterUpdate(){
        $this->singleGetData();
    }


    public function beforeDelete(){
        $this->singleGetData();
    }


    public function afterInsert(){
        $this->singleGetData();
    }
}