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

import cd.casic.module.terminal.common.OperatorLogs;
import cd.casic.module.terminal.convert.TerminalConnectLogConvert;
import cd.casic.module.terminal.dal.dataobject.TerminalConnectLogDO;
import cd.casic.module.terminal.dal.mysql.TerminalConnectLogMapper;
import cd.casic.module.terminal.enums.TerminalConnectTypeEnum;
import cd.casic.module.terminal.host.terminal.enums.TerminalConnectStatusEnum;
import cd.casic.module.terminal.host.terminal.manager.TerminalManager;
import cd.casic.module.terminal.host.terminal.model.request.host.TerminalConnectLogCreateRequest;
import cd.casic.module.terminal.service.TerminalConnectLogService;
import cn.orionsec.kit.lang.constant.Const;
import cn.orionsec.kit.lang.utils.collect.Lists;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * 终端连接日志 服务实现类
 *
 * @author Yuru Pu
 * @version 1.0
 * @since 2025/7/8 14:17
 */
@Slf4j
@Service
public class TerminalConnectLogServiceImpl implements TerminalConnectLogService {

    @Autowired
    private TerminalConnectLogMapper terminalConnectLogDAO;


    @Override
    public TerminalConnectLogDO create(TerminalConnectTypeEnum type, TerminalConnectLogCreateRequest request) {
        TerminalConnectLogDO record = TerminalConnectLogConvert.MAPPER.to(request);
        record.setType(type.name());
        String status = request.getStatus();
        record.setStatus(status);
        record.setStartTime(new Date());
        record.setExtraInfo(JSON.toJSONString(request.getExtra()));
        // 失败直接设置结束时间
        if (TerminalConnectStatusEnum.FAILED.name().equals(status)) {
            record.setEndTime(new Date());
        }
        terminalConnectLogDAO.insert(record);
        return record;
    }


    @Override
    public Integer updateStatusById(Long id, TerminalConnectStatusEnum status, Map<String, Object> partial) {
        log.info("TerminalConnectLogService-updateStatusById start id: {}, status: {}", id, status);
        // 查询
        LambdaQueryWrapper<TerminalConnectLogDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TerminalConnectLogDO::getId, id).orderByDesc(TerminalConnectLogDO::getId);
        TerminalConnectLogDO record = terminalConnectLogDAO.selectOne(queryWrapper);
        /*TerminalConnectLogDO record = terminalConnectLogDAO.of()
                .createWrapper()
                .eq(TerminalConnectLogDO::getId, id)
                .orderByDesc(TerminalConnectLogDO::getId)
                .then()
                .getOne();*/
        if (record == null) {
            log.info("TerminalConnectLogService-updateStatusById no record id: {}", id);
            return Const.N_0;
        }
        return this.updateStatus(record, status, partial);
    }

    /**
     * 更新状态
     *
     * @param record  record
     * @param status  status
     * @param partial partial
     * @return effect
     */
    private int updateStatus(TerminalConnectLogDO record, TerminalConnectStatusEnum status, Map<String, Object> partial) {
        // 更新
        TerminalConnectLogDO update = new TerminalConnectLogDO();
        update.setId(record.getId());
        update.setStatus(status.name());
        update.setEndTime(new Date());
        if (partial != null) {
            Map<String, Object> extra = JSON.parseObject(record.getExtraInfo());
            if (extra == null) {
                extra = partial;
            } else {
                extra.putAll(partial);
            }
            update.setExtraInfo(JSON.toJSONString(extra));
        }
        return terminalConnectLogDAO.updateById(update);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteTerminalConnectLog(List<Long> idList) {
        log.info("TerminalConnectLogService.deleteTerminalConnectLog start {}", JSON.toJSONString(idList));
        if (Lists.isEmpty(idList)) {
            OperatorLogs.add(OperatorLogs.COUNT, Const.N_0);
            return Const.N_0;
        }
        // 删除日志表
        int effect = terminalConnectLogDAO.deleteBatchIds(idList);
        log.info("TerminalConnectLogService.deleteTerminalConnectLog finish {}", effect);
        // 设置日志参数
        OperatorLogs.add(OperatorLogs.COUNT, effect);
        return effect;
    }

}
