package com.dora.service.impl;

import com.dora.dto.*;
import com.dora.entity.PromotionPoster;
import com.dora.exception.BusinessException;
import com.dora.mapper.PromotionPosterMapper;
import com.dora.service.PromotionPosterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 推广海报服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PromotionPosterServiceImpl implements PromotionPosterService {
    
    private final PromotionPosterMapper promotionPosterMapper;
    
    @Override
    public List<PromotionPoster> getAllEnabledPromotionPosters() {
        log.info("查询所有启用的推广海报列表");
        return promotionPosterMapper.selectAllEnabled();
    }
    
    @Override
    public PromotionPoster getPromotionPosterById(Long id) {
        PromotionPoster promotionPoster = promotionPosterMapper.selectById(id);
        if (promotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        return promotionPoster;
    }
    
    @Override
    @Transactional
    public PromotionPoster createPromotionPoster(PromotionPoster promotionPoster) {
        // 设置默认值
        if (promotionPoster.getSortOrder() == null) {
            promotionPoster.setSortOrder(0);
        }
        if (promotionPoster.getIsEnabled() == null) {
            promotionPoster.setIsEnabled(1);
        }
        
        promotionPoster.setCreateTime(LocalDateTime.now());
        promotionPoster.setUpdateTime(LocalDateTime.now());
        promotionPoster.setIsDeleted(0);
        
        int result = promotionPosterMapper.insert(promotionPoster);
        if (result <= 0) {
            throw new BusinessException("创建推广海报失败");
        }
        
        return promotionPoster;
    }
    
    @Override
    @Transactional
    public PromotionPoster updatePromotionPoster(PromotionPoster promotionPoster) {
        PromotionPoster existingPromotionPoster = promotionPosterMapper.selectById(promotionPoster.getId());
        if (existingPromotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        
        promotionPoster.setUpdateTime(LocalDateTime.now());
        
        int result = promotionPosterMapper.updateById(promotionPoster);
        if (result <= 0) {
            throw new BusinessException("更新推广海报失败");
        }
        
        return getPromotionPosterById(promotionPoster.getId());
    }
    
    @Override
    @Transactional
    public void deletePromotionPoster(Long id) {
        PromotionPoster promotionPoster = promotionPosterMapper.selectById(id);
        if (promotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        
        int result = promotionPosterMapper.deleteById(id);
        if (result <= 0) {
            throw new BusinessException("删除推广海报失败");
        }
    }
    
    @Override
    public PageResultDto<PromotionPosterListDto> getPromotionPostersByPage(int page, int size) {
        log.info("分页查询推广海报列表: page={}, size={}", page, size);
        int offset = (page - 1) * size;
        List<PromotionPoster> promotionPosters = promotionPosterMapper.selectByPage(offset, size);
        Long total = promotionPosterMapper.countAll();
        
        List<PromotionPosterListDto> promotionPosterListDtos = promotionPosters.stream()
                .map(this::convertToListDto)
                .toList();
        
        return new PageResultDto<>(total, (long)page, (long)size, promotionPosterListDtos);
    }
    
    @Override
    public PromotionPosterDto getPromotionPosterDtoById(Long id) {
        PromotionPoster promotionPoster = promotionPosterMapper.selectById(id);
        if (promotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        return convertToDto(promotionPoster);
    }
    
    @Override
    @Transactional
    public PromotionPosterDto createPromotionPoster(PromotionPosterCreateDto createDto) {
        PromotionPoster promotionPoster = new PromotionPoster();
        BeanUtils.copyProperties(createDto, promotionPoster);
        
        // 设置默认值
        if (promotionPoster.getSortOrder() == null) {
            promotionPoster.setSortOrder(0);
        }
        if (promotionPoster.getIsEnabled() == null) {
            promotionPoster.setIsEnabled(1);
        } else {
            promotionPoster.setIsEnabled(Boolean.TRUE.equals(createDto.getIsEnabled()) ? 1 : 0);
        }
        
        promotionPoster.setCreateTime(LocalDateTime.now());
        promotionPoster.setUpdateTime(LocalDateTime.now());
        promotionPoster.setIsDeleted(0);
        
        int result = promotionPosterMapper.insert(promotionPoster);
        if (result <= 0) {
            throw new BusinessException("创建推广海报失败");
        }
        
        return convertToDto(promotionPoster);
    }
    
    @Override
    @Transactional
    public PromotionPosterDto updatePromotionPoster(PromotionPosterUpdateDto updateDto) {
        PromotionPoster existingPromotionPoster = promotionPosterMapper.selectById(updateDto.getId());
        if (existingPromotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        
        PromotionPoster promotionPoster = new PromotionPoster();
        BeanUtils.copyProperties(updateDto, promotionPoster);
        
        // 处理Boolean到Integer的转换
        if (updateDto.getIsEnabled() != null) {
            promotionPoster.setIsEnabled(Boolean.TRUE.equals(updateDto.getIsEnabled()) ? 1 : 0);
        } else {
            promotionPoster.setIsEnabled(1);
        }
        
        promotionPoster.setUpdateTime(LocalDateTime.now());
        
        int result = promotionPosterMapper.updateById(promotionPoster);
        if (result <= 0) {
            throw new BusinessException("更新推广海报失败");
        }
        
        return getPromotionPosterDtoById(updateDto.getId());
    }
    
    @Override
    @Transactional
    public void batchUpdateSortOrder(List<PromotionPosterSortDto> sortDtos) {
        if (sortDtos == null || sortDtos.isEmpty()) {
            throw new BusinessException("批量更新数据不能为空");
        }
        
        List<PromotionPoster> promotionPosters = sortDtos.stream().map(sortDto -> {
            PromotionPoster promotionPoster = new PromotionPoster();
            promotionPoster.setId(sortDto.getId());
            promotionPoster.setSortOrder(sortDto.getSortOrder());
            promotionPoster.setUpdateTime(LocalDateTime.now());
            return promotionPoster;
        }).toList();
        
        int result = promotionPosterMapper.batchUpdateSortOrder(promotionPosters);
        if (result <= 0) {
            throw new BusinessException("批量更新排序失败");
        }
        
        log.info("批量更新推广海报排序成功: size={}", sortDtos.size());
    }
    
    @Override
    @Transactional
    public void updatePromotionPosterStatus(Long id, Boolean isEnabled) {
        PromotionPoster existingPromotionPoster = promotionPosterMapper.selectById(id);
        if (existingPromotionPoster == null) {
            throw new BusinessException("推广海报不存在");
        }
        
        Integer enabledValue = Boolean.TRUE.equals(isEnabled) ? 1 : 0;
        LocalDateTime updateTime = LocalDateTime.now();
        
        int result = promotionPosterMapper.updateStatus(id, enabledValue, updateTime);
        if (result <= 0) {
            throw new BusinessException("更新推广海报状态失败");
        }
        
        log.info("更新推广海报状态成功: id={}, enabled={}", id, isEnabled);
    }
    
    /**
     * 转换为DTO
     */
    private PromotionPosterDto convertToDto(PromotionPoster promotionPoster) {
        PromotionPosterDto dto = new PromotionPosterDto();
        BeanUtils.copyProperties(promotionPoster, dto);
        dto.setIsEnabled(promotionPoster.getIsEnabled() == 1);
        return dto;
    }
    
    /**
     * 转换为ListDTO
     */
    private PromotionPosterListDto convertToListDto(PromotionPoster promotionPoster) {
        PromotionPosterListDto dto = new PromotionPosterListDto();
        BeanUtils.copyProperties(promotionPoster, dto);
        dto.setIsEnabled(promotionPoster.getIsEnabled() == 1);
        return dto;
    }
}
