package com.yingpai.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yingpai.miniapp.domain.bo.AgreementConfigBo;
import com.yingpai.miniapp.domain.vo.AgreementConfigVo;
import com.yingpai.miniapp.service.IAgreementConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysConfig;
import org.dromara.system.mapper.SysConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 协议配置服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AgreementConfigServiceImpl implements IAgreementConfigService {

    private final SysConfigMapper sysConfigMapper;

    private static final String USER_AGREEMENT_KEY = "miniapp.user.agreement";
    private static final String PRIVACY_POLICY_KEY = "miniapp.privacy.policy";

    @Override
    public AgreementConfigVo getConfig() {
        AgreementConfigVo vo = new AgreementConfigVo();
        vo.setUserAgreement(getConfigString(USER_AGREEMENT_KEY));
        vo.setPrivacyPolicy(getConfigString(PRIVACY_POLICY_KEY));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateConfig(AgreementConfigBo bo) {
        if (bo.getUserAgreement() != null) {
            updateOrInsertConfig(USER_AGREEMENT_KEY, bo.getUserAgreement(), "用户协议内容");
        }
        if (bo.getPrivacyPolicy() != null) {
            updateOrInsertConfig(PRIVACY_POLICY_KEY, bo.getPrivacyPolicy(), "隐私政策内容");
        }
        return true;
    }

    private String getConfigString(String key) {
        List<SysConfig> list = sysConfigMapper.selectList(
            new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, key).last("LIMIT 1"));
        return !list.isEmpty() ? list.get(0).getConfigValue() : "";
    }

    private void updateOrInsertConfig(String key, String value, String name) {
        List<SysConfig> list = sysConfigMapper.selectList(
            new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, key).last("LIMIT 1"));

        if (!list.isEmpty()) {
            sysConfigMapper.update(null, new LambdaUpdateWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, key)
                .set(SysConfig::getConfigValue, value));
        } else {
            SysConfig config = new SysConfig();
            config.setConfigName(name);
            config.setConfigKey(key);
            config.setConfigValue(value);
            config.setConfigType("N");
            sysConfigMapper.insert(config);
        }
    }
}
