<?php

declare(strict_types=1);

namespace app\model;

use app\index\controller\Common;
use think\facade\Cache;
use think\Model;

/**
 * @mixin \think\Model
 */
class PostComment extends Model
{
  //

  public function post()
  {
    return $this->belongsTo(Post::class, 'post_id');
  }

  public function getUserAttr()
  {
    return Common::getUserInfo($this->getData('user_uid'));
  }

  public function getReadUrlAttr()
  {
    $model_post = $this->getAttr('post');

    $read_url = $model_post->read_url . '#comment-' . $this->getData('id');

    return $read_url;
  }

  public static function getPostCommentsCount($post_id)
  {
    $cache_key = 'post_comment_count_' . $post_id;
    $count = Cache::get($cache_key);

    if (is_null($count)) {
      $count = PostComment::where('post_id', $post_id)->count();

      Cache::tag('comment')->set($cache_key, $count);
    }

    return $count;
  }

  public static function clearCountCache()
  {
    Cache::tag('comment')->clear();
  }
}
