package org.hzhub.workflow.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.common.core.exception.ServiceException;
import org.hzhub.common.redis.utils.RedisUtils;
import org.hzhub.workflow.domain.WecomTenantConfig;
import org.hzhub.workflow.domain.bo.WecomTenantConfigBo;
import org.hzhub.workflow.domain.vo.WecomTenantConfigVo;
import org.hzhub.workflow.mapper.WecomTenantConfigMapper;
import org.hzhub.workflow.service.IWecomTenantConfigService;
import org.hzhub.workflow.wecom.WecomConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信租户配置服务实现
 *
 * @author hzhub
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WecomTenantConfigServiceImpl implements IWecomTenantConfigService {

    private static final String CACHE_KEY_PREFIX = "wecom:tenant:";

    private final WecomTenantConfigMapper configMapper;
    private final WecomConfig wecomConfig;

    @Override
    @Cacheable(cacheNames = "wecom_tenant_config", key = "'current'")
    public WecomTenantConfigVo getByCurrentTenant() {
        WecomTenantConfig config = configMapper.selectOne(new LambdaQueryWrapper<WecomTenantConfig>().last("LIMIT 1"));
        if (config == null) {
            return null;
        }
        WecomTenantConfigVo vo = new WecomTenantConfigVo();
        vo.setId(config.getId());
        vo.setCorpid(config.getCorpid());
        vo.setCorpsecret(config.getCorpsecret());
        vo.setAgentId(config.getAgentId());
        vo.setCallbackToken(config.getCallbackToken());
        vo.setCallbackAesKey(config.getCallbackAesKey());
        vo.setEnabled(config.getEnabled());
        vo.setRemark(config.getRemark());
        return vo;
    }

    @Override
    @CacheEvict(cacheNames = "wecom_tenant_config", allEntries = true)
    public void saveOrUpdate(WecomTenantConfigBo bo) {
        WecomTenantConfig existing = configMapper.selectOne(new LambdaQueryWrapper<WecomTenantConfig>().last("LIMIT 1"));
        WecomTenantConfig entity = new WecomTenantConfig();
        entity.setCorpid(bo.getCorpid());
        entity.setCorpsecret(bo.getCorpsecret());
        entity.setAgentId(bo.getAgentId());
        entity.setCallbackToken(bo.getCallbackToken());
        entity.setCallbackAesKey(bo.getCallbackAesKey());
        entity.setEnabled(bo.getEnabled() != null ? bo.getEnabled() : "0");
        entity.setRemark(bo.getRemark());

        if (existing != null) {
            entity.setId(existing.getId());
            configMapper.updateById(entity);
        } else {
            configMapper.insert(entity);
        }
        // 清除 access_token 缓存（租户维度）
        RedisUtils.deleteObject("wecom_access_token:" + bo.getCorpid());
    }

    @Override
    public String testConnection(String corpid, String corpsecret) {
        if (corpid == null || corpsecret == null) {
            return "企业ID和应用密钥不能为空";
        }
        String url = wecomConfig.getApiBaseUrl() + "/cgi-bin/gettoken";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", corpid);
        params.put("corpsecret", corpsecret);

        try {
            String resp = HttpUtil.get(url, params);
            var json = JSONUtil.parseObj(resp);
            int errcode = json.getInt("errcode", -1);
            if (errcode == 0) {
                return "连接成功";
            }
            return "连接失败: " + json.getStr("errmsg");
        } catch (Exception e) {
            return "连接异常: " + e.getMessage();
        }
    }

    @Override
    public String getCorpId() {
        WecomTenantConfigVo config = getByCurrentTenant();
        if (config == null || config.getCorpid() == null) {
            throw new ServiceException("未配置企业微信企业ID，请先在审批页设置企业微信配置");
        }
        return config.getCorpid();
    }

    @Override
    public String getCorpSecret() {
        WecomTenantConfigVo config = getByCurrentTenant();
        if (config == null || config.getCorpsecret() == null) {
            throw new ServiceException("未配置企业微信应用密钥，请先在审批页设置企业微信配置");
        }
        return config.getCorpsecret();
    }

    @Override
    public String getAgentId() {
        WecomTenantConfigVo config = getByCurrentTenant();
        if (config == null || config.getAgentId() == null) {
            throw new ServiceException("未配置企业微信应用AgentID，请先在审批页设置企业微信配置");
        }
        return config.getAgentId();
    }
}
