Work.php 19.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
<?php
declare(strict_types=1);

namespace app\controller\api;

use app\BaseController;
use app\service\AuthContext;
use think\facade\Db;

class Work extends BaseController
{
    /** 与库中 status 比对(兼容首尾空格、大小写差异) */
    protected function workRowIsApproved(array $row): bool
    {
        return strtolower(trim((string) ($row['status'] ?? ''))) === 'approved';
    }

    /** 公开列表(仅已通过) */
    public function list()
    {
        $keyword    = trim((string) $this->request->get('keyword', ''));
        $dateRange  = trim((string) $this->request->get('date_range', 'all'));
        $likesSort  = trim((string) $this->request->get('likes_sort', 'all'));
        $categories = trim((string) $this->request->get('categories', ''));
        $catArr     = array_values(array_filter(array_map('trim', explode(',', $categories))));

        $q = Db::name('work')->alias('w')
            ->leftJoin('mp_user u', 'u.id = w.user_id')
            ->whereRaw('LOWER(TRIM(COALESCE(w.status, \'\'))) = ?', ['approved'])
            ->field('w.*,u.nickname as author_name');

        if ($keyword !== '') {
            $q->whereLike('w.title|w.description', '%' . addcslashes($keyword, '%_\\') . '%');
        }

        if ($dateRange !== '' && $dateRange !== 'all') {
            $today = date('Y-m-d');
            $weekStartTs = strtotime('monday this week');
            if ($weekStartTs === false) {
                $weekStartTs = strtotime($today) ?: time();
            }
            $weekStart = date('Y-m-d', $weekStartTs);
            $monthStart = date('Y-m-01');
            $yearStart = date('Y-01-01');
            // 与前端卡片的 date 字段保持一致:优先 publish_date,缺失时回落 create_time 的日期部分
            $dateExpr = "DATE(COALESCE(NULLIF(TRIM(w.publish_date), ''), w.create_time))";
            switch ($dateRange) {
                case 'today':
                    $q->whereRaw($dateExpr . ' >= ?', [$today]);
                    break;
                case 'week':
                    $q->whereRaw($dateExpr . ' >= ?', [$weekStart]);
                    break;
                case 'month':
                    $q->whereRaw($dateExpr . ' >= ?', [$monthStart]);
                    break;
                case 'year':
                    $q->whereRaw($dateExpr . ' >= ?', [$yearStart]);
                    break;
            }
        }

        if ($catArr !== []) {
            $workIds = Db::name('work_category')->whereIn('category', $catArr)->group('work_id')->column('work_id');
            if ($workIds === []) {
                return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => []]]);
            }
            $q->whereIn('w.id', $workIds);
        }

        // 赞数相同时:发布时间/创建时间越晚越靠前(再按 id 降序兜底)
        if ($likesSort === 'desc') {
            $q->order('w.likes_count', 'desc')
                ->order('w.create_time', 'desc')
                ->order('w.id', 'desc');
        } elseif ($likesSort === 'asc') {
            $q->order('w.likes_count', 'asc')
                ->order('w.create_time', 'desc')
                ->order('w.id', 'desc');
        } else {
            // 瀑布流默认:仅按创建时间倒序(如 4月1日 在前、3月31日 在后)
            $q->order('w.create_time', 'desc')->order('w.id', 'desc');
        }

        $rows = $q->select()->toArray();
        $mp   = $this->optionalMpUser();
        $list = $this->toCardList($rows, $mp ? (int) $mp['id'] : 0);

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $list]]);
    }

    /** 星空榜:仅按赞数,不受 likes_sort 参数影响 */
    public function rank()
    {
        $rows = Db::name('work')->alias('w')
            ->leftJoin('mp_user u', 'u.id = w.user_id')
            ->whereRaw('LOWER(TRIM(COALESCE(w.status, \'\'))) = ?', ['approved'])
            ->field('w.*,u.nickname as author_name')
            ->order('w.likes_count', 'desc')
            ->order('w.create_time', 'desc')
            ->order('w.id', 'desc')
            ->select()
            ->toArray();

        $mp   = $this->optionalMpUser();
        $list = $this->toCardList($rows, $mp ? (int) $mp['id'] : 0);

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $list]]);
    }

    public function detail(int $id)
    {
        $mp = $this->optionalMpUser();
        $w  = Db::name('work')->alias('w')
            ->leftJoin('mp_user u', 'u.id = w.user_id')
            ->where('w.id', $id)
            ->field('w.*,u.nickname as author_name')
            ->find();

        if (!$w) {
            return json(['code' => 404, 'msg' => '作品不存在', 'data' => []]);
        }

        $mpId = $mp ? (int) $mp['id'] : 0;
        // 已通过:任何人可看(与首页列表一致);未通过仅作者本人可看
        if (!$this->workRowIsApproved($w) && (int) $w['user_id'] !== $mpId) {
            $st = strtolower(trim((string) ($w['status'] ?? '')));
            $msg = match ($st) {
                'pending'  => '作品审核中,请使用提交该作品的账号登录后再查看详情',
                'rejected' => '作品未通过审核,请使用提交该作品的账号登录后查看',
                default    => '作品不可见',
            };

            return json(['code' => 403, 'msg' => $msg, 'data' => []]);
        }

        $imgRows = Db::name('work_image')
            ->where('work_id', $id)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->column('url');
        $cats = Db::name('work_category')->where('work_id', $id)->column('category');

        $liked = false;
        if ($mpId > 0) {
            $liked = Db::name('work_like')->where('work_id', $id)->where('user_id', $mpId)->count() > 0;
        }

        $pub   = $w['publish_date'] ?: date('Y-m-d', strtotime((string) $w['create_time']));
        $cover = trim((string) ($w['cover_image'] ?? ''));
        /** 与首页封面一致:封面图放在第一位,再按排序接其余图并去重 */
        $urls = [];
        foreach ($imgRows as $u) {
            $u = trim((string) $u);
            if ($u !== '') {
                $urls[] = $u;
            }
        }
        if ($cover !== '') {
            $urls = array_values(array_unique(array_merge([$cover], $urls)));
        }

        $stNorm = strtolower(trim((string) ($w['status'] ?? '')));
        $data = [
            'id'           => (int) $w['id'],
            'userId'       => (int) $w['user_id'],
            'imageUrl'     => $cover,
            'images'       => $urls !== [] ? $urls : ($cover !== '' ? [$cover] : []),
            'title'        => (string) ($w['title'] ?? ''),
            'description'  => (string) ($w['description'] ?? ''),
            'likes'        => (int) $w['likes_count'],
            'author'       => $w['author_name'] ? (string) $w['author_name'] : '用户',
            'date'         => $pub,
            'shootDate'    => $w['shoot_date'] ? (string) $w['shoot_date'] : '',
            'categories'   => $cats,
            'liked'        => $liked,
            'status'       => (string) ($w['status'] ?? ''),
        ];
        if ($stNorm === 'rejected' && $mpId > 0 && (int) $w['user_id'] === $mpId) {
            $data['rejectReason'] = trim((string) ($w['reject_reason'] ?? ''));
        }

        return json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }

    public function create()
    {
        $user = AuthContext::mpUser();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未授权', 'data' => []]);
        }

        $title       = trim((string) $this->request->post('title', ''));
        $description = trim((string) $this->request->post('description', ''));
        $shootDate   = trim((string) $this->request->post('shoot_date', ''));
        $categories  = $this->request->post('categories', []);
        $imageUrls   = $this->request->post('image_urls', []);

        if (!is_array($categories)) {
            $categories = [];
        }
        if (!is_array($imageUrls)) {
            $imageUrls = [];
        }

        if ((int) ($user['status'] ?? 1) !== 1) {
            return json(['code' => 403, 'msg' => '账号已被禁用', 'data' => []]);
        }

        if (mb_strlen($title) < 1 || mb_strlen($title) > 10) {
            return json(['code' => 400, 'msg' => '标题限 1~10 字', 'data' => []]);
        }
        if (mb_strlen($description) < 1 || mb_strlen($description) > 100) {
            return json(['code' => 400, 'msg' => '描述限 1~100 字', 'data' => []]);
        }
        if ($categories === []) {
            return json(['code' => 400, 'msg' => '请选择作品类别', 'data' => []]);
        }
        $allowedCat = ['landscape', 'humanity', 'ecology', 'other'];
        foreach ($categories as $c) {
            if (!is_string($c) || !in_array($c, $allowedCat, true)) {
                return json(['code' => 400, 'msg' => '作品类别须为:风景、人文、生态、其他', 'data' => []]);
            }
        }
        if (count($imageUrls) < 1 || count($imageUrls) > 3) {
            return json(['code' => 400, 'msg' => '请上传 1~3 张图片', 'data' => []]);
        }

        $now = date('Y-m-d H:i:s');
        $sd  = null;
        if ($shootDate !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $shootDate)) {
            $sd = $shootDate;
        }

        $cover = (string) $imageUrls[0];

        $wid = Db::name('work')->insertGetId([
            'user_id'         => (int) $user['id'],
            'title'           => $title,
            'description'     => $description,
            'location'        => '',
            'shoot_date'      => $sd,
            'status'          => 'pending',
            'sort_order'      => 9999,
            'recommended'     => 0,
            'views'           => 0,
            'likes_count'     => 0,
            'comments_count'  => 0,
            'cover_image'     => $cover,
            'camera'          => '',
            'lens'            => '',
            'exif_settings'   => '',
            'publish_date'    => null,
            'create_time'     => $now,
            'update_time'     => $now,
        ]);

        foreach ($categories as $c) {
            if (!is_string($c) || $c === '') {
                continue;
            }
            Db::name('work_category')->insert([
                'work_id'  => $wid,
                'category' => $c,
            ]);
        }

        foreach ($imageUrls as $i => $url) {
            if (!is_string($url) || $url === '') {
                continue;
            }
            Db::name('work_image')->insert([
                'work_id' => $wid,
                'url'     => $url,
                'sort'    => (int) $i,
            ]);
        }

        return json(['code' => 0, 'msg' => '提交成功,请等待审核', 'data' => ['id' => $wid]]);
    }

    /** 已拒绝作品修改后重新提交,进入待审核 */
    public function resubmit(int $id)
    {
        $user = AuthContext::mpUser();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未授权', 'data' => []]);
        }

        $w = Db::name('work')->where('id', $id)->find();
        if (!$w || (int) $w['user_id'] !== (int) $user['id']) {
            return json(['code' => 404, 'msg' => '作品不存在', 'data' => []]);
        }
        if (strtolower(trim((string) ($w['status'] ?? ''))) !== 'rejected') {
            return json(['code' => 400, 'msg' => '仅已拒绝的作品可修改后重新提交', 'data' => []]);
        }

        $title       = trim((string) $this->request->post('title', ''));
        $description = trim((string) $this->request->post('description', ''));
        $shootDate   = trim((string) $this->request->post('shoot_date', ''));
        $categories  = $this->request->post('categories', []);
        $imageUrls   = $this->request->post('image_urls', []);

        if (!is_array($categories)) {
            $categories = [];
        }
        if (!is_array($imageUrls)) {
            $imageUrls = [];
        }

        if ((int) ($user['status'] ?? 1) !== 1) {
            return json(['code' => 403, 'msg' => '账号已被禁用', 'data' => []]);
        }

        if (mb_strlen($title) < 1 || mb_strlen($title) > 10) {
            return json(['code' => 400, 'msg' => '标题限 1~10 字', 'data' => []]);
        }
        if (mb_strlen($description) < 1 || mb_strlen($description) > 100) {
            return json(['code' => 400, 'msg' => '描述限 1~100 字', 'data' => []]);
        }
        if ($categories === []) {
            return json(['code' => 400, 'msg' => '请选择作品类别', 'data' => []]);
        }
        $allowedCat = ['landscape', 'humanity', 'ecology', 'other'];
        foreach ($categories as $c) {
            if (!is_string($c) || !in_array($c, $allowedCat, true)) {
                return json(['code' => 400, 'msg' => '作品类别须为:风景、人文、生态、其他', 'data' => []]);
            }
        }
        if (count($imageUrls) < 1 || count($imageUrls) > 3) {
            return json(['code' => 400, 'msg' => '请上传 1~3 张图片', 'data' => []]);
        }

        $now = date('Y-m-d H:i:s');
        $sd  = null;
        if ($shootDate !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $shootDate)) {
            $sd = $shootDate;
        }

        $cover = (string) $imageUrls[0];

        Db::transaction(function () use ($id, $title, $description, $sd, $cover, $categories, $imageUrls, $now): void {
            Db::name('work_category')->where('work_id', $id)->delete();
            Db::name('work_image')->where('work_id', $id)->delete();

            Db::name('work')->where('id', $id)->update([
                'title'          => $title,
                'description'    => $description,
                'shoot_date'     => $sd,
                'status'         => 'pending',
                'reject_reason'  => '',
                'cover_image'    => $cover,
                'sort_order'     => 9999,
                'publish_date'   => null,
                'update_time'    => $now,
            ]);

            foreach ($categories as $c) {
                if (!is_string($c) || $c === '') {
                    continue;
                }
                Db::name('work_category')->insert([
                    'work_id'  => $id,
                    'category' => $c,
                ]);
            }

            foreach ($imageUrls as $i => $url) {
                if (!is_string($url) || $url === '') {
                    continue;
                }
                Db::name('work_image')->insert([
                    'work_id' => $id,
                    'url'     => $url,
                    'sort'    => (int) $i,
                ]);
            }
        });

        return json(['code' => 0, 'msg' => '已重新提交,请等待审核', 'data' => ['id' => $id]]);
    }

    public function toggleLike(int $id)
    {
        $user = AuthContext::mpUser();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未授权', 'data' => []]);
        }

        $w = Db::name('work')->where('id', $id)->find();
        if (!$w || !$this->workRowIsApproved($w)) {
            return json(['code' => 404, 'msg' => '作品不可点赞', 'data' => []]);
        }

        $uid = (int) $user['id'];
        $ex  = Db::name('work_like')->where('work_id', $id)->where('user_id', $uid)->find();
        if ($ex) {
            Db::name('work_like')->where('id', $ex['id'])->delete();
            Db::name('work')->where('id', $id)->dec('likes_count')->update();
            $likes = max(0, (int) $w['likes_count'] - 1);
            return json(['code' => 0, 'msg' => 'ok', 'data' => ['liked' => false, 'likes' => $likes]]);
        }

        Db::name('work_like')->insert([
            'work_id'     => $id,
            'user_id'     => $uid,
            'create_time' => date('Y-m-d H:i:s'),
        ]);
        Db::name('work')->where('id', $id)->inc('likes_count')->update();
        $likes = (int) $w['likes_count'] + 1;

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['liked' => true, 'likes' => $likes]]);
    }

    protected function toCard(array $w): array
    {
        $dt = trim((string) ($w['publish_date'] ?? ''));
        if ($dt === '') {
            $dt = date('Y-m-d', strtotime((string) ($w['create_time'] ?? 'now')));
        }
        return [
            'id'          => (int) $w['id'],
            'userId'      => (int) $w['user_id'],
            'imageUrl'    => (string) ($w['cover_image'] ?? ''),
            'title'       => (string) ($w['title'] ?? ''),
            'description' => (string) ($w['description'] ?? ''),
            'likes'       => (int) $w['likes_count'],
            'author'      => $w['author_name'] ? (string) ($w['author_name']) : '用户',
            'date'        => $dt,
        ];
    }

    /**
     * @param array<int, array<string, mixed>> $rows
     * @param int                                $mpUserId 当前请求带有效 Bearer 时传入,用于标记 liked
     */
    protected function toCardList(array $rows, int $mpUserId = 0): array
    {
        if ($rows === []) {
            return [];
        }
        $ids = array_map(fn ($r) => (int) ($r['id'] ?? 0), $rows);
        $catMap = $this->categoriesByWorkIds($ids);

        $likedSet = [];
        if ($mpUserId > 0) {
            $idList = array_values(array_unique(array_filter($ids, static fn (int $id) => $id > 0)));
            if ($idList !== []) {
                $likedRows = Db::name('work_like')
                    ->where('user_id', $mpUserId)
                    ->whereIn('work_id', $idList)
                    ->column('work_id');
                foreach ($likedRows as $wid) {
                    $likedSet[(int) $wid] = true;
                }
            }
        }

        return array_map(function (array $r) use ($catMap, $likedSet) {
            $card = $this->toCard($r);
            $wid  = (int) ($r['id'] ?? 0);
            $card['categories'] = $catMap[$wid] ?? [];
            $card['liked']      = isset($likedSet[$wid]);

            return $card;
        }, $rows);
    }

    /** @param array<int, int> $workIds */
    protected function categoriesByWorkIds(array $workIds): array
    {
        $workIds = array_values(array_unique(array_filter($workIds)));
        if ($workIds === []) {
            return [];
        }
        // 表无自增 id,复合主键 (work_id, category)
        $rows = Db::name('work_category')
            ->whereIn('work_id', $workIds)
            ->order('work_id', 'asc')
            ->order('category', 'asc')
            ->select()
            ->toArray();
        $out = [];
        foreach ($rows as $row) {
            $wid = (int) ($row['work_id'] ?? 0);
            $c   = trim((string) ($row['category'] ?? ''));
            if ($wid <= 0 || $c === '') {
                continue;
            }
            if (!isset($out[$wid])) {
                $out[$wid] = [];
            }
            if (!in_array($c, $out[$wid], true)) {
                $out[$wid][] = $c;
            }
        }

        return $out;
    }

    protected function optionalMpUser(): ?array
    {
        $auth = $this->request->header('Authorization', '');
        if (!is_string($auth) || !str_starts_with($auth, 'Bearer ')) {
            return null;
        }
        $token = trim(substr($auth, 7));
        if ($token === '') {
            return null;
        }
        $row = Db::name('mp_user')->where('api_token', $token)->find();

        return $row ?: null;
    }
}