<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\DwbsUser;
use App\Models\DwbsWarea;
use App\Models\Store;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Comment;
use Illuminate\Support\Facades\Auth;

class CommentController extends Controller
{
    //商品列表
    public function list(Request $request){
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);

        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $data=Comment::query();
        }else{
            $warea_ids=DwbsWarea::where('admin_id',$admin_id)->pluck('id');
            $agent_ids=DwbsUser::whereIn('warea_id',$warea_ids)->pluck('id');
            $store_ids=Store::whereIn('user_id',$agent_ids)->pluck('id');
            $data=Comment::query()->whereIn('store_id',$store_ids);
        }
        //店铺名称手机号筛选
        if($request->has('agent_phone') && !empty($request->input('agent_phone'))){
            $store_ids=Store::where('phone','like',"%".$request->input('agent_phone')."%")
                ->orWhere('name','like',"%".$request->input('agent_phone')."%")->pluck('id');
            $data->whereIn('store_id',$store_ids);
        }
        //客户信息筛选
        if($request->has('user_phone') && !empty($request->input('user_phone'))){
            $user_ids=User::where('phone','like',"%".$request->input('user_phone')."%")
                ->orWhere('nickname','like',"%".$request->input('user_phone')."%")->pluck('id');
            $data->whereIn('user_id',$user_ids);
        }

        $count=$data->where('is_reply',1)->count();
        $list=$data->where('is_reply',1)->with(['user:id,nickname,phone','store:id,name,phone'])
            ->orderBy('id','desc')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'成功',$count);
    }

    //
    public function detail(Request $request){
        $id=$request->input('id');
        $comment=Comment::with('reply')->where('id',$id)->first();
        return $this->success($comment);
    }

    //删除
    public function destroy(Request $request){
        $res=Comment::where('id',$request->input('id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }

}
