<?php

namespace App\Http\Controllers\V1;

use App\Models\Product;
use App\Models\ProductType;
use App\Models\ReportLog;
use App\Models\UserCollect;
use App\Models\UserLike;
use Illuminate\Http\Request;

/**
 *
 * 产品
 */
class ProductController extends Controller
{
    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;

        //如果用户被删除，会自动退出登录
        if (!empty($this->user->deleted_at)) {
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
    }
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *分类数据筛选
     */
    public function filterTypeList(Request $request){
      $pid = $request->input('pid');
      $map = [];
      $maps = [];
      if($pid){
          $map[] = ['pid','=',$pid];
          $maps[] = ['filter_display_pid','=',$pid];
      }
      $list = ProductType::query()
          ->where('status',1)
          ->where($map)
          ->orWhere($maps)
          ->get();
      $data = [];
      foreach ($list as $v){
          $data[] =[
              'id'                  => $v['id'],
              'icon'                => $v['icon'],
              'zh_name'             => $v['zh_alias'] != null?$v['zh_alias']:$v['zh_name'],
              'ko_name'             => $v['ko_alias'] != null?$v['ko_alias']:$v['ko_name'],
              'pid'                 => $v['filter_display_pid'] > 0?$v['filter_display_pid']:$v['pid'],
              'is_display'          => $v['is_filter_display']
          ];
      }
      return $this->success($this->recursion($data,$pid?$pid:0));
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 分类数据上传
     */
    public function uploadTypeList(Request $request){
        $pid = $request->input('pid');
        $map = [];
        $maps = [];
        if($pid){
            $map[] = ['pid','=',$pid];
            $maps[] = ['upload_display_pid','=',$pid];
        }
        $list = ProductType::query()
            ->where('status',1)
            ->where($map)
            ->orWhere($maps)
            ->get();
        $data = [];
        foreach ($list as $v){
            $data[] =[
                'id'                  => $v['id'],
                'icon'                => $v['icon'],
                'zh_name'             => $v['zh_alias'] != null?$v['zh_alias']:$v['zh_name'],
                'ko_name'             => $v['ko_alias'] != null?$v['ko_alias']:$v['ko_name'],
                'pid'                 => $v['upload_display_pid'] > 0?$v['upload_display_pid']:$v['pid'],
                'is_display'          => $v['is_upload_display']
            ];
        }
        return $this->success($this->recursion($data,$pid?$pid:0));
    }

    /**
     * @param $list
     * @param $pid
     * @return array
     * 递归处理
     */
    public function recursion($list = [],$pid = 0){
        $child = [];
        foreach ($list as $value) {
            if($value['is_display'] != 0){
                if ($value['pid'] == $pid ) {
                    if($this->recursion($list, $value['id'])){
                        // 递归调用，查找当前数据的子级
                        $value['child'] = $this->recursion($list, $value['id']);
                    }
                    // 把子级数据添加进数组
                    $child[] = $value;
                }
            }
        }
        return $child;
    }

    /**
     * @return void
     * 添加产品
     */
    public function addProduct(Request $request){
        $params =  $request->all();
        if(empty($params)){
            return $this->error("数据不能为空！");
        }
        $params['user_id'] = $this->userId; // 用户ID
        $res = Product::query()->create($params);
        if(!$res){
            return $this->error("上传失败！");
        }
        return $this->success();

    }

    /**
     * @return void
     * 我的上传列表
     */
    public function userProductList(Request $request){

        $limit = $request->get('limit',10);
        $list = Product::query()->where('status','=',1)
            ->where('user_id','=',$this->userId)
            ->orderByDesc('id')
            ->paginate($limit);
       return $this->success($this->page($list));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 产品列
     */
    public function productList(Request $request){
        $limit = $request->get('limit',10);
        $type = $request->get('type');
        $query = Product::query()->with('user:id,name,nickname,avatar,company_name,company_card_color,production_project');
        if(!empty($type)){
            $query->whereIn('type',$type);
        }
        $list = $query->where('status',1)->paginate($limit);
        return $this->success($this->page($list));
    }

    /**
     * @return void
     * 产品详情
     */
    public function productDetail(Request $request){

        $data = Product::query()
            ->with('user:id,name,nickname,avatar,company_name,company_url,production_project')
            ->select("id","name","user_id","content","image","type")->first();

       return $this->success($data);

    }

    /**
     * @return void
     * 添加收藏
     */
    public function addCollect(Request $request){
        $product = Product::query()->where('id',$request->get('product_id'))->first();
        if(!$product){
            return $this->error("商品不存在！");
        }
        $collect = UserCollect::query()->where('product_id',$product->id)->where('user_id',$this->userId)->first();
        if($collect){
           return $this->error("您已收藏过了！");
        }
        $data =[
            'product_id' => $product->id,
            'user_id' => $this->userId,
        ];
        $res = UserCollect::query()->create($data);
        if(!$res){
            return $this->error("收藏失败！");
        }
        return $this->success();
    }

    /**
     * @return void
     * 添加喜欢
     */
    public function addLike(Request $request){
        $product = Product::query()->where('id',$request->get('product_id'))->first();
        if(!$product){
            return $this->error("商品不存在！");
        }
        $collect = UserLike::query()->where('product_id',$product->id)->where('user_id',$this->userId)->first();
        if($collect){
            return $this->error("您已点赞过了！");
        }
        $data =[
            'product_id' => $product->id,
            'user_id' => $this->userId,
        ];
        $res = UserLike::query()->create($data);
        if(!$res){
            return $this->error("操作失败！");
        }
        return $this->success();
    }

    /**
     * @return void
     * 收藏列表
     */
    public function collectList(Request $request){
        $limit = $request->get('limit',10);
        $list = UserCollect::query()
            ->with('product:id,name,image')
            ->where('user_id',$this->userId)
            ->where('is_arrange','=',0)
            ->select("id","product_id")
            ->paginate($limit);
        return $this->success($this->page($list));
    }

    /**
     * @return void
     * 举报图片
     */
    public function report(Request $request){
        $params = $request->all();
        if(empty($params['product_id'])){
            return $this->error("举报项不能为空！");
        }
        if(empty($params['report_id'])){
            return $this->error("举报问题不能为空！");
        }
        $params['user_id'] = $this->userId;
        $res = ReportLog::query()->create($params);
        if(!$res){
            return $this->error("举报失败！");
        }
        return $this->success();
    }


}
