package com.red.circle.other.infra.gateway.violation;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.domain.gateway.violation.ViolationRecordGateway;
import com.red.circle.other.domain.violation.ViolationRecord;
import com.red.circle.other.infra.database.rds.dao.violation.ViolationRecordDAO;
import com.red.circle.other.infra.database.rds.entity.violation.ViolationRecordEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 违规记录网关实现
 */
@Component
@RequiredArgsConstructor
public class ViolationRecordGatewayImpl implements ViolationRecordGateway {

    private final ViolationRecordDAO violationRecordDAO;

    @Override
    public Long save(ViolationRecord record) {
        ViolationRecordEntity entity = toEntity(record);
        entity.setBizNo(generateBizNo(record));
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        violationRecordDAO.insert(entity);
        return entity.getId();
    }

    @Override
    public PageResult<ViolationRecord> pageQuery(Integer targetType, String targetId, Integer violationType,
                                                 Integer operationType, Long operatorId, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<ViolationRecordEntity> wrapper = new LambdaQueryWrapper<>();
        
        if (targetType != null) {
            wrapper.eq(ViolationRecordEntity::getTargetType, targetType);
        }
        if (targetId != null) {
            wrapper.eq(ViolationRecordEntity::getTargetId, targetId);
        }
        if (violationType != null) {
            wrapper.eq(ViolationRecordEntity::getViolationType, violationType);
        }
        if (operationType != null) {
            wrapper.eq(ViolationRecordEntity::getOperationType, operationType);
        }
        
        wrapper.orderByDesc(ViolationRecordEntity::getCreateTime);
        
        IPage<ViolationRecordEntity> page = new Page<>(pageNum, pageSize);
        IPage<ViolationRecordEntity> result = violationRecordDAO.selectPage(page, wrapper);
        
        List<ViolationRecord> records = result.getRecords().stream()
                .map(this::toDomain)
                .collect(Collectors.toList());

        PageResult<ViolationRecord> pageResult = new PageResult<>();
        pageResult.setRecords(records);
        pageResult.setTotal(page.getTotal());
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());

        return pageResult;
    }

    /**
     * 生成业务单号
     */
    private String generateBizNo(ViolationRecord record) {
        return String.format("violation_%d_%s_%s",
                record.getTargetType(),
                record.getTargetId(),
                IdUtil.getSnowflakeNextIdStr());
    }

    /**
     * 领域对象转实体
     */
    private ViolationRecordEntity toEntity(ViolationRecord record) {
        ViolationRecordEntity entity = new ViolationRecordEntity();
        entity.setTargetType(record.getTargetType());
        entity.setTargetId(record.getTargetId());
        entity.setViolationType(record.getViolationType());
        entity.setOperationType(record.getOperationType());
        entity.setDescription(record.getDescription());
        entity.setScreenshotUrls(record.getScreenshotUrls() != null ? 
                JSON.toJSONString(record.getScreenshotUrls()) : null);
        entity.setOriginalContent(record.getOriginalContent());
        entity.setAdjustedContent(record.getAdjustedContent());
        entity.setOperatorId(record.getOperatorId());
        entity.setOperatorName(record.getOperatorName());
        entity.setStatus(1);
        return entity;
    }

    /**
     * 实体转领域对象
     */
    private ViolationRecord toDomain(ViolationRecordEntity entity) {
        return ViolationRecord.builder()
                .id(entity.getId())
                .bizNo(entity.getBizNo())
                .targetType(entity.getTargetType())
                .targetId(entity.getTargetId())
                .violationType(entity.getViolationType())
                .operationType(entity.getOperationType())
                .description(entity.getDescription())
                .screenshotUrls(entity.getScreenshotUrls())
                .originalContent(entity.getOriginalContent())
                .adjustedContent(entity.getAdjustedContent())
                .operatorId(entity.getOperatorId())
                .operatorName(entity.getOperatorName())
                .createTime(entity.getCreateTime())
                .build();
    }
}
