<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\Config as ConfigModel;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Exception;
use support\think\Db;

/**
 * 系统设置
 */
class ConfigController extends Base
{
    /**
     * 不需要验证权限的方法
     * @var string[]
     */
    protected $noNeedAuth = ['get','check','testmail'];

    /**
     * 账户设置
     * @return Response
     * @throws Exception
     */
    public function index(): Response 
    { 

        $_list = ConfigModel::order('id asc')->select();
        $_list = $_list->toArray();
        $list = [];
        foreach($_list as $k=>$v){
            if(!isset($list[$v['group']])){
                $list[$v['group']] = [];
            }
            // if(in_array($v['type'] ,['radio','checkbox','select','selects'] ) && $v['content']){
            //     $firstLetter = substr($v['content'],0,1);
            //     if($firstLetter == '[' || $firstLetter == '{'){
            //         $arr = json_decode($v['content'],true);
            //     }else{
            //         $_content = explode("\n",$v['content']);
            //         $arr = [];
            //         foreach($_content as $k1=>$v1){
            //             $_v1 = explode('|',$v1);
            //             $arr[$_v1[0]]=$_v1[1];
            //         }
            //     }
            //     $v['content'] = $arr;
            // }
            $list[$v['group']][$v['name']] = $v;
        }
        //echo json_encode($list,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return view('config/index',[
            'configlist'    =>  $list,
            'typeList'  => [
                'string'        => '字符串',
                'password'      => __('密码'),
                'text'          => __('文本'),
                'editor'        => __('编辑器'),
                'number'        => __('数字'),
                'date'          => __('日期'),
                'time'          => __('时间'),
                'datetime'      => __('日期时间'),
                'datetimerange' => __('日期时间区间'),
                'select'        => __('下拉列表'),
                'selects'       => __('多选下拉列表'),
                'image'         => __('图片'),
                'images'        => __('图片(多)'),
                'file'          => __('文件'),
                'files'         => __('文件(多)'),
                'switch'        => __('开关'),
                'checkbox'      => __('复选'),
                'radio'         => __('单选'),
                'city'          => __('城市地区'),
                'selectpage'    => __('关联表'),
                'selectpages'   => __('关联表(多选)'),
                'array'         => __('数组'),
                'custom'        => __('自定义'),
            ],
            'ruleList' => [
                'required' => '必选',
                'digits'   => '数字',
                'letters'  => '字母',
                'date'     => '日期',
                'time'     => '时间',
                'email'    => '邮箱',
                'url'      => '网址',
                'qq'       => 'QQ号',
                'IDcard'   => '身份证',
                'tel'      => '座机电话',
                'mobile'   => '手机号',
                'zipcode'  => '邮编',
                'chinese'  => '中文',
                'username' => '用户名',
                'password' => '密码'
            ]
        ]);
    }

    /**
     * 更改
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        $list = ConfigModel::where(1,1)->select();
        $post = $request->post();
        $saveData = [];
        /**
         * @var ConfigModel $v
         */
        foreach ($list as $k => $v) {
            if(isset($post[$v['name']]) ){
                $value = $post[$v['name']];
                // if($v['type'] == 'selects'){
                //     $value = implode(',',$value);
                // }
                $saveData[] = [
                    "id"=>$v['id'],
                    "type"=>$v['type'],
                    "name"=>$v['name'],
                    'value'=> $value
                ];
            }
        }
        $Config = new ConfigModel;
        $Config->saveAll($saveData);
        $this->buildcache();
        return $this->success('保存成功');
    }
    /**
     * 更改
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        $post = $request->post('row');
        Db::startTrans();
        try {
            // if($post['type'] == 'selects'){
            //     $post['value'] = implode(',',$post['value']);
            // }
            $user = ConfigModel::create($post);
            Db::commit();
            $this->buildcache();
            return $this->success('保存成功');
        } catch (Exception $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }
    protected function buildcache(){
        //缓存
        $_list = ConfigModel::Field('name,value,type')->order('id asc')->select();
        $_list = $_list->toArray();
        $list = [];
        foreach($_list as $k=>$v){
            if(in_array($v['type'] ,['array']) && !is_array($v['value'])){
                $v['value'] = json_decode($v['value'], true);
            }
            if(in_array($v['type'] ,['selects']) && !is_array($v['value'])){
                $v['value'] = explode(',',$v['value']??'');
            }
            $list[$v['name']] = $v['value'];
        }

        $fn = base_path(false) . '/config/site.php';
        file_put_contents($fn, "<?php \n return ".var_export($list,true).';');
    }

    /**
     * 颜色检查
     * @param string $color
     * @return string
     * @throws BusinessException
     */
    protected function filterColor(string $color): string
    {
        if (!preg_match('/\#[a-zA-Z]6/', $color)) {
            throw new BusinessException('参数错误');
        }
        return $color;
    }
    /**
     * 配置名称检查
     * @param string $color
     * @return string
     * @throws BusinessException
     */

    function check(){
        $param = Request()->post('param');
        $name = Request()->get('name');
        if(ConfigModel::where($name, $param)->count('id')>0){
            return $this->fail("已被占用");
        }else{
            return $this->success();
        }
    }
    /**
     * 测试邮件
     * @return Response
     */
    function testmail(){
        $config = Request()->post();
        addJob([
            'email'     =>  $config['test_mail_address'],
            'title' =>  '这是一封来自'.config('site.name').'的邮件',
            'body'  =>  '这是一封来自'.config('site.name').'的校验邮件,用于校验邮件配置是否正常!',
            'config'    =>  [
                "mail_from"=>$config['mail_from'],
                "mail_smtp_host"=>$config['mail_smtp_host'],
                "mail_smtp_user"=>$config['mail_smtp_user'],
                "mail_smtp_pass"=>$config['mail_smtp_pass'],
                "mail_smtp_port"=>$config['mail_smtp_port'],
                "mail_verify_type"=>$config['mail_verify_type'],
            ]
        ],'Email');
        return $this->success($config['test_mail_address']."邮件已经发送");
    }

}
