<?php

namespace App\Http\Controllers\Admin;

use Request;
use Illuminate\Http\Request as ajaxRequest;

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

    //根据条件获取下载内容
    private function downloads($model, $data)
    {  
        if ($data['title']) {
            $num   = $data['num'] ?? 12;
            $data  = $model::leftJoin('download_descriptions', 'download_descriptions.download_id', '=', 'downloads.id')
                    ->select('downloads.*', 'download_descriptions.title')
                    ->where('download_descriptions.lang', config('setting.lang'))
                    ->where('download_descriptions.title', 'like', "%{$data['title']}%")
                    ->latest('downloads.orders')->simplePaginate($num)->toArray();
         
            return response()->json(['status' => 'success', 'data' => $data]);
        }
    }

    //统计内容数量信息
    private function totals($model, $data)
    {  
        $models = config('system.models');

        $total = [
            'message' => $models['message']::count(),
            'news'    => $models['news']::count(),
            'product' => $models['product']::count(),
            'lang'    => $model::count(),
        ];

        return response()->json(['status' => 'success', 'data' => $total]);
    }

    //获取购买语言版本
    private function langs($model, $data)
    {  
        $data = $model::latest('buy')->oldest('orders')->get();

        $defaultLang  = config('setting.lang');

        foreach ($data as &$value) {
            $domain = $value->slug == $defaultLang ? secondaryDomain() : secondaryDomain($value->slug);
            $value->img = preg_match("#^(https?:)?//(.*)#", $value->img) ? $value->img : url($value->img);
            $value->url = Request::getScheme().'://'.$domain;
        }

        return response()->json(['status' => 'success', 'data' => $data]);
    }



}
