<?php

namespace App\Http\Controllers;

use App\Http\Requests\EditConfigInput;
use App\Models\Config;
use Yo;
use Login;

class ConfigController extends Controller
{
  public function create(EditConfigInput $request)
  {
    Login::admin([8]);
    $label = $request->post('label');
    $value = $request->post('value');
    $type = $request->post('type');
    $remark = $request->post('remark');
    $config = new Config();
    $config->label = $label;
    $config->value = $value;
    $config->type = $type;
    $config->remark = $remark ?? '';
    $config->save();
    return Yo::create_echo($config->id);
  }

  public function delete()
  {
    Login::admin([8]);
    $id = request()->post('id');
    Config::where('id', $id)->delete();
    return Yo::delete_echo($id);
  }

  public function update(EditConfigInput $request)
  {
    Login::admin([8]);
    $config_id = $request->post('config_id');
    $label = $request->post('label');
    $value = $request->post('value');
    $type = $request->post('type');
    $remark = $request->post('remark');
    $config = Config::find($config_id);
    if (!$config) Yo::error_echo(100000, ['配置']);
    $config->label = $label;
    $config->value = $value;
    $config->type = $type;
    $config->remark = $remark ?? '';
    $config->save();
    return Yo::update_echo($config->id);
  }

  public function list()
  {
    $configs = Config::get();
    $list = [];
    foreach ($configs as $config) {
      $value = $config->value;
      if (in_array($config->type, [3, 4, 5])) {
        $value = json_decode($value, true);
      }
      $config['value_turn'] = $value;
      $list[] = $config;
    }
    return Yo::echo(['list' => $list]);
  }

  public function get()
  {
    $label_arr = request()->post('label_arr');
    $configs = $this->get_config_list($label_arr);
    $list = [];
    foreach ($configs as $config) {
      $value = $config->value;
      if (in_array($config->type, [3, 4, 5])) {
        $value = json_decode($value, true);
      }
      $list[$config->label] = $value;
    }
    return Yo::echo($list);
  }

  public function get_config_list($arr): array
  {
    $config_arr = [];
    foreach ($arr as $item) {
      $config = Config::where('label', $item)->first();
      if ($config) $config_arr[] = $config;
    }
    return $config_arr;
  }
}
