<?php

namespace app\admin\controller\fastim;

use app\common\controller\Backend;
use think\Exception;
use app\admin\model\fastim\Config as ConfigModel;

/*
 * FastIm配置-基于fastadmin系统配置的精简版
 */

class Config extends Backend
{
    protected $model = null;

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

    /*
     * 查看
     */
    public function index()
    {
        $this->view->assign('configList', $this->model::getConfigListByGroup(null, 0));
        return $this->view->fetch();
    }

    /*
     * 保存修改
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $this->token();
            $row = $this->request->post("row/a", [], 'trim');

            if ($row) {
                $configList = [];
                foreach ($this->model->all() as $v) {
                    if (isset($row[$v['name']])) {
                        $value = $row[$v['name']];
                        if (is_array($value) && isset($value['field'])) {
                            $value = json_encode(ConfigModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
                        } else {
                            $value = is_array($value) ? implode(',', $value) : $value;
                        }
                        $v['value']   = $value;
                        $configList[] = $v->toArray();
                    }
                }
                try {
                    $this->model->allowField(true)->saveAll($configList);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
}