package cd.casic.module.terminal.service.impl;


import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import cd.casic.module.machine.dal.dataobject.SecretKeyDO;
import cd.casic.module.machine.dal.mysql.MachineInfoMapper;
import cd.casic.module.machine.dal.mysql.SecretKeyMapper;
import cd.casic.module.machine.enums.AuthenticationType;
import cd.casic.module.machine.utils.CryptogramUtil;
import cd.casic.module.terminal.common.ErrorMessage;
import cd.casic.module.terminal.controller.dto.TerminalConnectDTO;
import cd.casic.module.terminal.enums.*;
import cd.casic.module.terminal.host.config.model.HostSshConfigModel;
import cd.casic.module.terminal.host.extra.model.HostSshExtraModel;
import cd.casic.module.terminal.service.HostConnectService;
import cn.orionsec.kit.lang.utils.Valid;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;

/**
 * 主机连接服务实现
 *
 * @author Jiahang Li
 * @version 1.0.0
 * @since 2024/10/12 23:58
 */
@Slf4j
@Service
public class HostConnectServiceImpl implements HostConnectService {


    @Autowired
    private MachineInfoMapper machineInfoMapper;

    @Autowired
    private SecretKeyMapper secretKeyMapper;



    private final HostSshConfigModel CONFIG = HostSshConfigModel.builder().connectTimeout(10000).charset("UTF-8").fileContentCharset("UTF-8").fileNameCharset("UTF-8").build();


    @Override
    public TerminalConnectDTO getSshConnectInfo(Long hostId) {
        log.info("HostConnectService.getSshConnectInfo-withHost hostId: {}", hostId);
        // 查询主机
        MachineInfoDO host = machineInfoMapper.selectById(hostId);
        // 获取配置
        return this.getHostConnectInfo(host, CONFIG, null);
    }


    @Override
    public TerminalConnectDTO getSshConnectInfo(Long hostId, Long userId) {
        // 查询主机
        MachineInfoDO host = machineInfoMapper.selectById(hostId);
        Valid.notNull(host, ErrorMessage.HOST_ABSENT);
        // 获取配置
        return this.getSshConnectInfo(host, userId);
    }


    @Override
    public TerminalConnectDTO getSshConnectInfo(MachineInfoDO host, Long userId) {
        Long hostId = host.getId();
        log.info("HostConnectService.getSshConnectInfo hostId: {}, userId: {}", hostId, userId);
        // 验证主机是否有权限
       /* List<Long> hostIdList = assetAuthorizedDataService.getUserAuthorizedHostId(userId);
        Valid.isTrue(hostIdList.contains(hostId),
                ErrorMessage.ANY_NO_PERMISSION,
                DataPermissionTypeEnum.HOST_GROUP.getPermissionName());*/
        // 获取主机配置
        CONFIG.setPort(host.getSshPort());
        CONFIG.setUsername(host.getUsername());
        if (host.getAuthenticationType().equals(1)){
            CONFIG.setAuthType(HostSshAuthTypeEnum.PASSWORD.name());
            CONFIG.setPassword(CryptogramUtil.doDecrypt(host.getPassword()));
        }else {
            CONFIG.setKeyId(host.getSecretKeyId());
        }
        Valid.notNull(CONFIG, ErrorMessage.CONFIG_ABSENT);
        // 获取连接配置
        return this.getHostConnectInfo(host, CONFIG, null);
    }

    /**
     * 获取主机 SSH 连接配置
     *
     * @param host   host
     * @param config config
     * @param extra  extra
     * @return session
     */
    private TerminalConnectDTO getHostConnectInfo(MachineInfoDO host,
                                                  HostSshConfigModel config,
                                                  HostSshExtraModel extra) {
        // 填充认证信息
        TerminalConnectDTO conn = new TerminalConnectDTO();
        conn.setOsType(host.getMachineInfoType()==1? "LINUX":"WINDOWS");
//        conn.setArchType(host.getArchType());
        conn.setHostId(host.getId());
        conn.setHostName(host.getName());
//        conn.setHostCode(host.getCode());
        conn.setHostAddress(host.getHostIp());
        conn.setHostPort(host.getSshPort());
        conn.setTimeout(config.getConnectTimeout());
        conn.setCharset(config.getCharset());
        conn.setFileNameCharset(config.getFileNameCharset());
        conn.setFileContentCharset(config.getFileContentCharset());

        // 获取自定义认证方式
        HostExtraSshAuthTypeEnum extraAuthType = Optional.ofNullable(extra)
                .map(HostSshExtraModel::getAuthType)
                .map(HostExtraSshAuthTypeEnum::of)
                .orElse(null);
        if (HostExtraSshAuthTypeEnum.CUSTOM_KEY.equals(extraAuthType)) {
            // 自定义密钥
            config.setAuthType(HostSshAuthTypeEnum.KEY.name());
            config.setKeyId(extra.getKeyId());
            if (extra.getUsername() != null) {
                config.setUsername(extra.getUsername());
            }
        } else if (HostExtraSshAuthTypeEnum.CUSTOM_IDENTITY.equals(extraAuthType)) {
            // 自定义身份
            config.setAuthType(HostSshAuthTypeEnum.IDENTITY.name());
            config.setIdentityId(extra.getIdentityId());
        }
        // 身份认证
        HostSshAuthTypeEnum authType = AuthenticationType.of(host.getAuthenticationType()).name().equals(AuthenticationType.SECRET_KEY.name()) ? HostSshAuthTypeEnum.KEY : HostSshAuthTypeEnum.PASSWORD;
        if (HostSshAuthTypeEnum.IDENTITY.equals(authType)) {
            // 身份认证
            Valid.notNull(config.getIdentityId(), ErrorMessage.IDENTITY_ABSENT);
//            HostIdentityDO identity = hostIdentityDAO.selectById(config.getIdentityId());
            Valid.notNull(host, ErrorMessage.IDENTITY_ABSENT);
            config.setUsername(host.getUsername());
            HostIdentityTypeEnum identityType = HostIdentityTypeEnum.of(config.getAuthType());
            if (HostIdentityTypeEnum.PASSWORD.equals(identityType)) {
                // 密码类型
                authType = HostSshAuthTypeEnum.PASSWORD;
                config.setPassword(host.getPassword());
            } else if (HostIdentityTypeEnum.KEY.equals(identityType)) {
                // 密钥类型
                authType = HostSshAuthTypeEnum.KEY;
                config.setKeyId(host.getSecretKeyId());
            }
        }

        // 填充认证信息
        conn.setUsername(host.getUsername());
        if (HostSshAuthTypeEnum.PASSWORD.equals(authType)) {
            // 密码认证
            conn.setPassword(host.getPassword());
        } else if (HostSshAuthTypeEnum.KEY.equals(authType)) {
            // 密钥认证
            Long keyId = host.getSecretKeyId();
            Valid.notNull(keyId, ErrorMessage.KEY_ABSENT);
            SecretKeyDO key = secretKeyMapper.selectById(keyId);
            Valid.notNull(key, ErrorMessage.KEY_ABSENT);
            conn.setKeyId(keyId);
            conn.setPublicKey(key.getPublicKey());
            conn.setPrivateKey(key.getPrivateKey());
            conn.setPrivateKeyPassword(key.getPassword());
        }
        return conn;
    }

}
