<?php

namespace App\Http\Controllers\Admin;

use App\Models\FormData;
use App\Models\FormSet;
use Illuminate\Http\Request;

class FormSetController extends Controller
{
    protected $redirect_index = '/admin/FormSet/index';

    protected $view_path = 'admin.form-sets.';

    protected $pre_uri = '/admin/FormSet/';

    protected $model_name = '表单设置';

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new FormSet();
    }

    public function index()
    {
        $item = $this->model->first();
        if(empty($item)) {
            $item = $this->model->createDefault();
        }

        list($pre_uri, $model, $model_name) = array($this->pre_uri, $this->model, $this->model_name);

        return view($this->view_path . 'index', compact('pre_uri', 'model', 'model_name', 'item'));
    }

    public function update(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id'))) || !is_array($request->input('data'))) {
            return $this->showWarning('参数错误');
        }
        $data = $request->input('data');

        $values = collect(['show_below_index', 'text_1_status', 'text_1_need',  'text_2_status', 'text_2_need', 'text_3_status', 'text_3_need', 'text_4_status', 'text_4_need', 'multi_text_status', 'multi_text_need', 'radio_status', 'radio_need', 'checkbox_status', 'checkbox_need']);

        foreach($values as $value) {
            $data[$value] = isset($data[$value]) ? $data[$value] : 2;
        }
        $data['money'] = floor($data['money'] * 100);

        if(!$item->update($data)) {
            return $this->showWarning('数据库保存失败');
        }
        return $this->showMessage('操作成功');
    }

    public function programCode(Request $request)
    {
        $app = app('wechat.mini_program');
        $response = $app->app_code->getUnlimit('ad', ['page' => 'pages/form/index']);

        $filename = $response->saveAs('public', 'app-code.png');
        dd($filename);
    }
}
