<?php

namespace app\api\service\goods;

use app\common\library\utils\Date;
use app\common\library\utils\Tool;
use app\common\exception\BaseException;
use app\common\library\utils\Image;
use app\api\model\Comments as CommentModel;

/**
 * @package app\api\service\goods
 * @class Comments
 * @author xzncit 2024/3/26
 */
class Comments {

    /**
     * 列表
     * @param $params
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        $condition = [];
        $condition[] = ["comments.status","=",1];
        $condition[] = ["goods_id","=",intval($params["goods_id"]??0)];

        if(isset($params["type"])){
            if($params["type"] == 0){
                $condition[] = ["order_type","in","0,4"];
            }else{
                $condition[] = ["order_type","=",intval($params["type"])];
            }
        }

        $page  = $params["page"]??1;
        $count = CommentModel::withJoin("user")->where($condition)->count();
        $array["list"] = CommentModel::withJoin("user")->where($condition)->page($page,$array["size"])->order("id","DESC")->select()->map(function ($res){
            $image = array_map(function ($v){
                return Image::thumb($v);
            },!empty($res["images"]) ? json_decode($res["images"],true) : []);

            $array = [
                "id"              => $res["id"],
                "avatar"          => Image::avatar($res["user"]["avatar"]),
                "username"        => Tool::repeat(getUserName($res["user_id"]),2,4),
                "image"           => $image??[],
                "spec"            => $res["spec_value"],
                "content"         => $res["content"],
                "reply_content"   => $res["reply_content"],
                "comment_time"    => Date::format($res["comment_time"])
            ];

            return $array;
        });

        $array["total"] = ceil($count / $array["size"]);
        if($array["total"] == $page -1){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        return $array;
    }

}