package com.cool.modules.dingtalk.service.impl;

import com.cool.core.base.BaseServiceImpl;
import com.cool.modules.dingtalk.entity.DingtalkConfigEntity;
import com.cool.modules.dingtalk.mapper.DingtalkConfigMapper;
import com.cool.modules.dingtalk.service.DingtalkConfigService;
import com.cool.modules.dingtalk.util.DingtalkApiUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 钉钉配置服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DingtalkConfigServiceImpl extends BaseServiceImpl<DingtalkConfigMapper, DingtalkConfigEntity>
        implements DingtalkConfigService {

    private final DingtalkApiUtil dingtalkApiUtil;

    @Override
    public DingtalkConfigEntity getConfig() {
        log.info("【钉钉配置】获取钉钉配置");

        QueryWrapper qw = QueryWrapper.create()
                .eq(DingtalkConfigEntity::getStatus, 1)
                .orderBy(DingtalkConfigEntity::getId, true)
                .limit(1);

        DingtalkConfigEntity config = this.getOne(qw);

        if (config != null) {
            log.info("【钉钉配置】配置获取成功, ID: {}, AppKey: {}", config.getId(), config.getAppKey());
        } else {
            log.warn("【钉钉配置】未找到启用的配置");
        }

        return config;
    }

    @Override
    public boolean validateConfig(String appKey, String appSecret) {
        log.info("【钉钉配置】验证配置有效性, AppKey: {}", appKey);

        try {
            // 临时设置配置并尝试获取AccessToken
            dingtalkApiUtil.setConfig(appKey, appSecret);
            String accessToken = dingtalkApiUtil.getAccessToken();

            if (accessToken != null && !accessToken.isEmpty()) {
                log.info("【钉钉配置】配置验证成功, AccessToken: {}", accessToken.substring(0, Math.min(20, accessToken.length())) + "...");
                return true;
            } else {
                log.error("【钉钉配置】配置验证失败, AccessToken为空");
                return false;
            }
        } catch (Exception e) {
            log.error("【钉钉配置】配置验证异常", e);
            return false;
        }
    }

    @Override
    public DingtalkConfigEntity saveOrUpdateConfig(DingtalkConfigEntity entity) {
        log.info("【钉钉配置】保存或更新配置, AppKey: {}", entity.getAppKey());

        // 查询是否已存在配置
        DingtalkConfigEntity existingConfig = getConfig();

        if (existingConfig != null) {
            // 更新现有配置
            entity.setId(existingConfig.getId());
            this.updateById(entity);
            log.info("【钉钉配置】更新配置成功, ID: {}", entity.getId());
        } else {
            // 新增配置
            this.save(entity);
            log.info("【钉钉配置】新增配置成功, ID: {}", entity.getId());
        }

        // 更新DingtalkApiUtil中的配置
        dingtalkApiUtil.setConfig(entity.getAppKey(), entity.getAppSecret());

        return entity;
    }
}
