<?php

namespace Application\Service\Extension\Formatter;

use Application\Service\Extension\Laminas;
use Application\Service\Extension\Uploader\adapter\Oss;
use Laminas\Json\Json;

class Formatter
{
    protected array $defaultHandler = [
        'create_time' => 'createTimeHandler',
        'update_time' => 'updateTimeHandler',
        'create_user_id' => 'createByHandler',
        'reference_file' => 'referenceFileHandler',
    ];

    public function createTimeHandler($value = null)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function updateTimeHandler($value = null)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function createByHandler($value = null)
    {
        return current(Laminas::$serviceManager->adminUser->fetchOne([
            'columns' => ['realname'],
            'where' => [
                'id' => $value
            ]
        ])) ?: 'unkonwn';
    }

    /**
     * @note 将上传的附件地址的前缀去掉
     * @param $value
     * @return array|null[]|null
     */
    public function referenceFileHandler($value = null): ?array
    {
        $value = is_array($value) ? $value : (is_null($value) ? Json::decode($value, Json::TYPE_ARRAY) : [$value]);
        self::formatUploadFile($value);
        return $value;
    }

    public static function formatUploadFile(array &$fileData) {
        array_walk($fileData, function (&$item) {
           $item['url'] = str_ireplace(Oss::getUploadDomain(), '', $item['url']);
        });
    }
    /**
     * @param array $data
     * @param BaseFormatter|null $handlerClass
     */
    public static function format(array &$data, BaseFormatter $handlerClass = null)
    {
        $handlerClass = $handlerClass ?: new BaseFormatter();
        // 非一维数组
        if (count($data) !== count($data, COUNT_RECURSIVE)) {
            array_walk($data, function (&$item) use ($handlerClass) {
                self::handle($handlerClass, $item);
            });
        }else{
            self::handle($handlerClass, $data);
        }
    }

    private static function handle($handlerClass,array &$item)
    {
        foreach ($item as $key => &$value) {

            if (isset($handlerClass->handlerMap[$key])) {
                if (is_string($func = $handlerClass->handlerMap[$key])) {
                    $value = $handlerClass->{$func}($value, $item);
                }
            }
        }
    }
}