<?php

namespace app\controller\api;

use app\exception\RepositoryException;
use app\model\Comment as CommentModel;
use app\repository\AccountRepository;
use app\repository\CommentRepository;
use app\validate\Comment as VComment;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Config;

/**
 * 评论相关
 *
 * Class Comment
 * @package app\controller\api
 */
class Comment extends Base
{
    protected $noNeedLogin = [
        'commentList',
    ];

    /**
     * 群聊列表
     * */
    public function myCommentZone()
    {
        $page = $this->request->param('page/d', 1);
        //$size = $this->request->param('size/d', 30);
        Config::load("extra/wechat","wechat");
        $systemSize = config("wechat.commentNum") ?? 30;
        $data = CommentRepository::getInstance()->myCommentZone( $page, $systemSize);
        return $this->json(0, "success", $data);
    }

    /**
     * 创建一条文字评论 开发中
     * */
    public function commentText()
    {
        $accountId = $this->request->user['user_id'] ?? 0;
        $accountRepo = AccountRepository::getInstance();

        try {

            $account = $accountRepo->findById($accountId, [], function ($q) {
                return $q->with(['business', 'parent']);
            });

            if (empty($account)) {
                throw new RepositoryException('用户无效！');
            }


            $param = [
                "comment"            => input("comment/s", ""),//评论内容   图片类型放入地址  语音类型放置语音文件地址
                "user_code"          => $account['user_code'],
                "create_time"        => date("Y-m-d H:i:s"),
                //"url"                => input("url/s", ""),//图片地址   仅图片评论才有
                "state"              => CommentModel::state_default,
                "type"               => input("type/d",0),//评论类型
                "lng"                => input("lng/s"),//经度
                "lat"                => input("lat/s"),//纬度
                "location"           => input("location/s"),
            ];

            //如果是图片或者语音  加上域名信息
            if(in_array($param['type'],[CommentModel::type_img,CommentModel::type_voice])){
                $comment            = $param['comment'];
                $param['url']       = $this->request->domain() . $comment;
                $param['comment']   = $this->request->domain() . $comment;

            }

            //检测评论规则
            validate(VComment::class)->check($param);

            CommentModel::create($param);
            return $this->json(0,"评论成功,等待审核");
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            echo $e->getMessage();
            return $this->json(5001, '服务器繁忙！获取用户个人信息失败');
        }
    }

}