<?php

namespace app\admin\controller\sys_manage;

use app\model\SysConfig;
use support\Request;

class GreenChannelController{
    public function select(){
        $config = SysConfig::where('config_key','app-system-hospital')->first();
        if(!$config){
            return json_fail("数据异常");
        }

        $list = json_decode($config->config_value_json,true);
        $data = [];
        foreach($list as $key => $item){
            $item['hospital'] = $key;
            $data[] = $item;
        }

        return json_success('',$data);
    }

    public function insert(Request $request){
        $config = SysConfig::where('config_key','app-system-hospital')->first();
        if(!$config){
            return json_fail("数据异常");
        }
        $params = $request->post();

        $list = json_decode($config->config_value_json,true);
        if(isset($list[$params['hospital']])){
            return json_fail('医院已存在');
        }
        $data[$params['hospital']] = [
            'city' => $params['city'] ?? '',
            'agent'=>'',
            'dates'=>''
        ];
        $list = $data + $list;//array_merge($data,$list);

        try{
            SysConfig::where('config_key','app-system-hospital')->update(['config_value_json'=>json_encode($list)]);

            return json_success('添加医院成功');
        }catch(\Exception $e){
            return json_fail("添加医院失败");
        }
    }

    public function update(Request $request){
        $config = SysConfig::where('config_key','app-system-hospital')->first();
        if(!$config){
            return json_fail("数据异常");
        }
        $params = $request->post();

        $list = json_decode($config->config_value_json,true);
        if(isset($list[$params['hospital']])){
            return json_fail('医院已存在');
        }
        $data[$params['hospital']] = [
            'city' => $params['city'] ?? '',
            'agent'=>'',
            'dates'=>''
        ];
        array_unshift($list,$data);

        dump($list);
    }

    public function delete(Request $request){
        $hospital = $request->post('hospital','');
        if(!$hospital){
            return json_fail("参数异常");
        }

        $config = SysConfig::where('config_key','app-system-hospital')->first();
        if(!$config){
            return json_fail("数据异常");
        }
        $params = $request->post();

        $list = json_decode($config->config_value_json,true);
        if (!isset($list[$hospital])){
            return json_fail('医院不存在');
        }

        unset($list[$hospital]);
        
        try{
            SysConfig::where('config_key','app-system-hospital')->update(['config_value_json'=>json_encode($list)]);

            return json_success('删除医院成功');
        }catch(\Exception $e){
            return json_fail("删除医院失败");
        }
    }
}
