package org.dromara.zjk.controller;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.api.RemoteConfigService;
import org.dromara.zjk.domain.bo.ZjkExpertBo;
import org.dromara.zjk.domain.vo.ZjkExpertVo;
import org.dromara.zjk.service.IZjkExpertService;
import org.dromara.zjk.utils.EncryptionUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/zjk")
@Slf4j
public class ApiController {
    // 默认的密钥常量
    private static final String DEFAULT_SECRET_KEY = "k6psy7kafT%UaPd2";


    @DubboReference(timeout=5000)
    private final RemoteConfigService remoteConfigService;

    private final IZjkExpertService zjkExpertService;

    /**
     * 专家库数据获取
     * @param authorizationCode
     * @return
     */
    @PostMapping("/api/expert-data")
    public R<String> getEncryptedExpertData(@RequestHeader("Authorization") String authorizationCode) {
        try {
            // 获取密钥配置
            String secretKey = remoteConfigService.selectConfigByKey("api.secret.key");
            if (StringUtils.isEmpty(secretKey)) {
                secretKey = DEFAULT_SECRET_KEY;
            }

            // 验证授权码是否为空
            if (StringUtils.isEmpty(authorizationCode)) {
                log.warn("Authorization code is missing.");
                throw new ServiceException("授权码为空，禁止访问");
            }

            // 验证授权码是否匹配
            if (!authorizationCode.equals(secretKey)) {
                log.warn("Invalid authorization code: {}", authorizationCode);
                throw new ServiceException("授权码错误，禁止访问");
            }

            // 查询专家数据
            List<ZjkExpertVo> zjkExpertVoList = zjkExpertService.exportList(new ZjkExpertBo());

            if (zjkExpertVoList == null || zjkExpertVoList.isEmpty()) {
                log.info("无可返回的数据");
                return R.ok("无可返回的数据");
            }
            String data = JSON.toJSONString(zjkExpertVoList);
            // 数据加密
            String encryptedData = EncryptionUtil.encrypt(data, secretKey);
            return R.ok("操作成功",encryptedData);
        } catch (ServiceException e) {
            log.error("Service exception occurred: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("Unexpected error occurred", e);
            return R.fail("系统异常，请联系管理员");
        }
    }

    // 解密接口 (用于调试或者需要解密的地方)
    @PostMapping("/api/decrypt")
    public String decryptData(
        @RequestHeader("Authorization") String authorizationCode,
        @RequestBody String encryptedData) {
        try {
            // 从配置服务获取密钥
            String SECRET_KEY = remoteConfigService.selectConfigByKey("api.secret.key");
            if (StringUtils.isEmpty(SECRET_KEY)) {
                SECRET_KEY = DEFAULT_SECRET_KEY;
            }

            // 验证授权码
            if (!authorizationCode.equals(SECRET_KEY)) {
                throw new IllegalAccessException("Invalid authorization code");
            }

            // 解密数据
            String decryptedData = EncryptionUtil.decrypt(encryptedData, SECRET_KEY);
            return decryptedData;

        } catch (Exception e) {
            return "Error occurred: " + e.getMessage();
        }
    }

}
