<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\api\service\goods;

use think\facade\Db;
use app\common\exception\BaseException;
use app\common\library\jwt\Token;
use app\common\library\utils\Image;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\GoodsItem as GoodsItemModel;
use app\common\model\goods\GoodsImage as GoodsImageModel;
use app\common\model\goods\Spec as SpecModel;
use app\common\model\goods\SpecValue as SpecValueModel;
use app\common\model\goods\Attribute as AttributeModel;
use app\common\model\promotion\Coupon as CouponModel;
use app\common\model\Users as UsersModel;
use app\common\model\users\UsersCollect as UsersCollectModel;
use app\common\model\users\UsersCoupon as UsersCouponModel;
use app\common\model\users\UsersVisit as UsersVisitModel;
use app\common\service\Users as UsersService;
use app\common\service\promotion\Discount as DiscountService;

/**
 * @package app\api\service\goods
 * @class Goods
 * @author xzncit 2024-03-07
 */
class Goods {

    /**
     * 列表
     * @param array $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[] = ["status","=","0"];
        if(!empty($params["cat_id"]) && is_numeric($params["cat_id"])){
            $catID   = getCategoryChildren(["pid"=>$params["cat_id"]]);
            $catID[] = $params["cat_id"];
            $condition[] = ["cat_id","in",$catID];
        }

        if(empty($params["order"])){
            $order = "desc";
        }else{
            if(in_array($params["order"],["asc","desc"])){
                $order = $params["order"];
            }else{
                $order = "desc";
            }
        }

        if(empty($params["type"]) || $params["type"] == "all"){
            $field = "id";
        }else if($params["type"] == "price"){
            $field = "sell_price";
        }else{
            $field = "sale";
        }

        $page  = $params["page"]??1;
        $count = GoodsModel::where($condition)->count();
        $array["list"] = GoodsModel::where($condition)->page($page,$array["size"])->order($field,$order)->select()->map(function ($res){
            $discount = DiscountService::special($res["sell_price"],$res["id"]);
            $array = [
                "id"            => $res["id"],
                "type"          => $discount["type"],
                "name"          => $res["title"],
                "sell_price"    => $discount["price"],
                "market_price"  => $res["market_price"],
                "sale"          => ($res["sale"] + $res["sale_init"]),
                "unit"          => $res["unit"],
                "image"         => Image::thumb($res["photo"],["prefix"=>"medium"])
            ];

            return $array;
        });

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

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $goods = GoodsModel::where(["id"=>$id,"status"=>0])->find();
        if(empty($goods)){
            throw new BaseException("您要访问的内容不存在",404);
        }

        $goods["sell_price"] = DiscountService::special($goods["sell_price"],$goods["id"])["price"];
        UsersVisitModel::history(0,$id);
        GoodsModel::where(["id"=>$id,"status"=>0])->save([ "visit"=>Db::raw("visit+1") ]);
        $goods["photo"] = Image::thumb($goods["photo"]);
        $goods["image"] = GoodsImageModel::where("goods_id",$id)->select()->map(function ($res){
            return Image::thumb($res["path"]);
        });

        $goods["content"] = Image::replace(Image::removeAttribute($goods["content"]),function($path,$content){
            return str_replace($path, Image::thumb($path), $content);
        });

        $goods["collect"] = UsersService::auth("id",0) > 0 && UsersCollectModel::where([
            ["type","=","1"],
            ["category","=","0"],
            ["user_id","=",UsersService::get("id",0)],
            ["goods_id","=",$id]
        ])->count() ? 1 : 0;

        $goods["attr"] = AttributeModel::where("goods_id",$goods["id"])->select()->map(function ($res){
            return [
                "name"=>$res["name"],
                "value"=>$res["value"]
            ];
        });

        $goods["spec"] = SpecModel::where("goods_id",$goods["id"])->select()->map(function ($value){
            $data = [
                "id"    => $value["id"],
                "name"  => $value["name"],
                "list"  => []
            ];

            $data["list"] = SpecValueModel::where("spec_id",$value["id"])->select()->map(function ($res){
                return [
                    "id"            => $res["id"],
                    "pid"           => $res["spec_id"],
                    "value"         => $res["value"],
                    "thumb_image"   => Image::thumb($res["thumb_image"]),
                    "selected"      => false,
                    "disable"       => false
                ];
            });

            return $data;
        });

        $goods["item"] = GoodsItemModel::where("goods_id",$goods["id"])->select()->map(function ($res){
            return [
                "id"            => $res["id"],
                "sku_id"        => $res["sku_id"],
                "spec_value"    => $res["spec_value"],
                "goods_number"  => $res["goods_number"],
                "store_nums"    => $res["store_nums"],
                "market_price"  => $res["market_price"],
                "sell_price"    => DiscountService::special($res["sell_price"],$res["goods_id"],$res["sku_id"])["price"],
                "thumb_image"   => Image::thumb($res["thumb_image"])
            ];
        });

        return [
            "id"               => $goods["id"],
            "title"            => $goods["title"],
            "sell_price"       => $goods["sell_price"],
            "market_price"     => $goods["market_price"],
            "store_nums"       => $goods["store_nums"],
            "unit"             => $goods["unit"],
            "sale"             => $goods["sale"],
            "visit"            => $goods["visit"],
            "photo"            => $goods["photo"],
            "image"            => $goods["image"],
            "collect"          => $goods["collect"],
            "attr"             => $goods["attr"],
            "spec"             => $goods["spec"],
            "item"             => $goods["item"],
            "content"          => $goods["content"],
            "min_count"        => 1,
            "max_count"        => $goods["store_nums"]
        ];
    }

    /**
     * 收藏
     * @param $id
     * @return int
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function collect($id){
        $goods = GoodsModel::where("id",$id)->find();
        if(empty($goods)){
            throw new BaseException("该商品不存在",0);
        }

        if(!Token::isAuth()){
            throw new BaseException("您还没有登录，请先登录",401);
        }

        $user = UsersModel::where("id",Token::get("id"))->find();
        if(empty($user)){
            throw new BaseException("您还没有登录，请先登录",401);
        }

        $condition   = [];
        $condition[] = ["type","=","1"];
        $condition[] = ["category","=","0"];
        $condition[] = ["user_id","=",$user["id"]];
        $condition[] = ["goods_id","=",$id];
        $collect     = UsersCollectModel::where($condition)->find();
        if(empty($collect)){
            UsersCollectModel::create([
                "type"          => 1,
                "category"      => 0,
                "user_id"       => $user["id"],
                "goods_id"      => $id,
                "create_time"   => time()
            ]);

            return 1;
        }else{
            UsersCollectModel::where($condition)->delete();
            return 2;
        }
    }

    /**
     * 优惠券
     * @return CouponModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function coupon(){
        $list = CouponModel::where(["status"=>1,"push_type"=>1])->order('id','desc')->limit(20)->select()->map(function ($value){
            $status = 1; // 待领取
            $nowTime = time();
            if($value["expire_type"] == 2 && $nowTime > $value["end_time"]){
                $status = 3; // 已过期
            }

            if(Token::isAuth() && UsersCouponModel::where(["coupon_id"=>$value["id"],"user_id"=>Token::get("id")])->find()){
                $status = 2; // 已领取
            }

            if($value["expire_type"] == 2){
                $time = date("Y-m-d",$value["end_time"]);
            }else if($value["expire_type"] == 1){
                $time = $value["expire_day"];
            }

            $amount = $value["reduce_price"];
            if($value["type"] == 2){
                $amount = number_format(($value["discount"] / 100) * 10,1);
            }

            $title = $value["type"] == 2 ? "折扣券" : "满 " . (int)$value["order_amount"] . " 减 " . (int)$value["reduce_price"];
            $result = [
                "id"            => $value["id"],
                "name"          => $value["name"],
                "title"         => $title,
                "type"          => $value["type"],
                "expire_type"   => $value["expire_type"],
                "amount"        => $amount,
                "order_amount"  => $value["order_amount"],
                "status"        => $status,
                "time"          => $time
            ];

            return $result;
        });

        return $list;
    }

    /**
     * 商品推荐
     * @param array $params
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function recommend($params=[]){
        $condition   = [];
        $condition[] = ["status","=","0"];
        $condition[] = ["id","<>",intval($params["id"]??0)];
        return GoodsModel::where($condition)->orderRaw("RAND()")->limit(6)->select()->map(function ($res){
            return [
                "id"            => $res["id"],
                "name"          => $res["title"],
                "sell_price"    => $res["sell_price"],
                "image"         => Image::thumb($res["photo"],["prefix"=>"medium"])
            ];
        });
    }

}