package com.xunhong.erp.turbo.infra.infrastructure.gateway;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xunhong.erp.turbo.api.infra.dto.cmd.SettingUpdateCmd;
import com.xunhong.erp.turbo.api.infra.dto.qry.SettingShowQry;
import com.xunhong.erp.turbo.infra.domain.entity.Setting;
import com.xunhong.erp.turbo.infra.domain.gateway.SettingGateway;
import com.xunhong.erp.turbo.infra.infrastructure.convert.SettingConvert;
import com.xunhong.erp.turbo.infra.infrastructure.entity.SettingDO;
import com.xunhong.erp.turbo.infra.infrastructure.mapper.SettingMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Objects;

/**
 * @author shenyifei
 */
@Repository
@RequiredArgsConstructor
public class SettingGatewayImpl implements SettingGateway {
	private final SettingMapper settingMapper;
	private final SettingConvert settingConvert;

	@Override
	public Setting update(SettingUpdateCmd settingUpdateCmd) {
		// 判断是否存在当前配置
		LambdaQueryWrapper<SettingDO> queryWrapper = Wrappers.lambdaQuery(SettingDO.class);
		queryWrapper.eq(Objects.nonNull(settingUpdateCmd.getSettingKey()), SettingDO::getSettingKey, settingUpdateCmd.getSettingKey());
		SettingDO settingDO = settingMapper.selectOne(queryWrapper);

		if (Objects.isNull(settingDO)) {
			settingDO = settingConvert.toSettingDO(settingUpdateCmd);
			settingMapper.insert(settingDO);
		} else {
			settingConvert.toSettingDO(settingDO, settingUpdateCmd);
			settingMapper.updateById(settingDO);
		}

		return settingConvert.toSetting(settingDO);
	}

	@Override
	public Setting show(SettingShowQry settingShowQry) {
		LambdaQueryWrapper<SettingDO> queryWrapper = Wrappers.lambdaQuery(SettingDO.class);
		queryWrapper.eq(Objects.nonNull(settingShowQry.getSettingKey()), SettingDO::getSettingKey, settingShowQry.getSettingKey());
		queryWrapper.last("limit 1");

		SettingDO settingDO = settingMapper.selectOne(queryWrapper);
		return settingConvert.toSetting(settingDO);
	}
}

