<?php
namespace App\Http\Controllers\Api;

use App\Command\Log;
use App\Models\Brand;
use App\Models\BrandLevel;
use App\Models\Category;
use App\Models\Manufacturer;
use App\Models\ManufacturerCommand;
use App\Models\User;
use App\Models\UserPermission;
use Illuminate\Http\Request;

class ProductController extends BaseController {

    public function getOneLevelCategory(Request $request){
        $slug = $request->slug ?? '';
       
        if(!in_array($slug,['manufacturer','performance','marketPrice','sample','advantage'])){
            return $this->JsonResponse('','参数错误2',201);
        }
        $list_data = Category::where(['parent_id'=>0])->select(['id','title'])->get();
        $data = [];
        $model = 'App\\Models\\'.ucfirst($slug);
        if($list_data->toArray()){
            foreach ($list_data as $datum){
                if($model::where(['cate_1'=>$datum->id])->count() > 0){
                    $data[] = ['id'=>$datum->id,'title'=>$datum->title];
                }
            }
        }
        return $this->JsonResponse($data);
    }

    public function getSecondaryCategory(Request $request){
        $parent_id = $request->parent_id ?? null;
        if(!$parent_id){
            return $this->JsonResponse('','参数错误',201);
        }
        $slug =  $request->slug ?? '';
        if(!in_array($slug,['manufacturer','performance','marketPrice','sample','advantage'])){
            return $this->JsonResponse('','参数错误2',201);
        }
        $model = 'App\\Models\\'.ucfirst($slug);
        $cate = Category::find($parent_id);
        if(!$cate || $cate->parent_id != 0){
            return $this->JsonResponse('','参数错误2',201);
        }
        $data = [];
        //获取二级品类
        $twoLevel = Category::where(['parent_id'=>$parent_id])->get();
        if($twoLevel->toArray()){
            foreach ($twoLevel as $two){
                if($model::where(['cate_2'=>$two->id])->count() <= 0){
                    continue;
                }
                $twoData = [
                    'id' => $two->id,
                    'title' => $two->title,
                    'level'=>2,
                    'son'=>[]
                ];

                $threeLevel = Category::where(['parent_id'=>$two->id])->get();
                if($threeLevel->toArray()){
                    foreach ($threeLevel as $three){
                        if($model::where(['cate_3'=>$three->id])->count() <= 0){
                            continue;
                        }
                        $twoData['son'][] = [
                            'id' => $three->id,
                            'title' => $three->title,
                            'level'=>3,
                        ];
                    }
                }
                $data[] = $twoData;
            }
        }
        return $this->JsonResponse($data);
    }

    public function getFourLevelData(Request $request){
        $three_id = $request->three_id ?? null;


        $slug = $request->slug ?? '';
        if(!in_array($slug,['manufacturer','performance','marketPrice','sample','advantage'])){
            return $this->JsonResponse('','参数错误2',201);
        }
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $search_text = trim($request->search_text) ?? '';
        $brand_level = $request->brand_level ?? null;
        $brand_level = $brand_level ? json_decode($brand_level,true) : null;
        $brand_id = $request->brand ?? null;
        $brand_id = $brand_id ? json_decode($brand_id, true) : null;
        $f_cate_ids = [];
        //var_dump($three_id);exit();
        if($three_id){
             $f_cate_ids = json_decode($three_id,true);

            // $f_cate = Category::whereIn('parent_id',$three_id)->select(['id'])->get();
            // if($f_cate->toArray()){
            //     foreach ($f_cate as $item){
            //         $f_cate_ids[] = $item->id;
            //     }
            // }
        }
         $f_cate_ids_2 = [];
         $four_id = $request->four_id ?? null;
         if($four_id){
             $f_cate_ids_2 = json_decode($four_id,true);

            // $f_cate = Category::whereIn('parent_id',$three_id)->select(['id'])->get();
            // if($f_cate->toArray()){
            //     foreach ($f_cate as $item){
            //         $f_cate_ids[] = $item->id;
            //     }
            // }
        }

        $model = 'App\\Models\\'.ucfirst($slug);
        $data = [];
        $sql = $model::where(['deleted_at'=>null]);
        if (!empty($f_cate_ids)){
            $sql = $sql->whereIn('cate_3',$f_cate_ids);
        }

        if (!empty($f_cate_ids_2)){
            $sql = $sql->whereIn('cate_4',$f_cate_ids_2);
        }
        $specifications = $request->specifications ?? null;

        if($specifications){
            $sql= $sql->where('specifications','LIKE','%'.$specifications.'%');
        }
        if($search_text != ''){
            switch ($slug){
                case 'manufacturer':
                    $sql= $sql->where('main_products','LIKE','%'.$search_text.'%');
                    break;
                case 'performance':
                    //$sql = $sql->orWhere('parameter','LIKE','%'.$search_text.'%')->orWhere('scene','LIKE','%'.$search_text.'%');
                    $sql2 = $model::where('parameter','LIKE','%'.$search_text.'%')->count();

                    $sql3 = $model::where('scene','LIKE','%'.$search_text.'%')->count();
                    if($sql2>0 && $sql3>0){
                        $sql = $sql->where('parameter','LIKE','%'.$search_text.'%')->where('scene','LIKE','%'.$search_text.'%');
                    }elseif($sql2>0 && $sql3 == 0){
                        $sql = $sql->where('parameter','LIKE','%'.$search_text.'%');
                    }elseif($sql2==0 && $sql3>0){
                         $sql = $sql->where('scene','LIKE','%'.$search_text.'%');
                    }elseif($sql2 == 0 && $sql3 == 0){
                        $sql = $sql->where('parameter','LIKE','%'.$search_text.'%')->where('scene','LIKE','%'.$search_text.'%');
                    }

                    //$sql = $sql->whereJsonContains('parameter',(string)$search_text);
                    break;
                case 'marketPrice':
                    $sql = $sql->where('specifications','LIKE','%'.$search_text.'%');
                    break;
                case 'sample':
                    $sql = $sql->where('project_name','LIKE','%'.$search_text.'%');
                    break;
                case 'advantage':
                    $sql = $sql->where('characteristic','LIKE','%'.$search_text.'%');
            }
        }
        if ($brand_level){
            $sql = $sql->whereIn('brand_level',$brand_level);
        }
        if($brand_id > 0){
            $sql = $sql->whereIn('brand_id',$brand_id);
        }
        $data['total'] = $sql->count();

        $data['list'] = [];
        $listData = $sql->offset(($page - 1) * $limit)->limit($limit)->orderBy('created_at','DESC')->get();
        if($data['total']>0){
            foreach ($listData as $datum){
                $specifications = '';
                $unit_price = '';
                switch ($slug){
                    case 'performance':
                        $parameter = $datum->performance ?? null;
                        $specifications = $parameter ? json_decode($parameter,true)[0] : '';
                        break;
                    case 'marketPrice':
                        $specifications = $datum->specifications ?? '';
                        $unit_price = $datum->unit_price;
                        break;
                    case 'sample':
                        $specifications = $datum->specifications ?? '';
                        break;
                    default :
                        $specifications = '';
                }
                $img_arr = $datum->img_url ?? null;
               $cover_arr = $img_arr ? json_decode($img_arr,true) : [];
               $cover = $cover_arr[0] ?? '';
               $data['list'][] = [
                   'id' => $datum->id,
                   'cover' => $cover,
                   'title' => Category::find($datum->cate_4)->title ?? '',
                   'specifications' => $specifications,
                   'unit_price'=>$unit_price
               ];
            }
        }
        return $this->JsonResponse($data);
    }

    //获取模块单品详情
    public function singleItemInfo(Request $request){
        $id = $request->id ?? null;
        $slug = $request->slug ?? '';
        if(!$id || !in_array($slug,['manufacturer','performance','marketPrice','sample','advantage'])){
            return $this->JsonResponse('','参数错误2',201);
        }
        $model = 'App\\Models\\'.ucfirst($slug);
        $userPerminssion = $request->user()->permissions ? json_decode($request->user()->permissions, true) : [];
        //获取当前模块所有字段
        $parent_id = match ($slug) {
            'manufacturer' => 1,
            'performance' => 2,
            'marketPrice' => 3,
            'sample' => 4,
            'advantage' => 5,
            default => 0,
        };
        $fileds = UserPermission::where(['parent_id'=>$parent_id])->where('slug','!=','add')->get();
        $select = [];
        foreach ($fileds as $filed){
            if(in_array($filed->id, $userPerminssion)){
                $select[] = $filed->slug;
            }
        }
        $data = [];
        $ysData = $model::where(['id'=>$id])->first();
        foreach ($ysData->toArray() as $key=>$datum){
            if(in_array($key,$select)){
                if(in_array($key, ['cate_1','cate_2','cate_3','cate_4'])){
                    $data[$key] = Category::find($datum)->title ?? '';
                }elseif ($key == 'brand_level'){
                    $data[$key] = $ysData->brand_level_model->title ?? '';
                }elseif ($key == 'brand_id'){
                    $data['brand'] = $ysData->brand->title ?? '';
                }elseif ($key == 'img_url'){
                    $data['img'] = empty($datum) ? [] : json_decode($datum, true);
                }elseif ($key == 'parameter'){
                    $data['parameter'] = empty($datum) ? [] : json_decode($datum, true);
                }elseif($key == 'contacts'){
                    $val1 =str_replace(',',',',$datum);
                    $ct_ph = explode(',',$val1);
                    $data['contact'] = $ct_ph[0] ?? '';
                    $data['contact_phone'] = $ct_ph[1] ?? '';
                }elseif($key == 'jwd'){
                    $val1 =str_replace(',',',',$datum);
                    $data['jwd'] = explode(',',$val1) ?? [];
                }elseif($key == 'main_products'){
                    $val1 =str_replace(',',',',$datum);
                    $data['main_products'] = explode(',',$val1);
                }else{
                    $data[$key] = $datum;
                }
            }else{
                $data[$key] = '';
            }
        }

        return $this->JsonResponse($data);
    }

    //获取厂家资源评论列表
    public function getManufacturerCommand(Request $request){
        $id = $request->id ?? 0;
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $sql = ManufacturerCommand::where(['m_id'=>$id]);
        $data = [];
        $data['total'] = $sql->count();

        if($page == 1){
            $data['is_command'] = (bool)ManufacturerCommand::where(['m_id'=>$id,'user_id'=>$request->user()->id])->first();
        }
       $data['list'] = [];
        $list = $sql->offset(($page - 1) * $limit)
            ->limit($limit)
            ->orderBy('created_at','DESC')->get();

        if($data['total']>0){
            foreach ($list as $item){
                $c_user = User::find($item->user_id);
                $img = $item->img_url ? json_decode($item->img_url,true) : [];
                $data['list'][] = [
                    'command_id'=>$item->id,
                    'id'=>$item->m_id,
                    'user_id'=>$item->user_id,
                    'username'=>$c_user->name,
                    'avatar'=>$c_user->avatar,
                    'sjyhnl'=>$item->sjyhnl,
                    'ghsx'=>$item->ghsx,
                    'ghzl'=>$item->ghzl,
                    'dznl'=>$item->dznl,
                    'fwphd'=>$item->fwphd,
                    'pjyj'=>$item->pjyj,
                    'img'=>$img,
                    'created_at'=>date('Y-m-d H:i:s',strtotime($item->created_at))
                ];
            }
        }
        return $this->JsonResponse($data);
    }

    //评论厂家资源
    public function commandManufacturer(Request $request){
        $id = $request->id ?? null;
        if(!$id){
            return $this->JsonResponse('','参数错误',201);
        }
        $command_id = $request->command_id ?? 0;
        $user_id = $request->user()->id;
        if($command_id ==0 && ManufacturerCommand::where(['m_id'=>$id,'user_id'=>$user_id])->first()){
            return $this->JsonResponse('','当前用户已评论',201);
        }


        $model =  ManufacturerCommand::find($command_id) ?? new ManufacturerCommand();
        if($command_id > 0 && $model->user_id && $model->user_id != $user_id){
            return $this->JsonResponse('','非本人评论',201);
        }
        $model->m_id = $id;
        $model->user_id = $user_id;
        $model->sjyhnl = min(($request->sjyhnl ?? 0), 5);
        $model->ghsx = min(($request->ghsx ?? 0), 5);
        $model->ghzl = min(($request->ghzl ?? 0), 5);
        $model->dznl = min(($request->dznl ?? 0), 5);
        $model->fwphd = min(($request->fwphd ?? 0), 5);
        $model->pjyj =  $request->pjyj ?? '';
        $img_arr = [];
        $model->img_url =  json_encode($request->img_arr ?? []);
        $model->save();

        return $this->JsonResponse('');
    }

    //新增模块数据
    public function addData(Request $request){
        $slug = $request->slug ?? null;
        if(!in_array($slug,['manufacturer','performance','marketPrice','sample','advantage'])){
            return $this->JsonResponse('','参数错误',201);
        }
        $parent_id = match ($slug) {
            'manufacturer' => 1,
            'performance' => 2,
            'marketPrice' => 3,
            'sample' => 4,
            'advantage' => 5,
            default => 0,
        };
        $p_id = UserPermission::where(['slug'=>'add','parent_id'=>$parent_id])->first()->id ?? 0;
        $user_pr = $request->user()->permissions ? json_decode($request->user()->permissions,true):[];
        if(!in_array($p_id, $user_pr)){
            return $this->JsonResponse('','无权限操作',201);
        }
        $cate_1_id = Category::getIdForNameAndParentId(($request->cate_1 ?? ''),0);
        $cate_2_id = Category::getIdForNameAndParentId(($request->cate_2 ?? ''),$cate_1_id);
        $cate_3_id = Category::getIdForNameAndParentId(($request->cate_3 ?? ''),$cate_2_id);
        $cate_4_id = Category::getIdForNameAndParentId(($request->cate_4 ?? ''),$cate_3_id);
        $brand_level = BrandLevel::firstOrCreate(['title'=>($request->brand_level ?? '')])->id;
        $brand_id = Brand::firstOrCreate(['title'=>($request->brand ?? '')])->id;
        $model = new ('App\\Models\\'.ucfirst($slug))();
        $model->cate_1 = $cate_1_id;
        $model->cate_2 = $cate_2_id;
        $model->cate_3 = $cate_3_id;
        $model->cate_4 = $cate_4_id;
        $model->brand_level = $brand_level;
        $model->brand_id = $brand_id;
        $model->img_url = json_encode($request->img_arr ?? []);
        switch ($slug){
            case 'manufacturer':
                $model->company = $request->company ?? '';
                $model->company_cate = $request->company_cate ?? '';
                $model->position = $request->position ?? '';
                $model->jwd = $request->jwd ?? '';
                $model->contacts =( $request->contact ?? '').','.($request->phone ?? '');
                $model->main_products = $request->main_products ??'';
                $model->scale = $request->scale ?? '';
                $model->device = $request->device ?? '';
                $model->capacity = $request->capacity ?? '';
                $model->supply_cycle = $request->supply_cycle ?? 0;
                $model->transport = $request->transport ?? 0;
                $model->participate_in_zj = $request->participate_in_zj ?? '';
                $model->participate_in = $request->participate_in ?? '';
                $model->brand_link  = $request->brand_link ??'';
                break;
            case 'performance':
                $model->parameter = json_encode(($request->parameter ?? []), JSON_UNESCAPED_UNICODE);
                $model->scene = $request->scene ?? '';
                $model->installation_method = $request->installation_method ??'';
                $model->standard = $request->standard ?? '';
                break;
            case 'marketPrice':
                $model->company = $request->company ?? '';
                $model->position = $request->position ?? '';
                $model->jwd = $request->jwd ?? '';
                $model->contacts =( $request->contact ?? '').','.($request->phone ?? '');
                $model->specifications = $request->specifications ??'';
                $model->metering = $request->metering ?? '';
                $model->unit = $request->unit ?? '';
                $model->unit_price = $request->unit_price ?? 0;
                $model->pay_way  = $request->pay_way ?? '';
                $model->source = $request->source ?? '';
                $model->quotation_time = $request->quotation_time??'';
                break;
            case 'sample':
                $model->category = $request->category ?? '';
                $model->project_name = $request->project_name ?? '';
                $model->company = $request->company ?? '';
                $model->contacts =( $request->contact ?? '').','.($request->phone ?? '');
                $model->specifications = $request->specifications ??'';
                $model->used_part = $request->used_part ?? '';
                $model->sealed_sample = $request->sealed_sample	?? '';
                break;
            case 'advantage':
                $model->characteristic = $request->characteristic ?? '';
                $model->company = $request->company ?? '';
                $model->goods = $request->goods ?? '';
                $model->contacts =( $request->contact ?? '').','.($request->phone ?? '');
                break;
        }
        if(!$model->save()){
            return $this->JsonResponse('','新增失败',201);
        }
        return $this->JsonResponse('');
    }

    //获取品牌数据
    public function getBrandData(){
        return $this->JsonResponse([
            'brand_level'=> BrandLevel::select(['id','title'])->get(),
            'brand'=>Brand::select(['id','title'])->get()
        ]);

    }

    //主营产品获取三级品类id
    public function zycpzid(Request $request){
        $zycp = $request->zycp ?? null;
        if (!$zycp){
            return $this->JsonResponse('','参数错误',201);
        }
        $zycp = str_replace(',',',',$zycp);
        $zycp_arr = explode(',',$zycp);
        $data = [];
        foreach ($zycp_arr as $item){
            $ca = Category::where(['title'=>$item])->select(['id'])->get();
            if($ca->toArray()){
                foreach ($ca as $value){
                    $data[] = $value['id'];
                }
            }
        }
        if(empty($data)){
            $data = [-1];
        }
        return  $this->JsonResponse($data);
    }

    //公司名称转换公司资源库数据id
    public function muToMid(Request $request){
        $m_name = $request->m_name ?? '';
        if(!$m_name){
            return $this->JsonResponse('','参数错误',201);
        }
        $data = Manufacturer::where(['company'=>$m_name])->first()->id ?? null;
        return  $this->JsonResponse($data);
    }

    //品牌名称获取品牌id
    public function brandNametoId(Request $request){
        $brand_name = $request->brand_name ?? '';
        return $this->JsonResponse(Brand::where(['title'=>$brand_name])->first()->id ?? null);
    }
}