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

namespace common\libs\logging\operate\provider;


class BatchProvider extends AbstractProvider {

    /**
     * 格式化 sql 中的 in
     * @param array $array
     * @return string
     */
    public static function staticFormatIn(array $array){
        $array = array_unique($array);
        $in = "'" . implode("','", $array) . "'";
        return $in;
    }

    /**
     * 标准化
     * @param $data
     * @return array|bool
     */
    public function normalize($data){
        if(!$data){
            return false;
        }
        if(!$this->getLabels()){
            return false;
        }
        $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];
                    }
                }
            }
            $result[$key] = $this->handleData($this->attrLabels[$key], $value);
        }
        return $result;
    }

    /**
     * 批量获取数据
     */
    public function batchGetData(){
        if(!$this->data){
            return ;
        }
        $this->data = array_unique($this->data);
        $ids = self::staticFormatIn($this->data);
        $fetchClass = $this->fetchClass;
        if($this->select){
            $list = $fetchClass::find()->select($this->select)->where("{$this->dataType} IN (".$ids.")")->indexBy($this->dataType)->asArray()->all();
        }else{
            $list = $fetchClass::find()->selectNoText()->where("{$this->dataType} IN (".$ids.")")->indexBy($this->dataType)->asArray()->all();
        }
        $this->result = [];
        if($list){
            foreach($this->data as $id){
                if(isset($list[$id])){
                    $this->result[$id] = $this->normalize($list[$id]);
                }
            }
        }
    }

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

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

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