package com.ycwl.basic.puzzle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ycwl.basic.puzzle.dto.PuzzleFillRuleDTO;
import com.ycwl.basic.puzzle.dto.PuzzleFillRuleItemDTO;
import com.ycwl.basic.puzzle.dto.PuzzleFillRuleSaveRequest;
import com.ycwl.basic.puzzle.entity.PuzzleFillRuleEntity;
import com.ycwl.basic.puzzle.entity.PuzzleFillRuleItemEntity;
import com.ycwl.basic.puzzle.mapper.PuzzleFillRuleItemMapper;
import com.ycwl.basic.puzzle.mapper.PuzzleFillRuleMapper;
import com.ycwl.basic.puzzle.service.IPuzzleFillRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拼图填充规则服务实现
 */
@Slf4j
@Service
public class PuzzleFillRuleServiceImpl implements IPuzzleFillRuleService {

    @Autowired
    private PuzzleFillRuleMapper ruleMapper;

    @Autowired
    private PuzzleFillRuleItemMapper itemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(PuzzleFillRuleSaveRequest request) {
        // 1. 保存主规则
        PuzzleFillRuleEntity ruleEntity = new PuzzleFillRuleEntity();
        BeanUtils.copyProperties(request, ruleEntity);
        ruleMapper.insert(ruleEntity);

        Long ruleId = ruleEntity.getId();
        log.info("创建填充规则成功, ruleId={}, ruleName={}", ruleId, request.getRuleName());

        // 2. 批量保存明细
        if (request.getItems() != null && !request.getItems().isEmpty()) {
            List<PuzzleFillRuleItemEntity> itemEntities = request.getItems().stream()
                    .map(dto -> {
                        PuzzleFillRuleItemEntity entity = new PuzzleFillRuleItemEntity();
                        BeanUtils.copyProperties(dto, entity);
                        entity.setRuleId(ruleId);
                        return entity;
                    })
                    .collect(Collectors.toList());

            itemMapper.batchInsert(itemEntities);
            log.info("批量保存规则明细成功, count={}", itemEntities.size());
        }

        return ruleId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(PuzzleFillRuleSaveRequest request) {
        if (request.getId() == null) {
            throw new IllegalArgumentException("更新规则时ID不能为空");
        }

        // 1. 更新主规则
        PuzzleFillRuleEntity ruleEntity = new PuzzleFillRuleEntity();
        BeanUtils.copyProperties(request, ruleEntity);
        ruleMapper.updateById(ruleEntity);

        // 2. 删除旧明细
        itemMapper.deleteByRuleId(request.getId());

        // 3. 批量插入新明细
        if (request.getItems() != null && !request.getItems().isEmpty()) {
            List<PuzzleFillRuleItemEntity> itemEntities = request.getItems().stream()
                    .map(dto -> {
                        PuzzleFillRuleItemEntity entity = new PuzzleFillRuleItemEntity();
                        BeanUtils.copyProperties(dto, entity);
                        entity.setRuleId(request.getId());
                        return entity;
                    })
                    .collect(Collectors.toList());

            itemMapper.batchInsert(itemEntities);
        }

        log.info("更新填充规则成功, ruleId={}, itemCount={}", request.getId(),
                request.getItems() != null ? request.getItems().size() : 0);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) {
        // MyBatis-Plus会级联删除明细(通过外键ON DELETE CASCADE)
        ruleMapper.deleteById(id);
        log.info("删除填充规则成功, ruleId={}", id);
        return true;
    }

    @Override
    public PuzzleFillRuleDTO getById(Long id) {
        PuzzleFillRuleEntity ruleEntity = ruleMapper.selectById(id);
        if (ruleEntity == null) {
            return null;
        }

        PuzzleFillRuleDTO dto = new PuzzleFillRuleDTO();
        BeanUtils.copyProperties(ruleEntity, dto);

        // 查询明细
        List<PuzzleFillRuleItemEntity> itemEntities = itemMapper.listByRuleId(id);
        if (itemEntities != null && !itemEntities.isEmpty()) {
            List<PuzzleFillRuleItemDTO> itemDTOs = itemEntities.stream()
                    .map(entity -> {
                        PuzzleFillRuleItemDTO itemDTO = new PuzzleFillRuleItemDTO();
                        BeanUtils.copyProperties(entity, itemDTO);
                        return itemDTO;
                    })
                    .collect(Collectors.toList());
            dto.setItems(itemDTOs);
        }

        return dto;
    }

    @Override
    public List<PuzzleFillRuleDTO> listByTemplateId(Long templateId) {
        List<PuzzleFillRuleEntity> ruleEntities = ruleMapper.listByTemplateId(templateId);
        if (ruleEntities == null || ruleEntities.isEmpty()) {
            return new ArrayList<>();
        }

        return ruleEntities.stream()
                .map(ruleEntity -> {
                    PuzzleFillRuleDTO dto = new PuzzleFillRuleDTO();
                    BeanUtils.copyProperties(ruleEntity, dto);

                    // 查询明细
                    List<PuzzleFillRuleItemEntity> itemEntities = itemMapper.listByRuleId(ruleEntity.getId());
                    if (itemEntities != null && !itemEntities.isEmpty()) {
                        List<PuzzleFillRuleItemDTO> itemDTOs = itemEntities.stream()
                                .map(entity -> {
                                    PuzzleFillRuleItemDTO itemDTO = new PuzzleFillRuleItemDTO();
                                    BeanUtils.copyProperties(entity, itemDTO);
                                    return itemDTO;
                                })
                                .collect(Collectors.toList());
                        dto.setItems(itemDTOs);
                    }

                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Boolean toggleEnabled(Long id, Integer enabled) {
        LambdaUpdateWrapper<PuzzleFillRuleEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PuzzleFillRuleEntity::getId, id)
                .set(PuzzleFillRuleEntity::getEnabled, enabled);

        int count = ruleMapper.update(null, updateWrapper);
        log.info("切换规则启用状态, ruleId={}, enabled={}", id, enabled);
        return count > 0;
    }
}
