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

namespace app\api\logic\twoshop;
use app\common\{model\TwoGoods,
    logic\BaseLogic,
    model\TwoGoodsComment,
    model\TwoGoodsVisit,
    model\TwoGoodsCollect,
    model\SearchRecord};
use app\common\service\ConfigService;


/**
 * 商品接口逻辑层
 * Class GoodsLogic
 * @package app\api\logic
 */
class GoodsLogic extends BaseLogic
{

    /**
     * @notes 商品详情
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail($params)
    {
        $id = $params['id'];
        $userId = $params['user_id'];

        $goods = TwoGoods::with(['spec_value.spec_list','spec_value_list','user2','user2.user_level'])
            // ->field('id,name,type,image,video,video_cover,total_stock,click_num,virtual_sales_num+sales_num as sales_num,unit_id,spec_type,content,poster,virtual_click_num,express_type,express_money')
            // ->append(['goods_image'])
            ->find($id);

        

            
        if(empty($goods)){
             self::$error = '商品已下架！';
             return false;
        }
        // 判断是否需要统计浏览量
        // if (isset($params['visit'])) {
            //记录点击量
            $goods->click_num = $goods->click_num + 1;
            $goods->save();

            // 浏览量
            $this->visit($id, $userId);
        // }

        $stockShow = ConfigService::get('goods_set', 'is_show', 1);
        $showPrice = ConfigService::get('goods_set', 'show_price', 1);
        $goods->stock_show = true;
        if(0 == $stockShow){
            $goods->stock_show = false;
        }

        if($userId) {
           

            //是否收藏过
            $IsCollect = TwoGoodsCollect::where(['goods_id' => $id, 'user_id' => $userId,'type'=>1])->value('id');
            $goods->is_collect = $IsCollect ? 1 : 0;

            // 是否收藏
            $IsCollect = TwoGoodsCollect::where(['goods_id' => $id, 'user_id' => $userId,'type'=>2])->value('id');
            $goods->is_like = $IsCollect ? 1 : 0;

            // 计算点赞个数和收藏个数
            $goods->collect_count =  TwoGoodsCollect::where(['goods_id' => $id,'type'=>1])->count();
            $goods->like_count =  TwoGoodsCollect::where(['goods_id' => $id,'type'=>2])->count();

            $goods->member_price    = $goods->spec_value_list[0]->member_price;
        }
        if(0 == $showPrice){
            foreach ($goods->spec_value_list as $key =>$specValue){
                $specValue['lineation_price'] = 0;
            }
        }
        $goods->sell_price      = $goods->spec_value_list[0]->sell_price;
        $goods->lineation_price = $goods->spec_value_list[0]->lineation_price;

        

        $goods->click_num += $goods->virtual_click_num;
        $goods->unit_name = '';
        if($goods->unit_id){
            $goods->unit_name = $goods->unit->name;
        }
        $goods->hidden(['unit_id','unit']);
        $goods->distribution = 0;

        // 运费
        if ($goods->express_type == 1) {
            $goods->free_shipping_tips = '￥0.00';
        } else {
            if ($goods->express_type == 2) {
                $goods->free_shipping_tips = self::getFreeShippingTips($userId,$goods->express_money);
            }
            if ($goods->express_type == 3) {
                $goods->free_shipping_tips = self::getFreeShippingTips($userId,0);
            }
        }

        // 计算评论评分
        $goods_comment1 = \app\common\model\TwoGoodsComment::where('goods_comment',1)->where('goods_id',$goods->id)->count();
        $goods_comment2 = \app\common\model\TwoGoodsComment::where('goods_comment',2)->where('goods_id',$goods->id)->count();
        $goods_comment3 = \app\common\model\TwoGoodsComment::where('goods_comment',3)->where('goods_id',$goods->id)->count();
        $goods_comment4 = \app\common\model\TwoGoodsComment::where('goods_comment',4)->where('goods_id',$goods->id)->count();
        $goods_comment5 = \app\common\model\TwoGoodsComment::where('goods_comment',5)->where('goods_id',$goods->id)->count();
        $goods->source = $this->calculateRating($goods_comment1,$goods_comment2,$goods_comment3,$goods_comment4,$goods_comment5);

        $data = $goods->toArray();

        $data['comment1'] = $goods_comment1;
        $data['comment2'] = $goods_comment2;
        $data['comment3'] = $goods_comment3;
        $data['comment4'] = $goods_comment4;
        $data['comment5'] = $goods_comment5;

        $data['category'] = \app\common\model\TwoGoodsCategory::where('id', $goods['category_id'])->find();
        $types = \app\common\model\TwoType::whereIn('id', explode(',', $goods['type_ids'] ?? ''))->select();

        $data['types'] = [];

        foreach ($types as $type) {
            if ($type['pid'] === 0) {
                $data['types'][] = $type;
                continue;
            }

            $item = \app\common\model\TwoType::find($type['pid']);

            if ($item['is_option'] != 1) {
                $data['types'][] = $type;
                continue;
            }

            $item['value'] = $type;
            $data['types'][] = $item;
        }

        $data['user'] = [];
        $data['user']['id'] = $data['user2']['id'];
        $data['user']['nickname'] = $data['user2']['nickname'];
        $data['user']['avatar'] = $data['user2']['avatar'];
        $data['user']['login_time'] = $data['user2']['login_time'];
        $data['user']['last_online_time'] = $data['user2']['last_online_time'];
        $data['user']['user_level'] = $data['user2']['user_level'];
        $data['user']['is_follow'] = !!\app\common\model\UserFollow::where([ 'follow_user_id' => $data['user2']['id'], 'user_id' => $userId ])->find();
        unset($data['user2']);

        $data['create_time'] = formatTime($goods['create_time']).'发布';

        return $data;
    }

    public static function avgComment($uid, $field = 'sell_user_id')
    {
        $comments = TwoGoodsComment::where($field, $uid)->where('status', 1)->select()->toArray();

        if (count($comments) <= 0) {
            return 5;
        }

        $all = 0;
        $count = 0;

        foreach ($comments as $comment) {
            $comment = round(
                (
                    intval($comment['goods_comment']) +
                    intval($comment['service_comment']) +
                    intval($comment['description_comment']) +
                    intval($comment['express_comment'])
                ) / 4
            );

            if ($comment < 1) {
                $comment = 1;
            }

            if ($comment > 5) {
                $comment = 5;
            }

            $all += $comment;
            $count++;
        }

        $result = round($all / $count);

        if ($result < 1) {
            $result = 1;
        }

        if ($result > 5) {
            $result = 5;
        }

        return $result;
    }

    public static function getCommentRate($uid, $field = 'sell_user_id')
    {
        $comments = TwoGoodsComment::where($field, $uid)->where('status', 1)->select()->toArray();

        if (count($comments) <= 0) {
            return 1;
        }

        $count = 0;

        foreach ($comments as $comment) {
            $comment = round(
                (
                    intval($comment['goods_comment']) +
                    intval($comment['service_comment']) +
                    intval($comment['description_comment']) +
                    intval($comment['express_comment'])
                ) / 4
            );

            if ($comment < 1) {
                $comment = 1;
            }

            if ($comment > 5) {
                $comment = 5;
            }

            if ($comment > 3) {
                $count++;
            }
        }

        return $count / count($comments);
    }

    public function calculateRating($star1, $star2, $star3, $star4, $star5) {
        // 计算总评价数
        $total = $star1 + $star2 + $star3 + $star4 + $star5;
        
        // 处理零评价情况
        if ($total == 0) return 0.00;
        
        // 计算加权总分
        $weightedSum = 
            ($star1 * 1) + 
            ($star2 * 2) + 
            ($star3 * 3) + 
            ($star4 * 4) + 
            ($star5 * 5);
        
        // 计算并格式化结果
        return round($weightedSum / $total, 2);
    }

    /**
     * @notes 商品搜索记录
     * @param $userId
     * @param $limit
     * @return array
     */
    public function searchRecord($userId,$limit){
        $recordList = SearchRecord::where(['user_id'=>$userId])
            ->limit($limit)
            ->order('id desc')
            ->column('keyword');

        return $recordList;
    }

    /**
     * @notes 清空搜索记录
     * @param int $userId
     */
    public function clearRecord(int $userId)
    {
        SearchRecord::where(['user_id'=>$userId])->delete();
    }

    /**
     * @notes 商品浏览记录
     * @param $goodsId
     * @param $userId
     * @return bool
     */
    public function visit($goodsId, $userId)
    {
        // echo '浏览记录';die;
        if (empty($userId)) {
            $userId = 0;
        }
        $ip = request()->ip();

        // 一个ip一个商品一个用户一天只生成一条记录
        $record = TwoGoodsVisit::where([
            'ip' => $ip,
            'goods_id' => $goodsId,
            'user_id' => $userId,
        ])->whereDay('create_time')->findOrEmpty();

        if (!$record->isEmpty()) {
            // 增加浏览量
            $record->visit += 1;
            $record->save();
            return true;
        }

        // 生成商品浏览记录
        TwoGoodsVisit::create([
            'ip' => $ip,
            'goods_id' => $goodsId,
            'user_id' => $userId,
            'visit' => 1
        ]);
    }

    /**
     * @notes 自定义海报获取商品信息
     */
    public static function getGoodsByTypeId($type, $activityId, $goodsId, $userId) {
        // type 1普通通商品 
        switch($type) {
            case 1:
                return Goods::field('name, image, min_lineation_price, min_price')->where('id', $goodsId)->findOrEmpty()->toArray();
            default:
                return [];
        }
    }

    public static function getFreeShippingTips($userId,$express_money = 0) {
        // 用户未登录
        if (empty($userId)) {
            return '';
        }
        return '￥'.$express_money;
    }
}
