<?php

namespace app\admin\service\sys_manage;

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

class ConfigService
{
    public static function configList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $keyword = $request->get('keyword', '');

        $rows = SysConfig::select('*')
            ->when($keyword != '', function ($query) use ($keyword) {
                $query->where('config_name', 'like', '%' . $keyword . '%');
            })
            ->orderBy('config_sort', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        $total = SysConfig::when($keyword != '', function ($query) use ($keyword) {
            $query->where('config_name', 'like', '%' . $keyword . '%');
        })->count();

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    public static function configInfo($id)
    {
        $config = SysConfig::where('config_id', $id)->first();
        if (!$config) {
            return json_fail('配置不存在');
        }

        return json_success('', $config->toArray());
    }

    /**
     * @Desc 添加配置
     * @Author Gorden
     * @Date 2024/2/22 15:57
     *
     * @param $params
     * @return \support\Response
     */
    public static function addConfig($params)
    {
        try {
            $data = [
                'config_status' => $params['config_status'],
                'config_category' => $params['config_category'],
                'config_key' => $params['config_key'],
                'config_name' => $params['config_name'],
                'config_alias' => $params['config_alias'],
                'config_value' => $params['config_value'],
                'config_value_json' => !empty($params['config_value_json']) ? $params['config_value_json'] : '{}',
                'config_sort' => $params['config_sort'] ?? 0,
                'config_groupby' => $params['config_groupby'] ?? '',
                'config_remark' => isset($params['config_remark']) ? format_string($params['config_remark']) : '',
                'config_extend_json' => !empty($params['config_extend_json']) ? $params['config_extend_json'] : '{}',
                'config_addtimes' => time()
            ];

            SysConfig::insert($data);
        } catch (\Exception $e) {
            return json_fail('添加配置失败');
        }

        return json_success('添加配置成功');
    }

    /**
     * @Desc 修改配置
     * @Author Gorden
     * @Date 2024/2/22 16:24
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateConfig($id, $params)
    {
        try {
            $data = [
                'config_status' => $params['config_status'],
                'config_category' => $params['config_category'],
                'config_key' => $params['config_key'],
                'config_name' => $params['config_name'],
                'config_alias' => $params['config_alias'],
                'config_value' => $params['config_value'],
                'config_value_json' => !empty($params['config_value_json']) ? $params['config_value_json'] : '{}',
                'config_sort' => $params['config_sort'],
                'config_groupby' => $params['config_groupby'],
                'config_remark' => format_string($params['config_remark']),
                'config_extend_json' => !empty($params['config_extend_json']) ? $params['config_extend_json'] : '{}',
            ];
            SysConfig::where('config_id', $id)->update($data);
        } catch (\Exception $e) {
            return json_fail('修改配置失败');
        }

        return json_success('修改配置成功');
    }

    /**
     * @Desc 配置修改
     * @Author Gorden
     * @Date 2024/2/22 16:38
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateStatus($id, $params)
    {
        try {
            SysConfig::where('config_id', $id)->update(['config_status' => $params['config_status']]);
        } catch (\Exception $e) {
            return json_fail('配置状态修改失败');
        }

        return json_success('配置状态修改成功');
    }

    /**
     * @Desc 删除字段
     * @Author Gorden
     * @Date 2024/2/22 15:08
     *
     * @param $id
     * @return \support\Response
     */
    public static function delConfig(Request $request)
    {
        $ids = $request->post('config_id');
        if (!$ids) {
            return json_fail("数据错误");
        }
        try {
            if (is_array($ids)) {
                SysConfig::whereIn('config_id', $ids)->delete();
            } else {
                SysConfig::where('config_id', $ids)->delete();
            }
        } catch (\Exception $e) {
            return json_fail('配置删除失败');
        }

        return json_success('配置删除成功');
    }

    /**
     * @Desc APP 参数读取
     * @Author Gorden
     * @Date 2024/4/15 13:54
     *
     * @param $type
     * @return \support\Response|void
     */
    public static function getParams($type)
    {
        if ($type == 'sys') {
            $res = SysConfig::where('config_key', 'app-name')
                ->orWhere('config_key', 'app-version')
                ->orWhere('config_key', 'app-common-css')
                ->orWhere('config_key', 'app-license')
                ->orWhere('config_key', 'app-hide')
                ->get()
                ->toArray();
            $data = [];
            foreach ($res as $item) {
                $key = str_replace('-', '_', $item['config_key']);
                $data[$key] = $item['config_value'];
            }
            return json_success('', $data);
        } else {
            $res = SysConfig::where('config_key', $type)->select('config_status', 'config_value_json', 'config_key', 'config_value')->first();
            if (!empty($res)) {
                $res = $res->toArray();
                $valueJson = json_decode($res['config_value_json'], true);
                if (!in_array($res['config_key'], ['app-menu-shortcut', 'app-menu-navigation', 'app-menu-footer'])) {
                    $data['status'] = $res['config_status'];
                    $data['config_name'] = $res['config_value'];
                    foreach ($valueJson as $key => $item) {
                        $key = str_replace('-', '_', $key);
                        $data[$key] = $item;
                    }
                } else {
                    $data = $valueJson;
                }

                return json_success('', $data);
            }
        }
    }

    public static function paramsSave(Request $request, $type)
    {
        $params = $request->post();
        try {
            Db::beginTransaction();
            if ($params['type'] == 'sys') {
                SysConfig::where('config_key', 'app-name')->update(['config_value' => $params['app_name']]);
                SysConfig::where('config_key', 'app-version')->update(['config_value' => $params['app_version']]);
                SysConfig::where('config_key', 'app-common-css')->update(['config_value' => $params['app_common_css']]);
                SysConfig::where('config_key', 'app-license')->update(['config_value' => $params['app_license']]);
                SysConfig::where('config_key', 'app-hide')->update(['config_value' => $params['app_hide']]);
            } else if (!in_array($params['type'], ['shortcutMenu', 'navigationMenu', 'footerMenu'])) {
                $data = [
                    'config_status' => $params['status'],
                    'config_value' => $params['config_name'],
                ];
                unset($params['status'], $params['type'], $params['config_name']);
                $data['config_value_json'] = json_encode($params);

                SysConfig::where('config_key', $type)->update($data);
            } else {
                foreach ($params['config_value_json'] as $item) {
                    unset($item['isSet']);
                    $data['config_value_json'][] = $item;
                }
                SysConfig::where('config_key', $type)->update($data);
            }

            Db::commit();

            return json_success('success');
        } catch (\Exception $e) {
            Db::rollBack();
            return json_fail('保存失败');
        }
    }
}