DownloadAsset.php 2.73 KB
<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use think\facade\Db;
use Throwable;

class DownloadAsset extends BaseController
{
    private const TYPES = ['certificate', 'guide'];

    public function get()
    {
        $map = [];
        try {
            $rows = Db::name('download_asset')->select()->toArray();
            foreach ($rows as $r) {
                $type = strtolower(trim((string) ($r['type'] ?? '')));
                if (!in_array($type, self::TYPES, true)) {
                    continue;
                }
                $map[$type] = [
                    'imageUrl'    => trim((string) ($r['image_url'] ?? '')),
                    'updatedAt'   => (string) ($r['update_time'] ?? ''),
                ];
            }
        } catch (Throwable) {
            // 若未执行补丁 SQL,界面回落到默认图并提示先执行数据库补丁。
        }

        return json([
            'code' => 0,
            'msg'  => 'ok',
            'data' => [
                'certificate' => $map['certificate']['imageUrl'] ?? '/static/certificate-dialog-bg.png',
                'guide'       => $map['guide']['imageUrl'] ?? '/static/daocheng-yading-map.png',
                'updatedAt'   => [
                    'certificate' => $map['certificate']['updatedAt'] ?? '',
                    'guide'       => $map['guide']['updatedAt'] ?? '',
                ],
            ],
        ]);
    }

    public function save()
    {
        $type = strtolower(trim((string) $this->request->post('type', '')));
        $imageUrl = trim((string) $this->request->post('image_url', ''));
        if (!in_array($type, self::TYPES, true)) {
            return json(['code' => 400, 'msg' => '素材类型错误', 'data' => []]);
        }
        if ($imageUrl === '') {
            return json(['code' => 400, 'msg' => '图片地址不能为空', 'data' => []]);
        }

        $now = date('Y-m-d H:i:s');
        try {
            $row = Db::name('download_asset')->where('type', $type)->find();
            if ($row) {
                Db::name('download_asset')->where('id', (int) $row['id'])->update([
                    'image_url'   => $imageUrl,
                    'update_time' => $now,
                ]);
            } else {
                Db::name('download_asset')->insert([
                    'type'        => $type,
                    'image_url'   => $imageUrl,
                    'create_time' => $now,
                    'update_time' => $now,
                ]);
            }
        } catch (Throwable) {
            return json(['code' => 500, 'msg' => '请先执行 patch_download_asset.sql', 'data' => []]);
        }

        return json(['code' => 0, 'msg' => '已保存', 'data' => []]);
    }
}