<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\common\model;

/**
 * 购物车模型
 * Class Cart
 * @package app\common\model
 */
class Cart extends BaseModel
{

    /**
     * @notes 关联商品模型
     * @return \think\model\relation\HasOne
     */
    public function goods()
    {
        return $this->hasOne(Goods::class, 'id', 'goods_id')->hidden(['content'])->removeOption('soft_delete');
    }


    /**
     * @notes 关联商品规格模型
     * @return \think\model\relation\HasOne
     */
    public function goodsItem()
    {
        return $this->hasOne(GoodsItem::class, 'id', 'item_id');
    }


    /**
     * @notes 获取购物车列表
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCartLists($userId)
    {
        return $this->withoutField(['create_time', 'update_time'])
            ->with([
                'goods' => function ($query) {
                    $query->field(['id', 'name', 'image', 'status', 'delete_time']);
                },
                'goods_item' => function ($query) {
                    $query->field(['id', 'spec_value_str', 'sell_price', 'image']);
                }
            ])
            ->where(['user_id' => $userId])
            ->order(['id' => 'desc'])
            ->select()->toArray();
    }


    /**
     * @notes 通过规格id获取购物车信息
     * @param $itemId
     * @param $userId
     * @return array|\think\Model
     */
    public function getCartByItem($itemId, $userId)
    {
        return $this->with(['goods', 'goods_item'])
            ->where(['user_id' => $userId, 'item_id' => $itemId])
            ->findOrEmpty();
    }


    /**
     * @notes 通过购物车id获取信息
     * @param $id
     * @param $userId
     * @return array|\think\Model
     */
    public function getCartById($id, $userId)
    {
        return $this->with(['goods', 'goods_item'])
            ->where(['user_id' => $userId, 'id' => $id])
            ->findOrEmpty();
    }


}