<?php

namespace app\api\service\order;

use app\api\model\order\Order as OrderModel;
use app\common\exception\BaseException;
use app\common\library\file\File;
use app\common\library\file\FileManager;
use app\common\library\utils\Image;
use app\common\model\Attachment as AttachmentModel;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\Spec as SpecModel;
use app\common\model\order\OrderGoods as OrderGoodsModel;
use app\common\model\UsersComment as UsersCommentModel;
use app\common\service\Users as UsersService;
use think\facade\Config;

/**
 * @package app\api\service\order
 * @class Comment
 * @author xzncit 2024/3/20
 */
class Comment {

    public static function getList($id){
        $order = OrderModel::where(["id"=>$id,"user_id"=>UsersService::get("id",0)])->findOrEmpty()->toArray();
        if(empty($order)){
            throw new BaseException("您要操作的订单不存在",0);
        }

        if($order["status"] != 6 && $order["collect_status"] != 2){
            throw new BaseException("该订单不允许执行此操作",0);
        }

        $array = [];
        $array["goods"] = OrderGoodsModel::where("order_id",$order["id"])->select()->map(function ($res){
            $array = json_decode($res["goods_array"],true);
            $spec  = SpecModel::getSpecInfo($array["value"]??"");
            $photo = GoodsModel::where("id",$res["goods_id"])->value("photo","");
            return [
                "id"                => $res["id"],
                "goods_name"        => $res["goods_name"],
                "photo"             => Image::thumb($photo),
                "spec"              => $spec,
                "sell_price"        => $res["sell_price"],
                "total_price"       => $res["total_price"],
                "goods_total_nums"  => $res["goods_total_nums"],
                "is_comment"        => UsersCommentModel::where(["order_id"=>$res["order_id"],"order_goods_id"=>$res["id"]])->count() ? 1 : 0
            ];
        });

        return $array;
    }

    public static function detail($id){
        $orderGoods = OrderGoodsModel::where("id",$id)->findOrEmpty()->toArray();
        if(empty($orderGoods)){
            throw new BaseException("评价内容不存在",0);
        }

        $order = OrderModel::where(["id"=>$orderGoods["order_id"],"user_id"=>UsersService::get("id",0)])->find();
        if(empty($order)){
            throw new BaseException("订单不存在",0);
        }

        if($order["status"] != 6 && $order["collect_status"] != 2){
            throw new BaseException("该订单不允许执行此操作");
        }

        $array = json_decode($orderGoods["goods_array"],true);
        $spec  = SpecModel::getSpecInfo($array["value"]??"");
        $photo = GoodsModel::where("id",$orderGoods["goods_id"])->value("photo","");
        $result["goods"] = [
            "id"                => $orderGoods["id"],
            "goods_name"        => $orderGoods["goods_name"],
            "photo"             => Image::thumb($photo),
            "spec"              => $spec,
            "sell_price"        => $orderGoods["sell_price"],
            "total_price"       => $orderGoods["total_price"],
            "goods_total_nums"  => $orderGoods["goods_total_nums"],
            "is_comment"        => UsersCommentModel::where(["order_id"=>$orderGoods["order_id"],"order_goods_id"=>$orderGoods["id"]])->count() ? 1 : 0
        ];

        $result["order_id"] = $order["id"];
        return $result;
    }

    public static function save($params){
        if(empty($params["message"])){
            throw new BaseException("请填写评论内容",0);
        }

        if(empty($params["point"])){
            throw new BaseException("请填写评分",0);
        }

        $id              = intval($params["id"]??0);
        $params["point"] = $params["point"] > 5 ? 5 : 1;
        $photo           = array_map(function ($value){
            return Image::parseUrl($value);
        },$params["photo"]??[]);

        $orderGoods = OrderGoodsModel::where("id",$id)->findOrEmpty()->toArray();
        if(empty($orderGoods)){
            throw new BaseException("评价内容不存在",0);
        }

        $order = OrderModel::where(["id"=>$orderGoods["order_id"],"user_id"=>UsersService::get("id",0)])->find();
        if(empty($order)){
            throw new BaseException("订单不存在",0);
        }

        $comment = UsersCommentModel::where([
            "user_id"           => UsersService::get("id",0),
            "order_id"          => $orderGoods["order_id"],
            "order_goods_id"    => $orderGoods["id"],
            "goods_id"          => $orderGoods["goods_id"],
        ])->findOrEmpty()->toArray();

        $images = !empty($comment["images"]) ? json_decode($comment["images"],true) : [];

        if(!empty($images)){
            $array = array_diff($images,$photo);
            foreach($array as $value){
                $path       = trim($value,"/");
                $thumbImage = Config::get("website.thumb_image",[]);
                $arr        = explode("/",$path);
                $lastImage  = end($arr);
                file_exists($path) && unlink($path);
                foreach($thumbImage as $key=>$val){
                    $thumb = str_replace($lastImage, $key . '_' . $lastImage, $path);
                    file_exists($thumb) && unlink($thumb);
                }
            }

            if(!empty($array)){
                $newImage = [];
                foreach ($images as $v){
                    if(!in_array($v,$array)){
                        $newImage[] = $v;
                    }
                }

                $images = $newImage;
            }
        }

        $spec = !empty($orderGoods["goods_array"]) ? json_decode($orderGoods["goods_array"],true) : [];
        $data = [
            "user_id"           => UsersService::get("id",0),
            "order_id"          => $orderGoods["order_id"],
            "order_goods_id"    => $orderGoods["id"],
            "order_type"        => $order["type"],
            "goods_id"          => $orderGoods["goods_id"],
            "spec_value"        => $spec["name"]??"",
            "status"            => 1,
            "images"            => (!empty($images) ? json_encode($images) : []),
            "content"           => $params["message"],
            "point"             => $params["point"],
            "describes"         => $params["point"],
            "service"           => $params["point"],
            "logistics"         => $params["point"],
            "comment_time"      => time()
        ];

        if(!empty($comment)){
            UsersCommentModel::where("id",$comment["id"])->save($data);
        }else{
            UsersCommentModel::create($data);
        }

        $commentCount = UsersCommentModel::where("order_id",$order["id"])->count();
        $goodsCount   = OrderGoodsModel::where("order_id",$order["id"])->count();
        OrderModel::where("id",$order["id"])->save([ "evaluate_status"=> ($commentCount == $goodsCount ? 2 : 3) ]);
        return true;
    }

    public static function upload($id){
        $orderGoods = OrderGoodsModel::where("id",$id)->findOrEmpty()->toArray();
        if(empty($orderGoods)){
            throw new BaseException("评价内容不存在",0);
        }

        $order = OrderModel::where(["id"=>$orderGoods["order_id"],"user_id"=>UsersService::get("id",0)])->find();
        if(empty($order)){
            throw new BaseException("订单不存在",0);
        }

        if($order["status"] != 6 && $order["collect_status"] != 2){
            throw new BaseException("该订单不允许执行此操作");
        }

        $comment = UsersCommentModel::where([
            "user_id"           => UsersService::get("id",0),
            "order_id"          => $orderGoods["order_id"],
            "order_goods_id"    => $orderGoods["id"],
            "goods_id"          => $orderGoods["goods_id"],
        ])->findOrEmpty()->toArray();

        if(empty($comment)){
            $comment = [
                "user_id"           => UsersService::get("id",0),
                "order_id"          => $orderGoods["order_id"],
                "order_goods_id"    => $orderGoods["id"],
                "goods_id"          => $orderGoods["goods_id"],
                "status"            => 0,
                "images"            => "",
                "create_time"       => time()
            ];

            $comment["id"] = UsersCommentModel::create($comment)->id;
        }

        if($comment["status"] == 1){
            throw new BaseException("该商品已评论",0);
        }

        $images = !empty($comment["images"]) ? json_decode($comment["images"],true) : [];
        if(count($images) >= 5){
            throw new BaseException("评论图片请控制在5张内",0);
        }

        $upload = FileManager::upload("file",0,true,["save"=>false]);
        $image  = $upload["path"]??"";
        $images[] = $image;
        UsersCommentModel::where("id",$comment["id"])->save([ "images"=>json_encode($images) ]);
        return Image::thumb($image);
    }

}