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

namespace app\common\model;


use app\common\service\FileService;
use think\model\concern\SoftDelete;
use app\common\enum\{ TwoGoodsEnum, YesNoEnum};

/**
 * 商品模型
 * Class Goods
 * @package app\common\model
 */
class TwoGoods extends BaseModel
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function user()
    {
        return $this->hasOne(User::class,'id','user_id')->field('id,nickname,avatar,login_ip,login_time,last_online_time');
    }

    public function user2()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    // public function unit()
    // {
    //     return $this->hasOne(TwoGoodsUnit::class, 'id', 'unit_id');
    // }


    /**
     * @notes 去掉视频域名
     * @param $value
     * @return mixed|string
     */
    public function setVideoAttr($value)
    {
        return trim($value) ? FileService::setFileUrl($value) : '';
    }

    /**
     * @notes 获取视频域名
     * @param $value
     * @return mixed|string
     * @author lgp
     * @date 2022/3/28 14:35
     */
    public function getVideoAttr($value)
    {
        return trim($value) ? FileService::getFileUrl($value) : '';
    }

    /**
     * @notes 去掉视频封面域名
     * @param $value
     * @return mixed|string
     */
    public function setVideoCoverAttr($value)
    {
        return trim($value) ? FileService::setFileUrl($value) : '';
    }


    /**
     * @notes 获取视频封面域名
     * @param $value
     * @return string
     * @author lgp
     * @date 2022/3/28 14:38
     */
    public function getVideoCoverAttr($value)
    {
        return trim($value) ? FileService::getFileUrl($value) : '';
    }


    /**
     * @notes 关联轮播图模型
     * @return \think\model\relation\HasMany
     */
    // public function imageList()
    // {
    //     return $this->hasMany(TwoGoodsImage::class, 'goods_id');
    // }

    /**
     * @notes 关联商品分类模型
     * @return \think\model\relation\HasMany
     */
    public function goodsCategoryIndex()
    {
        return $this->hasMany(TwoGoodsCategoryIndex::class, 'goods_id');
    }


    /**
     * @notes 关联规格项模型
     * @return \think\model\relation\HasMany
     */
    public function specValue()
    {
        return $this->hasMany(TwoGoodsSpec::class, 'goods_id');
    }


    /**
     * @notes 关联规格值模型
     * @return \think\model\relation\HasMany
     */
    public function specValueSpec()
    {
        return $this->hasMany(TwoGoodsSpecValue::class, 'goods_id');
    }


    /**
     * @notes 关联规格信息模型
     * @return \think\model\relation\HasMany
     */
    public function specValueList()
    {
        return $this->hasMany(TwoGoodsItem::class, 'goods_id');
    }


    /**
     * @notes 关联评论模型
     * @return \think\model\relation\HasMany
     */
    public function goodsComment()
    {
        return $this->hasMany(TwoGoodsComment::class, 'goods_id');
    }

    /**
     * @notes 处理商品图片
     * @param $value
     * @param $data
     * @return array
     */
    // public function getGoodsImageAttr($value, $data)
    // {
    //     $goodsImage = array_column($this->imageList->toArray(), 'uri');
    //     array_unshift($goodsImage, FileService::getFileUrl($data['image']));
    //     return $goodsImage;
    // }

    /**
     * @notes 处理分类
     * @param $value
     * @param $data
     * @return array
     */
    // public function getCategoryIdAttr($value, $data)
    // {
    //     $goods_category_index = $this->goodsCategoryIndex->toArray();
    //     return array_column($goods_category_index, 'category_id');
    // }


    /**
     * @notes 关键词搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchKeywordAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('id|code|name', 'like', '%' . $value . '%');
        }
    }

    /**
     * @notes 分类搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchCategoryIdAttr($query, $value, $data)
    {
        if ($value) {
            $goodsCategory = TwoGoodsCategory::find($value);
            $level = $goodsCategory['level'] ?? '';
            $categoryIds = [];
            switch ($level) {
                case 1:
                    $categoryIds = TwoGoodsCategory::alias('A')
                        ->join('goods_category B', 'A.id = B.pid')
                        ->where(['A.id' => $value])
                        ->field('A.id as aid,B.id as bid')
                        ->select()->toArray();
                    $categoryIds = array_merge(array_column($categoryIds, 'aid'), array_column($categoryIds, 'bid'));
                    break;
                case 2:
                    $categoryIds = TwoGoodsCategory::where(['pid' => $value])
                        ->column('id');
                    break;
            }
            $categoryIds = array_merge([(int)$value], $categoryIds);
            $goodsIds = TwoGoodsCategoryIndex::where(['category_id' => $categoryIds])->column('goods_id');
            $query->where('id', 'in', $goodsIds);

        }

    }

    /**
     * @notes 品牌搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchBrandIdAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('brand_id', '=', $value);
        }

    }

    /**
     * @notes 商品类型筛选
     * @param $query
     * @param $value
     * @param $data
     * @author lgp
     * @date 2022/4/21 18:05
     */
    public function searchGoodsTypeAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('type', '=', $value);
        }
    }

    /**
     * @notes 供应商搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchSupplierIdAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('supplier_id', '=', $value);
        }

    }

    /**
     * @notes 价格排序
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchPriceAttr($query, $value, $data)
    {
        if ($value) {
            $query->order(['min_price' => $value]);
        }
    }

    /**
     * @notes 销售排序
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchSaleAttr($query, $value, $data)
    {
        if ($value) {
            $query->order(['sales_num' => $value]);
        }
    }

    /**
     * @notes 商品名称搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchNameAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('name', 'like', '%' . $value . '%');
        }
    }

    /**
     * @notes 类型搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchTypeAttr($query, $value, $data)
    {
        switch ($value) {
            case 1:   //销售中 todo 列出「销售状态：销售中」的商品
                $query->where(['status' => TwoGoodsEnum::STATUS_SELL]);
                break;
            case 2:  //库存预警 todo 列出「销售状态：销售中」且「库存预警：开启预警」 且「0 < 总库存 < 库存预警值」
                $query->where([
                    ['status', '=', TwoGoodsEnum::STATUS_SELL],
                    ['stock_warning', '>', 0],
                    ['total_stock', '>', 0],
                ]);
                $query->whereColumn('stock_warning', '>', 'total_stock');
                break;

            case 3:  //已售罄 todo 「销售状态：销售中」且 「总库存 == 0」
                $query->where(['status' => TwoGoodsEnum::STATUS_SELL, 'total_stock' => 0]);
                break;
            case 4:  //仓库中 todo 列出「销售状态：仓库中」的商品
                $query->where(['status' => TwoGoodsEnum::STATUS_STORAGE]);
                break;

        }

    }


    /**
     * @notes 最小值获取器
     * @param $value
     * @return int|mixed|string
     */
    public function getMinPriceAttr($value)
    {
        return clearZero($value);
    }

    /**
     * @notes 最大值获取器
     * @param $value
     * @return int|mixed|string
     */
    public function getMaxPriceAttr($value)
    {
        return clearZero($value);
    }

    /**
     * @notes 价格获取器
     * @param $value
     * @param $data
     * @datetime 2022/1/17 17:14
     */
    public function getPriceTextAttr($value, $data)
    {
        if ($data['spec_type'] == 1) {
            // 单规格
            return '¥ ' . clear_zero($data['min_price']);
        } else {
            // 多规格
            return '¥ ' . clear_zero($data['min_price']) . ' ~ ' . clear_zero($data['max_price']);
        }
    }

    /**
     * @notes 状态获取器
     * @param $value
     * @param $data
     * @return array|mixed|string
     * @datetime 2022/1/17 17:24
     */
    public function getStatusTextAttr($value, $data)
    {
        return TwoGoodsEnum::getStatusDesc($data['status']);
    }

    /**
     * @notes 分类获取器
     * @param $value
     * @param $data
     * @datetime 2022/1/17 17:25
     */
    public function getCategoryTextAttr($value, $data)
    {
        $field = ['gci.goods_id, gci.category_id, gc.name'];
        $lists = TwoGoodsCategoryIndex::alias('gci')
            ->leftJoin('goods_category gc', 'gc.id = gci.category_id')
            ->field($field)
            ->where('gci.goods_id', $data['id'])
            ->select()
            ->toArray();

        $categoryText = '';
        foreach ($lists as $item) {
            $categoryText .= $item['name'] . '/';
        }
        return trim($categoryText, '/');
    }

    /**
     * @notes 评论条数获取器(审核通过的)
     * @param $value
     * @param $data
     * @datetime 2022/1/17 17:32
     */
    public function getCommentTextAttr($value, $data)
    {
        return 0;
    }


    /**
     * @notes 状态筛选
     * @param $query
     * @param $value
     * @param $data
     * @author lgp
     * @date 2022/5/5 15:38
     */
    public function searchStatusAttr($query, $value, $data)
    {
        if ('' !== $value) {
            $query->where('status', '=', $value);
        }

    }
}
