<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

class ContentController extends AdminController
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @param string $model 
     * @return 根据 action 值返回回调函数结果
     */
    public function index(Request $request, $model)
    {
        $model = config('system.models')[$model];
        
        return call_user_func_array([$this, $request->input('action', 'status')], [$model,  $request->all()]);
    }

    //修改状态
    private function status($model, $data) 
    {  
        $status = $data['operating'] == 'close' ? 0 : 1;

        $content[$data['status']] = $status;

        if ($model == 'App\Models\Lang' && $status == 1) {
            $content['enabled'] = $status;
        }

        if (!auth()->user()->isMaster() && $data['status'] == 'buy') {
            return response()->json(['status' => 'success', 'message' => '您没有这个权限！']);
        }

        $model::find($data['id'])->fill($content)->save();

        return response()->json(['status' => 'success', 'message' => '修改成功！', 'content' => $content]);
    }

    // 更新排序
    private function orders($model, $data) 
    {  
        foreach ($data['orders'] as $key => $val) {
            $model::find($key)->update(['orders' => $val]);
        }

        return back()->with('success', '更新排序成功');
    }
    
    // 移动
    private function move($model, $data)
    {
        $model::whereIn('id', $data['id'])->update(['pid' => $data['pid']]);

        return back()->with('success', "内容移动成功，共移动 ".count($data['id'])." 条数据");
    }

    // 复制
    private function copy($model, $data) 
    {
        foreach ($data['id'] as $value) {
            $content = $model::with('description')->find($value)->replicate();
            $content->pid    = $data['pid'];
            $content->slug   = str_slug(str_random(6));
            $content->orders = $model::max('orders') + 1;
            $content->save();

            $description = ($model . 'Description')::find($content->description->id)->replicate();
            $modelId = $model == 'App\Models\Cases' ? 'case_id' : strtolower(class_basename($model)) . '_id';
            $description->{$modelId}    = $content->id;
            $description->save();
        }
       
        return back()->with('success', "内容复制成功，共复制 ".count($data['id'])." 条数据");
    }


}
