<?php

namespace App\Http\Controllers\V1;

use App\Models\Msg;
use App\Models\Product;
use App\Models\ProductType;
use App\Models\Report;
use App\Models\ReportLog;
use App\Models\User;
use App\Models\UserCollect;
use App\Models\UserFollow;
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)
          ->orderByDesc("sort")
          ->get();
      $data = [];
      foreach ($list as $v){
          if($v['filter_display_pid'] === 0){
              $v['pid'] = 0;
          }elseif ($v['filter_display_pid'] > 0){
              $v['pid'] = $v['filter_display_pid'];
          }else{
              $v['pid'] = $v['pid'];
          }

          $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['pid'],
              'is_display'          => $v['is_filter_display'],
              'product_count'       => Product::query()->whereJsonContains('type',[$v['id']])->where('status',1)->count()
          ];
      }
      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)
            ->orderByDesc("sort")
            ->get();
        $data = [];
        foreach ($list as $v){
            if($v['upload_display_pid'] === 0){
                $v['pid'] = 0;
            }elseif ($v['upload_display_pid'] > 0){
                $v['pid'] = $v['upload_display_pid'];
            }else{
                $v['pid'] = $v['pid'];
            }
            $data[] = [
                'id'                  => $v['id'],
                'icon'                => $v['icon'],
                'zh_name'             => $v['zh_name'],
                'ko_name'             => $v['ko_name'],
                'describe'            => $v['describe'],
                '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("数据不能为空！");
        }
        if(empty($params['type'])){
           return $this->error("分类不能能为空！");
        }
        $params['user_id'] = $this->userId; // 用户ID
        $res = Product::query()->create($params);
        if(!$res){
            return $this->error("上传失败！");
        }
        $follow = UserFollow::query()->where('to_user_id',$this->userId)->pluck('user_id')->toArray();
        if(!empty($follow)){
            $user = User::query()->where('id',$this->userId)->first();
            foreach ($follow as $v){
                $msg = [
                    'type' => 5,//关注的人发了新作品
                    'title' => "关注的人发了新作品",
                    'content' => " 您关注的".$user->name."上传了1张图片",
                    'user_id' => $this->userId,
                    'to_user_id' => $v,
                ];
                Msg::query()->create($msg); // 添加通知消息
            }
        }
        return $this->success($res);

    }

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

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

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 产品列表
     */
    public function productList(Request $request){
        $limit = $request->get('limit',10);
        $type = $request->get('type');
        $keyword = $request->get('keyword');
        $go = $request->get('go',6);
        $query = Product::query()
            ->with('user:id,name,nickname,avatar,company_name,company_card_color,production_project');
        if(!empty($type)){
            $type =  array_map('intval', explode(',',$type));
            $query->whereJsonContains('type',$type);
        }
        if(!empty($keyword)){
            $query->where('name','like','%'.$keyword.'%');
        }
        $list = $query->where('status',1)
            ->paginate(intval($limit));
        foreach ($list as $v){
            $v['is_collect'] = 0;
            if(!empty($this->userId)){
                $v['is_collect'] = UserCollect::query()->where('product_id',$v['id'])->where('user_id',$this->userId)->count();
            }
        }
        return $this->success(pages($list,$go));
    }

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

        $data = Product::query()
            ->with('user:id,name,nickname,avatar,company_name,company_url,production_project')
            ->where('status',1)
            ->where('id',$request->get('id'))
            ->select("id","name","user_id","content","image","type","url")->first();
        if(!$data){
            return $this->error("数据不存在！");
        }
        $data['is_collect'] = 0; // 收藏
        $data['is_follow'] = 0; // 关注
        $data['is_like'] = 0; // 喜欢
        if(!empty($this->userId)){
            $data['is_collect'] = UserCollect::query()->where('product_id',$data['id'])->where('user_id',$this->userId)->count();
            $data['is_follow'] = UserFollow::query()->where('to_user_id',$data['user_id'])->where('user_id',$this->userId)->count();
            $data['is_like'] = UserLike::query()->where('product_id',$data['id'])->where('user_id',$this->userId)->count();
        }
        if(!empty($data['user'])){
            $data['user']['follow_count'] = UserFollow::query()->where('user_id',$data['user_id'])->count();
        }
       return $this->success($data);

    }

    /**
     * @param Request $request
     * @return void
     * 删除产品
     */
    public function delProduct(Request $request){
        $id = $request->get('id');
        if(empty($id)){
            return $this->error("缺少参数ID!");
        }
        $product = Product::query()->where('id',$id)->first();
        if(!$product){
            return $this->error("产品不存在！");
        }
        $product->delete();
        return $this->success();
    }

    /**
     * @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("收藏失败！");
        }
        $user = User::query()->where('id',$this->userId)->first();
        $product_type = ProductType::query()->whereIn('id',$product['type'])->select('id','zh_name','ko_name')->first();
        $type_name = '';
        if(!empty($product_type)){
            $type_name = $product_type['zh_name'];
        }
        $msg = [
            'type' => 2,//下载通知
            'title' => "下载通知",
            'content' => "您收藏了".$type_name."中的1张图片",
            'user_id' => $this->userId,
            'to_user_id' => $this->userId,
        ];
        Msg::query()->create($msg); // 添加通知消息

        $msg1 = [
            'type' => 3,//保存通知
            'title' => "保存通知",
            'content' => $user->name."收藏了您".$type_name."中的1张图片",
            'user_id' => $this->userId,
            'to_user_id' => $product['user_id'],
        ];
        Msg::query()->create($msg1); // 添加通知消息

        return $this->success();
    }

    /**
     * @return void
     * 取消收藏
     */
    public function cancelCollect(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){
            $collect->delete();
        }
        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("操作失败！");
        }
        $user = User::query()->where('id',$this->userId)->first();
        $product_type = ProductType::query()->whereIn('id',$product['type'])->select('id','zh_name','ko_name')->first();
        $type_name = '';
        if(!empty($product_type)){
            $type_name = $product_type['zh_name'];
        }
        $msg = [
            'type' => 1,//喜欢通知
            'title' => "喜欢通知",
            'content' => $user->name."点赞了您".$type_name."中的1张图片",
            'user_id' => $this->userId,
            'to_user_id' => $product['user_id']
        ];
        Msg::query()->create($msg); // 添加通知消息

        return $this->success();
    }

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

    /**
     * @return void
     * 举报列表
     */
    public function reportList(){

        $list = Report::query()->where('status',1)->orderByDesc("sort")->get();

        return $this->success($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();
    }


}
