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

namespace app\api\service;

use app\common\library\utils\Image;
use think\facade\Db;
use app\common\library\jwt\Token;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\GoodsItem as GoodsItemModel;
use app\common\model\goods\Spec as SpecModel;
use app\common\model\goods\SpecValue as SpecValueModel;
use app\api\model\users\UsersCart as UsersCartModel;
use app\common\service\Users as UsersService;
use app\common\exception\BaseException;

/**
 * @package app\api\service
 * @class Cart
 * @author xzncit 2024-03-12
 */
class Cart {

    public static function getList($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        if(!Token::isAuth()){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        $condition   = [];
        $condition[] = ["user_id","=",Token::get("id")];
        $page  = $params["page"]??1;
        $count = UsersCartModel::withJoin("goods","LEFT")->where($condition)->count();
        $array["list"] = UsersCartModel::withJoin("goods","LEFT")->where($condition)->page($page,$array["size"])->order('id','desc')->select()->map(function ($value){
            $goods     = $value["goods"];
            $disabled  = false;
            $number    = $goods["store_nums"];
            if(!empty($value["sku_id"])){
                $goodsItem = GoodsItemModel::where(["goods_id"=>$value["goods_id"],"sku_id"=>$value["sku_id"]])->find();
                if(!empty($goodsItem)){
                    $array = explode(",",$goodsItem["spec_value"]);
                    $spec  = [];
                    foreach($array as $k=>$item){
                        $val       = explode(":",$item);
                        $name      = SpecModel::where(["id"=>$val[0]])->value("name","");
                        $specValue = SpecValueModel::where(["spec_id"=>$val[0],"id"=>$val[1]])->value("value","");
                        $spec[]    = $name . ":" . $specValue;
                    }

                    $number        = $goodsItem["store_nums"];
                    $value["spec"] = implode(",",$spec);
                }else{
                    $number   = 0;
                    $disabled = true;
                }
            }

            if($number <= 0){
                $disabled = true;
            }

            return [
                "id"        => $value["id"],
                "title"     => $goods["title"],
                "photo"     => Image::thumb($goods["photo"],["prefix"=>"medium"]),
                "price"     => empty($goodsItem) ? $goods["sell_price"] : $goodsItem["sell_price"],
                "spec"      => $value["spec"]??"",
                "disabled"  => $disabled,
                "checked"   => false,
                "num"       => $value["goods_num"],
                "min"       => 1,
                "max"       => $number
            ];
        });

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

        return $array;
    }

    /**
     * 添加
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function add($params=[]){
        $params["id"]     = intval($params["id"]??0);
        $params["sku_id"] = intval($params["sku_id"]??0);
        $params["num"]    = intval($params["num"]??0);
        $condition   = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $condition[] = ["goods_id","=",$params["id"]];
        $condition[] = ["sku_id","=",$params["sku_id"]];
        $cart = UsersCartModel::where($condition)->find();
        if(empty($cart)){
            UsersCartModel::create([
                "user_id"       => UsersService::get("id"),
                "goods_id"      => $params["id"],
                "sku_id"        => $params["sku_id"],
                "goods_num"     => $params["num"],
                "create_time"   => time()
            ]);
        }else{
            UsersCartModel::where($condition)->save([
                "goods_num" => Db::raw("goods_num+".$params["num"])
            ]);
        }

        return true;
    }

    public static function update($params=[]){
        $params["num"] = intval($params["num"]??1);
        if($params["num"] <= 0){
            $params["num"] = 1;
        }

        $condition = [];
        $condition[] = ["id","=",$params["id"]??0];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $cart = UsersCartModel::where($condition)->find();
        if(empty($cart)){
            throw new \Exception("您要修改的内容不存在",0);
        }

        $goods = GoodsModel::where("id",$cart["goods_id"])->find();
        if(empty($goods)){
            throw new \Exception("您要查找的商品不存在",0);
        }

        if(!empty($cart["sku_id"])){
            $goodsItem = GoodsItemModel::where(["goods_id"=>$goods["id"],"sku_id"=>$cart["sku_id"]])->find();
            if(empty($goodsItem)){
                throw new \Exception("您要查找的商品不存在",0);
            }

            if($params["num"] > $goodsItem["store_nums"]){
                $params["num"] = $goodsItem["store_nums"];
            }
        }else{
            if($params["num"] > $goods["store_nums"]){
                $params["num"] = $goods["store_nums"];
            }
        }

        UsersCartModel::where($condition)->update([
            "goods_num"     => $params["num"],
            "update_time"   => time()
        ]);

        return $params["num"];
    }

    /**
     * 获取购物车商品数量
     * @return float|int
     * @throws \app\common\exception\BaseException
     */
    public static function count(){
        if(Token::isAuth()){
            return UsersCartModel::where("user_id",Token::get("id"))->sum("goods_num");
        }

        return 0;
    }

    /**
     * 商品总数
     * @return int
     * @throws \think\db\exception\DbException
     */
    public static function total(){
        if(!Token::isAuth()){
            return 0;
        }

        $condition   = [];
        $condition[] = ["goods.id","<>",""];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        return UsersCartModel::withJoin("goods","LEFT")->where($condition)->count();
    }

    /**
     * 删除
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public static function delete($params){
        $id = is_array($params["id"]) ? $params["id"] : [$params["id"]];
        if(empty($id)){
            throw new \Exception("请选择需要删除的商品",0);
        }

        $condition = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $condition[] = ["id","in",implode(",",$id)];
        UsersCartModel::where($condition)->delete();
        return true;
    }

}