package com.dora.service.impl;

import com.dora.dto.*;
import com.dora.entity.Banner;
import com.dora.exception.BusinessException;
import com.dora.mapper.BannerMapper;
import com.dora.service.BannerService;
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;

/**
 * Banner图服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BannerServiceImpl implements BannerService {
    
    private final BannerMapper bannerMapper;
    
    @Override
    public List<Banner> getAllEnabledBanners() {
        log.info("查询所有启用的Banner列表");
        return bannerMapper.selectAllEnabled();
    }
    
    @Override
    public Banner getBannerById(Long id) {
        Banner banner = bannerMapper.selectById(id);
        if (banner == null) {
            throw new BusinessException("Banner不存在");
        }
        return banner;
    }
    
    @Override
    @Transactional
    public Banner createBanner(Banner banner) {
        // 设置默认值
        if (banner.getSortOrder() == null) {
            banner.setSortOrder(0);
        }
        if (banner.getIsEnabled() == null) {
            banner.setIsEnabled(1);
        }
        if (banner.getLinkType() == null) {
            banner.setLinkType("internal");
        }
        
        banner.setCreateTime(LocalDateTime.now());
        banner.setUpdateTime(LocalDateTime.now());
        banner.setIsDeleted(0);
        
        int result = bannerMapper.insert(banner);
        if (result <= 0) {
            throw new BusinessException("创建Banner失败");
        }
        
        return banner;
    }
    
    @Override
    @Transactional
    public Banner updateBanner(Banner banner) {
        Banner existingBanner = bannerMapper.selectById(banner.getId());
        if (existingBanner == null) {
            throw new BusinessException("Banner不存在");
        }
        
        banner.setUpdateTime(LocalDateTime.now());
        
        int result = bannerMapper.updateById(banner);
        if (result <= 0) {
            throw new BusinessException("更新Banner失败");
        }
        
        return getBannerById(banner.getId());
    }
    
    @Override
    @Transactional
    public void deleteBanner(Long id) {
        Banner banner = bannerMapper.selectById(id);
        if (banner == null) {
            throw new BusinessException("Banner不存在");
        }
        
        int result = bannerMapper.deleteById(id);
        if (result <= 0) {
            throw new BusinessException("删除Banner失败");
        }
    }
    
    @Override
    public PageResultDto<BannerListDto> getBannersByPage(int page, int size) {
        log.info("分页查询Banner列表: page={}, size={}", page, size);
        int offset = (page - 1) * size;
        List<Banner> banners = bannerMapper.selectByPage(offset, size);
        Long total = bannerMapper.countAll();
        
        List<BannerListDto> bannerListDtos = banners.stream()
                .map(this::convertToListDto)
                .toList();
        
        return new PageResultDto<>(total, (long)page, (long)size, bannerListDtos);
    }
    
    @Override
    public BannerDto getBannerDtoById(Long id) {
        Banner banner = bannerMapper.selectById(id);
        if (banner == null) {
            throw new BusinessException("Banner不存在");
        }
        return convertToDto(banner);
    }
    
    @Override
    @Transactional
    public BannerDto createBanner(BannerCreateDto createDto) {
        Banner banner = new Banner();
        BeanUtils.copyProperties(createDto, banner);
        
        // 设置默认值
        if (banner.getSortOrder() == null) {
            banner.setSortOrder(0);
        }
        if (banner.getIsEnabled() == null) {
            banner.setIsEnabled(1);
        } else {
            banner.setIsEnabled(Boolean.TRUE.equals(createDto.getIsEnabled()) ? 1 : 0);
        }
        if (banner.getLinkType() == null) {
            banner.setLinkType("internal");
        }
        
        banner.setCreateTime(LocalDateTime.now());
        banner.setUpdateTime(LocalDateTime.now());
        banner.setIsDeleted(0);
        
        int result = bannerMapper.insert(banner);
        if (result <= 0) {
            throw new BusinessException("创建Banner失败");
        }
        
        return convertToDto(banner);
    }
    
    @Override
    @Transactional
    public BannerDto updateBanner(BannerUpdateDto updateDto) {
        Banner existingBanner = bannerMapper.selectById(updateDto.getId());
        if (existingBanner == null) {
            throw new BusinessException("Banner不存在");
        }
        
        Banner banner = new Banner();
        BeanUtils.copyProperties(updateDto, banner);
        
        // 处理Boolean到Integer的转换
        if (updateDto.getIsEnabled() != null) {
            banner.setIsEnabled(Boolean.TRUE.equals(updateDto.getIsEnabled()) ? 1 : 0);
        } else {
            banner.setIsEnabled(1);
        }
        
        banner.setUpdateTime(LocalDateTime.now());
        
        int result = bannerMapper.updateById(banner);
        if (result <= 0) {
            throw new BusinessException("更新Banner失败");
        }
        
        return getBannerDtoById(updateDto.getId());
    }
    
    @Override
    @Transactional
    public void batchUpdateSortOrder(List<BannerSortDto> sortDtos) {
        if (sortDtos == null || sortDtos.isEmpty()) {
            throw new BusinessException("批量更新数据不能为空");
        }
        
        List<Banner> banners = sortDtos.stream().map(sortDto -> {
            Banner banner = new Banner();
            banner.setId(sortDto.getId());
            banner.setSortOrder(sortDto.getSortOrder());
            banner.setUpdateTime(LocalDateTime.now());
            return banner;
        }).toList();
        
        int result = bannerMapper.batchUpdateSortOrder(banners);
        if (result <= 0) {
            throw new BusinessException("批量更新排序失败");
        }
        
        log.info("批量更新Banner排序成功: size={}", sortDtos.size());
    }
    
    @Override
    @Transactional
    public void updateBannerStatus(Long id, Boolean isEnabled) {
        Banner existingBanner = bannerMapper.selectById(id);
        if (existingBanner == null) {
            throw new BusinessException("Banner不存在");
        }
        
        Integer enabledValue = Boolean.TRUE.equals(isEnabled) ? 1 : 0;
        LocalDateTime updateTime = LocalDateTime.now();
        
        int result = bannerMapper.updateStatus(id, enabledValue, updateTime);
        if (result <= 0) {
            throw new BusinessException("更新Banner状态失败");
        }
        
        log.info("更新Banner状态成功: id={}, enabled={}", id, isEnabled);
    }
    
    /**
     * 转换为DTO
     */
    private BannerDto convertToDto(Banner banner) {
        BannerDto dto = new BannerDto();
        BeanUtils.copyProperties(banner, dto);
        dto.setIsEnabled(banner.getIsEnabled() == 1);
        return dto;
    }
    
    /**
     * 转换为ListDTO
     */
    private BannerListDto convertToListDto(Banner banner) {
        BannerListDto dto = new BannerListDto();
        BeanUtils.copyProperties(banner, dto);
        dto.setIsEnabled(banner.getIsEnabled() == 1);
        return dto;
    }
}
