<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model;

use app\api\model\GoodsSku as GoodsSkuModel;
use app\api\model\GoodsSpecRel as GoodsSpecRelModel;
use app\api\model\store\Module as StoreModuleModel;
use app\api\service\Goods as GoodsService;
use app\api\service\User as UserService;
use app\api\service\user\Grade as UserGradeService;
use app\common\enum\goods\Status as GoodsStatusEnum;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsCategoryRel as GoodsCategoryRelModel;
use app\common\model\GoodsImage as GoodsImageModel;
use app\common\model\UploadFile as UploadFileModel;
use app\store\model\goods\GoodsPrice as GoodsPriceModel;
use cores\exception\BaseException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 商品模型
 * Class Goods
 * @package app\api\model
 */
class Goods extends GoodsModel
{
    /**
     * 隐藏字段
     * @var array
     */
    public $hidden = [
        'images',
        'delivery',
        'deduct_stock_type',
        'sales_initial',
        'sales_actual',
        'sort',
        'is_delete',
        'store_id',
        'create_time',
        'update_time'
    ];

    // 是否启用会员折扣价
    private bool $enableGradeMoney = true;

    /**
     * 商品详情:HTML实体转换回普通字符
     * @param $value
     * @return string
     */
    public function getContentAttr($value): string
    {
        return \htmlspecialchars_decode((string)$value);
    }

    /**
     * 设置是否启用会员折扣价
     * @param bool $value
     * @return $this
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setEnableGradeMoney(bool $value): Goods
    {
        $this->enableGradeMoney = $value && StoreModuleModel::checkModuleKey('user-grade');
        return $this;
    }

    /**
     * 获取是否启用会员折扣价
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getEnableGradeMoney(): bool
    {
        return $this->enableGradeMoney && StoreModuleModel::checkModuleKey('user-grade');
    }

    /**
     * 获取商品列表
     * @param array $param 查询条件
     * @param int $listRows 分页数量
     * @return mixed|\think\model\Collection|\think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = [], int $listRows = 15)
    {

        // 整理查询参数
        $params = array_merge($param, ['status' => GoodsStatusEnum::ON_SALE]);

        // 获取商品列表
        $list = parent::getList($params, $listRows);

        if ($list->isEmpty()) {
            return $list;
        }
        // 隐藏冗余的属性
        $list->hidden(static::getHidden(['content', 'goods_images', 'images']));
        // 整理列表数据并返回
        return $this->setGoodsListDataFromApi($list);
    }

    public function presale()
    {
        $userId = UserService::getCurrentLoginUserId(true);

        $info = PreSaleLog::where([
            'user_id' => $userId,
            'store_id' => request()->header()['storeid'],
            'goods_id' => $_POST['goods_id'],
        ])->find();

        if (!$info) {
            PreSaleLog::insert([
                'user_id' => $userId,
                'store_id' => request()->header()['storeid'],
                'goods_id' => $_POST['goods_id'],
                'ctime' => date('Y-m-d H:i:s')
            ]);
            return true;
        }
        return false;
    }

    /**
     * @notes:浏览记录
     * @return array
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function browseLogList(): array
    {
        $userId = UserService::getCurrentLoginUserId();
        $model = new GoodsBrowseLog;
        $end_time = date('Y-m-d');
        $start_time = date('Y-m-d', strtotime($end_time . ' - 2 days'));
        $list = $model->with(['sku', 'goods', 'images.file'])
            ->where('ctime', '>=', $start_time)
            ->where('ctime', '<=', $end_time)
            ->order('ctime', 'desc')
            ->where(['user_id' => $userId])
            ->select();
        $data = [];
        $array = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        if (!$list->isEmpty()) {
            foreach ($list as $value) {
                $data[$value['ctime']]['name'] = date('m-d', strtotime($value['ctime']));
                $data[$value['ctime']]['week'] = $array[date("w", strtotime($value['ctime']))];
                $data[$value['ctime']]['list'][] = $value;
            }
        }
        return array_values($data);
    }

    public function browseLog()
    {
        $userId = UserService::getCurrentLoginUserId(true);

        $list = GoodsBrowseLog::where([
            'store_id' => request()->header()['storeid'],
            'user_id' => $userId,
        ])->order('id desc')->paginate(15)->column('ctime');
        $list = array_unique($list);
        $res = [];

        foreach ($list as $k => $v) {
            $all = GoodsBrowseLog::alias('a')
                ->join('goods b', 'a.goods_id = b.goods_id')
                ->join('goods_sku c', 'a.goods_id = c.goods_id')
                ->where([
                    'a.store_id' => request()->header()['storeid'],
                    'a.user_id' => $userId,
                    'a.ctime' => $v,
                    'b.is_delete' => 0,
                    'b.status' => 10
                ])->field('a.ctime,a.goods_id,c.goods_props')->order('a.id desc')->select()->toArray();
            foreach ($all as $k2 => &$v2) {
                $v2['goods_props'] = \Qiniu\json_decode($v2['goods_props'], 1)[0] ?? '';
                $v2['image'] = $this->getDetails2($v2['goods_id'])->toArray()['goods_images'][0]->toArray()['preview_url'] ?? '';
            }
            $res[$v] = $all;
        }
        return $res;
    }


    public function browseDel()
    {
        $userId = UserService::getCurrentLoginUserId(true);
        $info = GoodsBrowseLog::where([
            'store_id' => request()->header()['storeid'],
            'user_id' => $userId,
        ])->whereIn('id', $_POST['ids'])->delete();
        return $info;
    }

    public function presaleList()
    {
        $userId = UserService::getCurrentLoginUserId(true);
        $info = PreSaleLog::alias('a')
            ->join('presale b', 'a.pre_id = b.id')
            ->join('goods c', 'c.goods_id = a.goods_id')
            ->where([
                'a.store_id' => request()->header()['storeid'],
                'a.user_id' => $userId,
            ])->field('c.goods_name,c.goods_price_min,a.id,b.p_time')->paginate(15);

        return $info;
    }

    public function presaleGoodsList()
    {
        $info = PreSale::where([
            'store_id' => request()->header()['storeid'],
            'is_change' => 0,
            'status' => 1,
        ])->order('id desc')->find();
        if ($info) {
            $goods = explode(',', $info->goods_list);

            $list = goods::alias('a')
                ->join('goods_category_rel b', 'a.goods_id = b.goods_id')
                ->where([
                    'a.store_id' => request()->header()['storeid'],
                    'a.status' => 10,
                    'b.category_id' => $_GET['category_id']
                ])->whereIn('a.goods_id', $goods)->field('a.goods_id,a.goods_name,a.goods_price_min,b.category_id,a.sales_initial,a.sales_actual')->select()->toArray();
            //暂时 要优化
            foreach ($list as &$v) {
                $file_id = GoodsImageModel::where([
                    'store_id' => request()->header()['storeid'],
                    'goods_id' => $v['goods_id'],
                ])->field('image_id')->find()->image_id;
                $file_path = UploadFileModel::where([
                    'store_id' => request()->header()['storeid'],
                    'file_id' => $file_id,
                ])->field('file_path')->find()->file_path;
                $v['image'] = "https://".$_SERVER['HTTP_HOST'] . '/uploads/' . $file_path;
                $v['end_time'] = strtotime($info->p_time) - time();

            }
            return $list;
        }
        return [];
    }

    public function presaleCateList()
    {
        $info = PreSale::where([
            'store_id' => request()->header()['storeid'],
            'is_change' => 0,
            'status' => 1,
        ])->order('id desc')->find();
        if ($info) {
            $goods = explode(',', $info->goods_list);
            $list = goods::alias('a')
                ->join('goods_category_rel b', 'a.goods_id = b.goods_id')
                ->join('category c', 'c.category_id = b.category_id')
                ->where([
                    'a.store_id' => request()->header()['storeid'],
                    'a.status' => 10,
                    'c.parent_id' => 0,
                ])->whereIn('a.goods_id', $goods)->field('c.*,a.sales_initial,a.sales_actual')->select()->toArray();
            $list = $this->removeDuplicatesByField($list, 'category_id');
            $info['end_time'] = strtotime($info->p_time) - time();
            $res['info'] = $info;
            $res['category'] = $list;
            return $res;
        }
        return [];
    }

    function removeDuplicatesByField($array, $field)
    {
        $uniqueArray = array();
        foreach ($array as $item) {
            if (!isset($uniqueArray[$item[$field]])) {
                $uniqueArray[$item[$field]] = $item;
            }
        }
        return array_values($uniqueArray);
    }

    public function canlpresale()
    {
        $userId = UserService::getCurrentLoginUserId(true);
        $info = PreSaleLog::where([
            'id' => $_POST['id'],
            'user_id' => $userId
        ])->delete();

        return $info;
    }

    /**
     * 获取商品详情 (详细数据用于页面展示)
     * @param int $goodsId 商品ID
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return mixed
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetails(int $goodsId, bool $verifyStatus = true)
    {
        // 关联查询(商品图片、sku列表)
        $with = ['images.file', 'skuList.image', 'video', 'videoCover'];
        // 获取商品记录
        $goodsInfo = $this->getGoodsMain($goodsId, $with, $verifyStatus);
        // 商品规格列表
        $goodsInfo['specList'] = GoodsSpecRelModel::getSpecList($goodsInfo['goods_id']);
        $GoodsCategoryRelModel = new GoodsCategoryRelModel();
        $category = $GoodsCategoryRelModel
            ->alias('a')
            ->join('category b', 'a.category_id = b.category_id')
            ->where([
                'a.goods_id' => $goodsId,
                'a.store_id' => request()->header()['storeid']
            ])->find()->toArray();
        $goodsInfo->category = $category;
        //多规格
        $goodsInfo->specifications = [];
        $skuList = [];
        $specList = [];
        if ($goodsInfo->spu_id > 0) {
            //查同规格的商品
            $spe = GoodsModel::where([
                'spu_id' => $goodsInfo->spu_id,
                'store_id' => request()->header()['storeid'],
                'is_delete' => 0
            ])->column('goods_id');
            foreach ($spe as $k => $v) {
                //$sku1 = $this->getSpecData($v)['skuList']->toArray()[0];
                // $skuList[] = $sku1;
                $spe1 = $this->getSpecData($v)['specList'][0];
                $spe1['valueList'][0]['goods_id'] = $v;
                $aa = 0;
                foreach ($specList as &$v2) {
                    if ($v2['spec_name'] == $spe1['spec_name']) {
                        $aa = 1;
                        $v2['valueList'][] = $spe1['valueList'];
                        break;
                    }
                }

                if ($aa == 0) {
                    $specList[] = $spe1;
                }
            }
        }

        $goodsInfo = $goodsInfo->toArray();

        //替换原规格数组
//        $goodsInfo['skuList2'] = $skuList;
        $goodsInfo['specList2'] = $specList ?? [];

        //加入足迹
        $userId = UserService::getCurrentLoginUserId(false) ?? '';
        if ($userId) {
            $info = GoodsBrowseLog::where([
                'user_id' => $userId,
                'goods_id' => $goodsId,
                'store_id' => request()->header()['storeid'],
                'ctime' => date('Y-m-d')
            ])->find();
            if (!$info) {
                GoodsBrowseLog::insert([
                    'user_id' => $userId,
                    'goods_id' => $goodsId,
                    'store_id' => request()->header()['storeid'],
                    'ctime' => date('Y-m-d')
                ]);
            }
        }

        return $goodsInfo;
    }

    public function getDetails2(int $goodsId, bool $verifyStatus = true)
    {
        // 关联查询(商品图片、sku列表)
        $with = ['images.file'];
        // 获取商品记录
        $goodsInfo = $this->getGoodsMain($goodsId, $with, $verifyStatus);

        return $goodsInfo;
    }

    /**
     * 获取商品详情 (仅包含主商品信息和商品图片)
     * @param int $goodsId 商品ID
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return mixed
     * @throws BaseException
     */
    public function getBasic(int $goodsId, bool $verifyStatus = true)
    {
        // 关联查询(商品图片)
        $with = ['images.file'];
        // 获取商品记录
        return $this->getGoodsMain($goodsId, $with, $verifyStatus);
    }

    /**
     * 获取商品规格数据
     * @param int $goodsId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSpecData(int $goodsId): array
    {
        $data = [];
        // 商品SKU列表
        $data['skuList'] = GoodsSkuModel::getSkuList($goodsId, true);
        // 商品规格列表
        $data['specList'] = GoodsSpecRelModel::getSpecList($goodsId);
        return $data;
    }

    /**
     * 获取商品主体信息
     * @param int $goodsId 商品ID
     * @param array $with 关联查询
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return mixed
     * @throws BaseException
     */
    private function getGoodsMain(int $goodsId, array $with = [], bool $verifyStatus = true)
    {
        // 获取商品记录
        $goodsInfo = static::detail($goodsId, $with);
        // 判断商品是否存在
        if (empty($goodsInfo) || $goodsInfo['is_delete']) {
            throwError('很抱歉,商品信息不存在');
        }
        // 判断商品状态(上架)
        if ($verifyStatus && $goodsInfo['status'] == GoodsStatusEnum::OFF_SALE) {
            throwError('很抱歉,当前商品已下架');
        }
        // 整理商品数据并返回
        return $this->setGoodsDataFromApi($goodsInfo);
    }

    /**
     * 根据商品id集获取商品列表
     * @param array $goodsIds
     * @return mixed
     */
    public function getListByIdsFromApi(array $goodsIds)
    {
        // 获取商品列表
        $data = $this->getListByIds($goodsIds, GoodsStatusEnum::ON_SALE);
        // 整理列表数据并返回
        return $this->setGoodsListDataFromApi($data);
    }

    /**
     * 获取商品指定的sku信息并且设置商品的会员价
     * @param mixed $goodsInfo 商品信息
     * @param string $goodsSkuId 商品SKUID
     * @param bool $enableGradeMoney 是否设置会员折扣价
     * @return \app\common\model\GoodsSku|array|null
     * @throws BaseException
     */
    public static function getSkuInfo($goodsInfo, string $goodsSkuId, bool $enableGradeMoney = true)
    {
        $goodsInfo['skuInfo'] = GoodsService::getSkuInfo($goodsInfo['goods_id'], $goodsSkuId);
        $enableGradeMoney && (new static)->setGoodsGradeMoney($goodsInfo);
        return $goodsInfo['skuInfo'];
    }

    /**
     * 设置商品展示的数据 api模块
     * @param $data
     * @return mixed
     */
    private function setGoodsListDataFromApi($data)
    {
        return $this->setGoodsListData($data, function ($goods) {
            // 整理商品数据 api模块
            $this->setGoodsDataFromApi($goods);
        });
    }

    /**
     * 整理商品数据 api模块
     * @param $goodsInfo
     * @return mixed
     */
    private function setGoodsDataFromApi($goodsInfo)
    {
        return $this->setGoodsData($goodsInfo, function ($goods) {
            // 计算并设置商品会员价
            $this->getEnableGradeMoney() && $this->setGoodsGradeMoney($goods);
            //计算plus 分销价格
            $this->setGoodsMoney($goods);
        });
    }

    /**
     * 设置商品plus 分销价格
     * @param Goods $goods
     * @throws BaseException
     */
    private function setGoodsMoney(self $goods)
    {
        // 判断是否登录
        if (!UserService::isLogin()) {
            return;
        }
        $catService = new \app\store\model\GoodsCategoryRel();
        $catIds = $catService->where(['goods_id' => $goods->goods_id])->column('category_id');
        //读取分类集
        $price_list_plus = $price_list_dealer = [];
        foreach ($catIds as $k => $v) {
            $price_list_plus[] = GoodsPriceModel::getDiscountPrice($v, 1, $goods['goods_price_min']);
            $price_list_dealer[] = GoodsPriceModel::getDiscountPrice($v, 2, $goods['goods_price_min']);
        }
        //价格判断
        if (UserService::isstore()) {
            $goods['goods_price_min_plus'] = min($price_list_plus);
            $goods['goods_price_min_dealer'] = min($price_list_dealer);
        } elseif (UserService::isPlusMember()) {
            $goods['goods_price_min_plus'] = min($price_list_plus);
        } elseif (UserService::isDealerMember()) {
            $goods['goods_price_min_dealer'] = min($price_list_dealer);
        }
        // 会员折扣价: 商品sku列表
        if ($goods->getRelation('skuList')) {
            foreach ($goods['skuList'] as &$skuItem) {
                $temp_price_plus = $temp_price_dealer = [];
                foreach ($catIds as $k => $v) {
                    $temp_price_plus[] = GoodsPriceModel::getDiscountPrice($v, 1, $skuItem['goods_price']);
                    $temp_price_dealer[] = GoodsPriceModel::getDiscountPrice($v, 2, $skuItem['goods_price']);
                }
                //价格判断
                if (UserService::isstore()) {
                    $skuItem['goods_price_plus'] = min($temp_price_plus);
                    $skuItem['goods_price_dealer'] = min($temp_price_dealer);
                } elseif (UserService::isPlusMember()) {
                    $skuItem['goods_price_plus'] = min($temp_price_plus);
                } elseif (UserService::isDealerMember()) {
                    $skuItem['goods_price_dealer'] = min($temp_price_dealer);
                }

            }
        }
        // 折扣价: 已选择的商品sku(用于购物车)
        if ($goods->getAttr('skuInfo')) {
            if (UserService::isPlusMember()) {
                $sku_price_plus = [];
                foreach ($catIds as $k => $v) {
                    $sku_price_plus[] = GoodsPriceModel::getDiscountPrice($v, 1, $goods['skuInfo']['goods_price']);
                }
                $goods['skuInfo']['goods_price'] = min($sku_price_plus);
            } elseif (UserService::isDealerMember()) {
                $sku_price_dealer = [];
                foreach ($catIds as $k => $v) {
                    $sku_price_dealer[] = GoodsPriceModel::getDiscountPrice($v, 2, $goods['skuInfo']['goods_price']);
                }
                $goods['skuInfo']['goods_price'] = min($sku_price_dealer);
            }

        }
    }

    /**
     * 设置商品的会员价
     * @param Goods $goods
     * @throws BaseException
     */
    private function setGoodsGradeMoney(self $goods)
    {
        // 设置当前商品是否使用会员等级折扣价
        $goods['is_user_grade'] = false;
        // 获取当前登录用户的会员等级信息
        $gradeInfo = UserGradeService::getCurrentGradeInfo();
        // 判断商品是否参与会员折扣
        if (empty($gradeInfo) || !$goods['is_enable_grade']) {
            return;
        }
        // 默认的折扣比例
        $discountRatio = $gradeInfo['equity']['discount'];
        // 商品单独设置了会员折扣
        if ($goods['is_alone_grade'] && isset($goods['alone_grade_equity'][$gradeInfo['grade_id']])) {
            $discountRatio = $goods['alone_grade_equity'][$gradeInfo['grade_id']];
        }
        if (empty($discountRatio)) {
            return;
        }
        // 标记参与会员折扣
        $goods['is_user_grade'] = true;
        // 会员折扣价: 商品基础价格
        $goods['goods_price_min'] = UserGradeService::getDiscountPrice($goods['goods_price_min'], $discountRatio);
        $goods['goods_price_max'] = UserGradeService::getDiscountPrice($goods['goods_price_max'], $discountRatio);
        // 会员折扣价: 商品sku列表
        if ($goods->getRelation('skuList')) {
            foreach ($goods['skuList'] as &$skuItem) {
                $skuItem['goods_price'] = UserGradeService::getDiscountPrice($skuItem['goods_price'], $discountRatio);
            }
        }
        // 会员折扣价: 已选择的商品sku(用于购物车)
        if ($goods->getAttr('skuInfo')) {
            $goods['skuInfo']['goods_price'] = UserGradeService::getDiscountPrice($goods['skuInfo']['goods_price'], $discountRatio);
        }
    }
}