<?php

namespace app\manystoreapi\controller;

use app\common\controller\ManystoreApiBase;
use app\common\model\ManystoreConfig as ManystoreConfigModel;
use app\common\model\ManystoreConfigGroup;
use app\common\model\ManystoreConfig;
use think\Cache;
use think\Exception;

/**
 * 机构API后台：配置接口
 */
class Config extends ManystoreApiBase
{
    protected $noNeedLogin = [];
//    protected $noNeedRight = ['index'];
    protected $layout = '';
    /**
     * @var \app\common\model\Config
     */
    protected $model = null;
    protected $config_value_model = null;
    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
//        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $this->model = model('ManystoreConfig');
        $this->config_value_model = model('ManystoreValue');
    }


    /**
     * 查看配置
     */
    public function index()
    {
        $siteList = [];
        $manystoreConfigGroup = new ManystoreConfigGroup();
        $groupList =  $manystoreConfigGroup->getGroupData();

        foreach ($groupList as $k => $v) {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];
        }

        $config_value_data_array = [];
        $config_value_data = collection($this->config_value_model->where(array('shop_id' => SHOP_ID))->select())->toArray();
        foreach ($config_value_data as $value) {
            $config_value_data_array[$value['config_id']] = $value;
        }

        foreach ($this->model->all() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            $value['title'] = __($value['title']);
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', isset($config_value_data_array[$value['id']]['value']) ? $config_value_data_array[$value['id']]['value'] : $value['default']);
            } else {
                $value['value'] = isset($config_value_data_array[$value['id']]['value']) ? $config_value_data_array[$value['id']]['value'] : $value['default'];
            }
            $value['content'] = json_decode($value['content'], TRUE);
            $siteList[$v['group']]['list'][] = $value;
        }

        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }
        $this->apisuccess('查询成功',  ['siteList' => $siteList]);
    }




    /**
     * @ApiTitle( 修改机构配置)
     * @ApiSummary(修改机构配置)
     * @ApiMethod(POST)
     * @ApiParams(name = "loss_ratio", type = "string",required=false,description = "课程损耗比（百分制）")
     * @ApiReturn({
     *
     *})
     */
    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            $row = $this->request->post();
            if ($row) {
                $configValueAll = [];

                $config_value_data_array = [];
                $config_value_data = collection($this->config_value_model->where(array('shop_id' => SHOP_ID))->select())->toArray();
                foreach ($config_value_data as $value) {
                    $config_value_data_array[$value['config_id']] = $value;
                }
                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(ManystoreConfigModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
                        } else {
                            $value = is_array($value) ? implode(',', $value) : $value;
                        }
                        $v['value'] = $value;

                        $config = $v->toArray();
                        $config_value = array();
                        if (!empty($config_value_data_array[$v['id']])) {
                            $config_value['id'] = $config_value_data_array[$v['id']]['id'];
                        }
                        $config_value['shop_id'] = SHOP_ID;
                        $config_value['store_id'] = STORE_ID;
                        $config_value['config_id'] = $config['id'];
                        $config_value['value'] = $value;
                        $configValueAll[] = $config_value;
                    }
                }
                $this->config_value_model->allowField(true)->saveAll($configValueAll);
                try {
                    $this->refreshFile();
                    $this->apisuccess("更新成功");
                } catch (Exception $e) {
                    $this->apierror($e->getMessage());
                }
            }
            $this->apierror(__('Parameter %s can not be empty', ''));
        }
    }


    /**
     * 刷新配置文件
     */
    protected function refreshFile()
    {
        Cache::rm('ManystoreConfig:' . SHOP_ID);
    }



}