package com.goomood.tableConfig.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.goomood.common.core.domain.model.LoginUser;
import com.goomood.common.utils.SecurityUtils;
import com.goomood.common.utils.StringUtils;
import com.goomood.tableConfig.domain.UserTableConfig;
import com.goomood.tableConfig.mapper.UserTableConfigMapper;
import com.goomood.tableConfig.service.IUserTableConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 服务实现类
 *
 * @author zuoyou
 * @since 2025-03-03
 */
@Service
@RequiredArgsConstructor
public class UserTableConfigServiceImpl implements IUserTableConfigService {
    @Resource
    private UserTableConfigMapper userTableConfigMapper;

    @Override
    public UserTableConfig getUserTableConfig(UserTableConfig config) {
        String tableName = config.getTableName();
        if (StringUtils.isEmpty(tableName)) {
            throw new RuntimeException("表名不能为空！");
        }
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        config.setUserId(loginUser.getUserId().toString());
        UserTableConfig userTableConfig = userTableConfigMapper.selectOne(Wrappers.lambdaQuery(UserTableConfig.class)
                .eq(UserTableConfig::getUserId, config.getUserId())
                .eq(UserTableConfig::getTableName, config.getTableName()));
        return userTableConfig;
    }

    @Override
    public void saveUserTableConfig(UserTableConfig config) {
        userTableConfigMapper.insertOrUpdate(config);
    }

    @Override
    public void initUserTableConfig(UserTableConfig config) {
        UserTableConfig userTableConfig = this.getUserTableConfig(config);
        if (userTableConfig != null) {
            userTableConfigMapper.deleteById(userTableConfig.getId());
        }
    }
}
