<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\app\logic\system;

use plugin\saiadmin\app\cache\ConfigCache;
use plugin\saiadmin\app\model\system\SystemConfigGroup;
use plugin\saiadmin\basic\think\BaseLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\app\model\system\SystemConfig;
use support\think\Db;

/**
 * 参数配置分组逻辑层
 */
class SystemConfigGroupLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SystemConfigGroup();
    }

    /**
     * 删除配置信息
     */
    public function destroy($ids): bool
    {
        $id = $ids[0];
        $model = $this->model->where('id', $id)->findOrEmpty();
        if ($model->isEmpty()) {
            throw new ApiException('Config data not found');
        }
        if (in_array(intval($id), [1, 2, 3])) {
            throw new ApiException('System default group cannot be deleted');
        }
        Db::startTrans();
        try {
            // 删除配置组
            $model->delete();
            // 删除配置组数据
            $typeIds = SystemConfig::where('group_id', $id)->column('id');
            SystemConfig::destroy($typeIds);
            ConfigCache::clearConfig($model->code);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ApiException('Delete data error, please check');
        }
    }
}
