<?php

namespace App\Http\Controllers\Open;

use Illuminate\Http\Request;
use App\Traits\JsonResponseTrait;
use App\Models\ProductDescription;
use App\Http\Controllers\Controller;
use App\Models\ProductCateDescription;
use Illuminate\Support\Facades\Schema;

class CollectController extends Controller
{
    use JsonResponseTrait;

    public function __construct()
    {
        $this->middleware('token');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        config(['managerLang' => 'en']);
        $model = $request->input('model_name');
        if (in_array($model, ['product', 'product-cate'])) {
            $exceptData = ['model_name'];
            if ($model == 'product' && Schema::hasColumn('product_descriptions', 'imgs')) {
                array_push($exceptData, 'imgs');
            }
            $data = $request->except($exceptData);
            $data['is_collect'] = 1;
            $data['flag'] = 0;
            $result = config('system.models.' . $model)::create($data);
            if ($model == 'product-cate') {
                $cate = config('system.models.' . $model)::where('is_collect', 1)->whereNull('parent_id')->first();
                $request->input('parent_id') ? $result->makeChildOf($request->input('parent_id')) : ($cate ? $result->makeChildOf($cate->id) : $result->makeRoot());
                config('system.models.' . $model)::attachSlug($result, $result->cname);
                ProductCateDescription::attachDescription([
                    'en' => ['cname' => $result->cname]
                ], $result->id, 'product_cid', true);
            } else {
                $description = $request->input('description');
                if (in_array('imgs', $exceptData) && !empty($request->input('imgs'))) {
                    $description['en']['imgs'] = $request->input('imgs');
                }
                config('system.models.' . $model)::attachSlug($result, $request->input('description.en.title'));
                ProductDescription::attachDescription($description, $result->id, 'product_id', true);
            }
            return $this->success(['model_id' => $result->id]);
        }

        return $this->error('创建失败！');

    }

}
