package com.test.musichouduan.service.impl;

import com.test.musichouduan.dto.BannerDTO;
import com.test.musichouduan.dto.PageResult;
import com.test.musichouduan.entity.Banner;
import com.test.musichouduan.exception.BusinessException;
import com.test.musichouduan.repository.BannerRepository;
import com.test.musichouduan.service.BannerService;
import com.test.musichouduan.service.FileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private FileService fileService;

    @Override
    public BannerDTO getBannerById(Long id) {
        Banner banner = bannerRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));
        return convertToDTO(banner);
    }

    @Override
    public List<BannerDTO> getBannerList() {
        // 只获取启用状态的轮播图，并按排序号排序
        List<Banner> banners = bannerRepository.findByStatusOrderByOrderNumAsc(1);
        return banners.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public PageResult<BannerDTO> getBannerPage(Integer page, Integer size) {
        Page<Banner> bannerPage = bannerRepository.findAll(
                PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "orderNum"))
        );

        List<BannerDTO> bannerDTOs = bannerPage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        return new PageResult<>(
                bannerDTOs,
                bannerPage.getTotalElements(),
                page,
                size
        );
    }

    @Override
    @Transactional
    public BannerDTO addBanner(BannerDTO bannerDTO, MultipartFile image) {
        // 上传图片
        String imageUrl = fileService.uploadImage(image);

        // 创建轮播图实体
        Banner banner = new Banner();
        BeanUtils.copyProperties(bannerDTO, banner);
        banner.setImageUrl(imageUrl);
        banner.setStatus(banner.getStatus() != null ? banner.getStatus() : 1);

        // 保存轮播图
        Banner savedBanner = bannerRepository.save(banner);

        return convertToDTO(savedBanner);
    }

    @Override
    @Transactional
    public BannerDTO updateBanner(Long id, BannerDTO bannerDTO, MultipartFile image) {
        // 获取轮播图
        Banner banner = bannerRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));

        // 如果有新图片，则上传并更新URL
        if (image != null && !image.isEmpty()) {
            // 删除旧图片
            if (banner.getImageUrl() != null) {
                fileService.deleteFile(banner.getImageUrl());
            }

            // 上传新图片
            String imageUrl = fileService.uploadImage(image);
            banner.setImageUrl(imageUrl);
        }

        // 更新轮播图信息
        banner.setTitle(bannerDTO.getTitle());
        banner.setTargetType(bannerDTO.getTargetType());
        banner.setTargetId(bannerDTO.getTargetId());
        banner.setLinkUrl(bannerDTO.getLinkUrl());
        if (bannerDTO.getOrderNum() != null) {
            banner.setOrderNum(bannerDTO.getOrderNum());
        }
        if (bannerDTO.getStatus() != null) {
            banner.setStatus(bannerDTO.getStatus());
        }

        // 保存轮播图
        Banner updatedBanner = bannerRepository.save(banner);

        return convertToDTO(updatedBanner);
    }

    @Override
    @Transactional
    public boolean deleteBanner(Long id) {
        // 获取轮播图
        Banner banner = bannerRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));

        // 删除图片
        if (banner.getImageUrl() != null) {
            fileService.deleteFile(banner.getImageUrl());
        }

        // 删除轮播图
        bannerRepository.delete(banner);

        return true;
    }

    @Override
    @Transactional
    public boolean updateBannerStatus(Long id, Integer status) {
        // 获取轮播图
        Banner banner = bannerRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));

        // 更新状态
        banner.setStatus(status);

        // 保存轮播图
        bannerRepository.save(banner);

        return true;
    }

    @Override
    @Transactional
    public boolean updateBannerOrder(Long id, Integer orderNum) {
        // 获取轮播图
        Banner banner = bannerRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));

        // 更新排序号
        banner.setOrderNum(orderNum);

        // 保存轮播图
        bannerRepository.save(banner);

        return true;
    }

    /**
     * 将实体转换为DTO
     *
     * @param banner 轮播图实体
     * @return 轮播图DTO
     */
    private BannerDTO convertToDTO(Banner banner) {
        BannerDTO bannerDTO = new BannerDTO();
        BeanUtils.copyProperties(banner, bannerDTO);
        // 处理字段名不一致的情况
        // 不需要手动设置，因为BeanUtils会自动匹配相同名称的属性
        return bannerDTO;
    }
}
