<?php

namespace App\Http\Controllers\Admin;

use File;
use Storage;
use App\Models\Lang;
use App\Models\Setting;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Services\UploadManager;
use App\Traits\JsonResponseTrait;

class SettingController extends AdminController
{
    use JsonResponseTrait;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($action)
    {
        $action = Str::studly($action);
        return call_user_func([$this, $action]);
    }

    //站点设置
    public function web()
    {
        $config       = Setting::where('lang', 'single')->lists('value', 'name')->toArray();
        $descriptions = Setting::all()->groupBy('lang');
        $tab = request()->input('tab', 'tab-1');
        $langs = Lang::latest('enabled')->where('slug', '<>', config('setting.lang'))->where('buy', 1)->oldest('orders')->get();

        foreach (config('system.brand') as $key => $value) {
            if (array_key_exists($key, $config)) {
                $config[$key] = $config[$key] ?: $value;
            } else {
                $config[$key] = $value;
            }
        }

        return view('admin.setting.index', compact('config', 'descriptions', 'tab', 'langs'));
    }

    //图片设置
    public function img()
    {
        $fonts = ['= 请选择字体 ='] + config('setting.watermarkFont');

        $config = Setting::where('lang', 'single')->lists('value', 'name');

        if (!isset($config['watermark_type'])) {
            $config['watermark_type'] = 1;
        }

        return view('admin.setting.setting_img', compact('config', 'fonts'));
    }

    //高级配置
    public function master()
    {
        // $robots = Storage::disk('robot')->get('robots.txt');

        $config = Setting::where('lang', 'single')->lists('value', 'name');

        return view('admin.setting.setting_master', compact('config'));
    }

    //SEO网站配置
    public function seo()
    {
        $descriptions = Setting::all()->groupBy('lang');
        
        return view('admin.setting.setting_seo', compact('descriptions'));
    }

    //产品SEO网站配置
    public function ProductSeo()
    {
        $descriptions = Setting::all()->groupBy('lang');
        if (!isset($descriptions[config('managerLang')])) $descriptions[config('managerLang')] = $descriptions[config('setting.lang')];

        return view('admin.setting.product_seo', compact('descriptions'));
    }

    //整站翻译
    public function translate()
    {
        return view('admin.setting.setting_translate');
    }

    // Google人机验证配置
    public function reCaptcha()
    {
        $config = Setting::where('lang', 'single')->lists('value', 'name');

        return view('admin.setting.setting_re_captcha', compact('config'));
    }

    // 阿里采集
    public function collect()
    {
        $config = Setting::where('lang', 'single')->lists('value', 'name');

        if (isset($config['collect_status']) && $config['collect_status'] == 2) {
            $httpClient = new \GuzzleHttp\Client();

            try {
                $res = $httpClient->get(config('setting.fw_collect_url') . '/' . $config['collect_task_id'], [
                    'headers' => [
                        'token' => config('setting.fw_collect_token'),
                        'Accept' => 'application/json'
                    ]
                ]);

                $content = json_decode($res->getBody()->getContents());

                if ($content->code == 0 && $content->data->status == 4) {
                    Setting::set(['collect_status' => 3]);
                }
            } catch (\Exception $e) {

            }
        }

        return view('admin.setting.setting_collect', compact('config'));
    }

    /**
     * 水印预览collect
     *
     * @return Response Tmage-type
     */
    public function watermarkPreview()
    {
        $watermakr_img = public_path().'/data/assets/images/watermark_preview.jpg';

        return with(new UploadManager())->watermark($watermakr_img);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        if ($request->has('ai_publish_num')) {
            $ai_publish_num = $request->input('ai_publish_num');
            $config = Setting::where('lang', 'single')->lists('value', 'name');
            $num = $config['ai_publish_num'] ?? '';

            if ($ai_publish_num != $num) {
                $httpClient = new \GuzzleHttp\Client();
                try {
                    $res = $httpClient->post(config('setting.api_url') . '/ai-news', [
                        'headers' => [
                            'token' => Setting::get('apptoken'),
                            'Accept' => 'application/json'
                        ],
                        'form_params' => [
                            'ai_publish_num' => $ai_publish_num
                        ]
                    ]);

                    $content = json_decode($res->getBody()->getContents());
                    if ($content->status == 'success') {
                        Setting::set(['ai_publish_num' => $ai_publish_num]);
                    }
                } catch (\Exception $e) {

                }
            }
        }
        if ($request->has('robots')) {
            $robots = $request->input('robots');
            $config = Setting::where('lang', 'single')->lists('value', 'name');
            $status = $config['robots'] ?? '';
            if ($robots != $status) {
                $httpClient = new \GuzzleHttp\Client();
                try {
                    // 修改外贸管理robot
                    $res = $httpClient->post(config('setting.robots_url'), [
                        'headers' => [
                            'token' => Setting::get('apptoken'),
                            'Accept' => 'application/json'
                        ],
                        'form_params' => [
                            'status' => $robots
                        ]
                    ]);

                    $content = json_decode($res->getBody()->getContents());
                    if ($content->status == 'success') {
                        Setting::set(['robots' => $robots]);
                        if ($robots == 1) {
                            Storage::disk('robot')->put('robots.txt', "User-agent: *\r\nDisallow: /captcha\r\nDisallow: /message?");
                        } else {
                            Storage::disk('robot')->put('robots.txt', "User-agent: *\r\nDisallow: /");
                        }
                    }
                } catch (\Exception $e) {

                }
            }
        }

        $url    = $_SERVER['HTTP_REFERER'];
        $input  = $request->except('_token', 'file', 'action', 'robots', 'tab', 'ai_publish_num');

        $input['keywordType'] = $input['keywordType'] ?? [];

        if ($request->has('is_collect')) {
            $isCollect = $request->input('is_collect');
            $config = Setting::where('lang', 'single')->lists('value', 'name');

            if ($config['collect_status'] != 1) {
                return back()->withInput()->with('error', '已不在待采集状态，请不要重复提交！');
            }

            if ($config['is_collect'] == 0 && $isCollect == 1) {
                $httpClient = new \GuzzleHttp\Client();

                try {
                    $res = $httpClient->post(config('setting.fw_collect_url'), [
                        'headers' => [
                            'token' => config('setting.fw_collect_token'),
                            'Accept' => 'application/json'
                        ],
                        'form_params' => [
                            'name' => $input['collect_name'],
                            'token' => Setting::get('apptoken'),
                            'cms_domain' => $request->getScheme() . '://' . secondaryDomain(),
                            'site' => $input['collect_url'],
                            'bucket' => env('OSS_BUCKET'),
                            'dir' => env('OSS_PATH'),
                            'num' => $input['collect_num']
                        ]
                    ]);

                    $content = json_decode($res->getBody()->getContents());

                    if ($content->code == 0) {
                        $input = array_merge($input, ['collect_status' => 2, 'collect_task_id' => $content->data->id]);
                        unset($input['collect_name']);
                        Setting::set($input);

                        return redirect($url)->with('success', '保存更新成功');
                    } else {
                        return back()->withInput()->with('error', '保存失败，请重新提交！');
                    }
                } catch (\Exception $e) {

                }
            }

            unset($input['collect_name']);
        }

        if ($request->has('action')) {
            if ($request->input('action') == 'web') {
                $input['description'][config('managerLang')]['logoes'] = $input['description'][config('managerLang')]['logoes'] ?? null;
                $input['qr_code'] = $input['qr_code'] ?? null;
                $input['translate_langs'] = $input['translate_langs'] ?? [];
                $input['translate_edit_langs'] = $input['translate_edit_langs'] ?? [];
            }
        }

        $result = Setting::set($input);

        if ($request->has('tab')) {
            if (!strstr($url, 'tab=')) {
                $url = $url . '?tab=' . $request->input('tab');
            } else {
                $url = preg_replace("/([\?|&]tab=)[^&]*/i", '$1' . $request->input('tab'), $url);
            }
        }
        if ($result) {
            return redirect($url)->with('success', '保存更新成功');
        }

        return back()->withInput()->with('error', '保存失败');
    }

    /*
     *异步确认是否可以一键翻译
     */
    public function confirm() 
    {
        $timeSolt = config('setting.translate_time');
        $time     = strtotime("-{$timeSolt} day");
        $config   = Setting::where('lang', 'single')->lists('value', 'name');
        if (!auth()->user()->isMaster() && $timeSolt != 0) {
            if (isset($config['translate_time'])) {
                if (strtotime($config['translate_time']) < $time) {
                    return response()->json(['status' => 'sucess', 'message' => '可以提交翻译！']);
                } else {
                    return response()->json(['status' => 'error', 'message' => $timeSolt.'天以内不能重复提交翻译！']);
                }
            } else {
                return response()->json(['status' => 'sucess']);
            }
        } else {
            return response()->json(['status' => 'sucess']);
        }
    }

    /*
     *异步确认是否可以一键翻译
     */
     public function lang() 
     {
         // 获取已购买语言版本 Lang
        $langs = Lang::where('buy', 1)->where('slug', '!=', config('setting.lang'))->get();
        $data['langs'] = $langs->toArray();
        $data['slug']  = $langs->pluck('slug')->toArray();

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

    /*
     *异步更新一键翻译时间
     */
    public function ajaxUpdate(Request $request)
    {
        $input  = $request->all();
        $input['translate_time'] = date('Y-m-d H:i:s');
        $result = Setting::set($input);

        return response()->json(['status' => $result ? 'sucess' : 'error', 'time' => $input['translate_time']]);

    }

    /*
     *异步更新可翻译语言版本
     */
    // public function ajaxLang(Request $request)
    // {
    //     $input  = $request->all();
    //     $langs  = "<?php\nreturn ".var_export(array_flatten($input['lang']), true).';';
    //     $result = \File::put(config_path('translateLang.php'), $langs);

    //     return response()->json(['status' => $result ? 'sucess' : 'error']);
    // }

    // 支付设置
    public function payment()
    {
        $setting = Setting::all()->lists('value', 'name');

        return view('admin.setting.setting_payment', compact('setting'));
    }


}
