<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/4 13:50
 * @Description：
 *
 */

namespace Application\Mvc\Controller\Plugins;
use Application\Service\DB\AbstractDb;
use Laminas\Mvc\Controller\Plugin\AbstractPlugin;
use Laminas\View\Model\JsonModel;
use Application\Common\StatusCode;
use Zend\Stdlib\ArrayUtils;

class RenderApiJson extends AbstractPlugin
{
    /**
     * Notes: 成功
     * User: llbjj
     * DateTime: 2022/5/5 8:30
     *
     * @param array $data
     * @return JsonModel
     */
    public function Success(array $data = [], $message = 'OK', array $extendData = [])
    {
        return self::renderView(StatusCode::SUCCESS, $message, $data, $extendData);
    }

    /**
     * Notes: 其他提示
     * User: llbjj
     * DateTime: 2022/5/5 8:30
     *
     * @param array $defaultStatus
     * @param String $msg
     * @return JsonModel
     */
    public function Error(array $defaultStatus, String $msg = '')
    {
        return self::renderView($defaultStatus, $msg);
    }

    /**
     * Notes:
     * User: llbjj
     * DateTime: 2022/5/5 8:30
     *
     * @param array $defaultStatus
     * @param String $msg
     * @param array $data
     * @return JsonModel
     */
    private function renderView(array $defaultStatus, String $msg = '', array $data = [], array $extendData = [])
    {
        $defaultStatus = $defaultStatus ?? StatusCode::SUCCESS;
        $code = $defaultStatus['code'];
        $msg = $msg ?: $defaultStatus['msg'];

        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        if ($dbProfile = AbstractDb::getDbProfile()) {
            $extendData = ArrayUtils::merge($extendData, ['profile' => $dbProfile]);
        }
        if(!empty($extendData)) $result = ArrayUtils::merge($result, $extendData);
        return new JsonModel($result);
    }
}