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

namespace app\api\controller;

use app\api\logic\GoodsLogic;
use JmesPath\TreeCompiler;

/**
 * 商品接口控制器
 * Class GoodsController
 * @package app\api\controller
 */
class Goods extends BaseShopController
{
    
    public array $notNeedLogin = ['lists','categoryList','index','detail','goodsMarketing','searchRecord','random'];
    
    /**
     * 首页
     */
    public function index()
    {
        $tab = \app\common\model\GoodsTab::select()->toArray();
        return show(1,'',[
            'tab'=>$tab,
            'alert'=>'弹窗内容数据',
            'goods'
        ]);
    }
    
    /**
     * 获取分类
     */
    public function categoryList()
    {
        $data = \app\common\model\GoodsCategory::select()->toArray();

        $data = buildTree($data);

        return show(1,'',$data);
    }
    
    public function random() {
        $limit = $this->request->get('limit',1);
        $items = \app\common\model\Goods::orderRaw('RAND()')->limit($limit)->field('id')->select()->toArray();
        $result=[];
        foreach ($items as $item) {
            $detail = (new GoodsLogic)->detail(['id'=>$item['id'],'user_id'=>$this->userId]);
            if (false === $detail) {
                return $this->fail(GoodsLogic::getError());
            }
            $result[] = $detail;
        }
        if (count($result) > 0 && count($result) < $limit) {
            while (true) {
                foreach ($result as $item) {
                    if (count($result) >= $limit) {
                        break 2;
                    }
                    
                    $result[] = $item;
                }
            }
        }
        return show(1,'',$result);
    }

    /**
     * @notes 首页商品列表
     * @return \think\response\Json
     */
    public function lists()
    {
        return $this->dataLists();
    }

    /**
     * @notes 搜索记录
     * @return \think\response\Json
     */
    public function searchRecord()
    {
        $limit = $this->request->get('limit ',10);
        $lists = [];
        // if($this->userId){
        //     $lists = (new GoodsLogic())->searchRecord($this->userId,$limit);
        // }
        return $this->success('', $lists);
    }

    /**
     * @note 商品详情
     * @return \think\response\Json
     */
    public function detail()
    {
        $params =  $this->request->get();
        $params['user_id'] = $this->userId;
        $detail = (new GoodsLogic)->detail($params);
        if (false === $detail) {
            return $this->fail(GoodsLogic::getError());
        }
        return $this->success('获取成功', $detail);
    }

    /**
     * @notes 清空搜索记录
     * @return \think\response\Json
     */
    public function clearRecord()
    {
        if($this->userId){
            (new GoodsLogic)->clearRecord($this->userId);
        }
        return $this->success('');
    }

    /**
     * 提交评论
     */
    public function addComment()
    {
        $params = $this->request->post();
        $orderGoods = \app\common\model\OrderGoods::where('order_id',$params['oid'])->find();
        if(!$orderGoods){
            return show(0,'订单不存在');
        }

        $commentRecord = \app\common\model\GoodsComment::where([
            ['user_id','=',$this->userId],
            ['order_id','=',$params['oid']],
        ])->find();
        if($commentRecord){
            return show(0,'已评论请勿反复评论');
        }       

        // 查询订单是否已收获
        $orderLog = \app\common\model\OrderLog::where([
            ['order_id','=',$params['oid']],
            ['operator_id','=',$this->userId],
            ['type','=','3'],
            ['channel','=','103']
        ])
        ->find();

        if(!$orderLog){
            return show(0,'订单异常或未收货');
        }

        $res = \app\common\model\GoodsComment::create([
            'goods_id'=>$orderGoods->goods_id,
            'item_id'=>$orderGoods->item_id,
            'spec_value_str'=>$orderGoods->goods_name,
            'user_id'=>$this->userId,
            'order_goods_id'=>$orderGoods->id,
            'goods_comment'=> $params['goods_comment'],//'商品评论星级 1 一星 2 二星 3三星 4四星 5五星'
            'service_comment'=>$params['service_comment'],//'服务评论星级 1 一星 2 二星 3三星 4四星 5五星',
            'description_comment'=>$params['service_comment'],//'描述相符星级1 一星 2 二星 3三星 4四星 5五星',
            'express_comment'=>$params['express_comment'],//'物流评论星级 1 一星 2 二星 3三星 4四星 5五星',
            'comment'=>$params['comment'],//'商品评论',
            'images'=>$params['images'],
            // 'reply'=>$params['reply'],//'商家回复',
            'status'=>0,//状态,
            'order_id'=>$params['oid'],
        ]);

        // dd($res);
        return show(1,'评论成功');
    }

    /**
     * 根据商品查询商品评论
     */
    public function goodsCommentList()
    {
        $params = $this->request->get();
        // 查询订单是否已收获
        $data = \app\common\model\GoodsComment::with('user')
        ->where([
            ['goods_id','=',$params['goods_id']],
            ['status','=',1]
        ])
        ->order(['id'=>'desc','create_time'=>'desc'])
        ->paginate(10);
        return show(1,'商品评论列表',$data);
    }

}