package com.ruoyi.web.modules.content.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.content.constant.BannerConstants;
import com.ruoyi.web.modules.content.domain.BizHomeBanner;
import com.ruoyi.web.modules.content.dto.BannerSortDTO;
import com.ruoyi.web.modules.content.mapper.BizHomeBannerMapper;
import com.ruoyi.web.modules.content.service.IBannerService;
import com.ruoyi.web.modules.content.support.BannerImageSupport;
import com.ruoyi.web.modules.content.vo.BannerListVO;
import com.ruoyi.web.modules.content.vo.HomeBannerAppVO;

/**
 * 首页 Banner 服务实现
 */
@Service
public class BannerServiceImpl implements IBannerService
{
    private static final String DICT_YES_NO = "sys_yes_no";

    @Autowired
    private BizHomeBannerMapper bannerMapper;

    @Override
    public List<BannerListVO> selectBannerList(BizHomeBanner query)
    {
        List<BannerListVO> rows = new ArrayList<>();
        for (BizHomeBanner row : bannerMapper.selectList(query))
        {
            rows.add(toListVo(row));
        }
        return rows;
    }

    @Override
    public BizHomeBanner selectBannerById(Long bannerId)
    {
        BizHomeBanner row = bannerMapper.selectById(bannerId);
        if (row == null)
        {
            throw new ServiceException("Banner 不存在或已删除");
        }
        return row;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertBanner(BizHomeBanner row)
    {
        validateFields(row);
        if (bannerMapper.countByName(row.getBannerName(), null) > 0)
        {
            throw new ServiceException("图片名称已存在");
        }
        row.setDelFlag(BannerConstants.DEL_FLAG_NORMAL);
        bannerMapper.insert(row);
        return buildSaveResult(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateBanner(BizHomeBanner row)
    {
        if (row.getBannerId() == null)
        {
            throw new ServiceException("Banner ID不能为空");
        }
        BizHomeBanner existing = bannerMapper.selectById(row.getBannerId());
        if (existing == null)
        {
            throw new ServiceException("Banner 不存在或已删除");
        }
        validateFields(row);
        if (bannerMapper.countByName(row.getBannerName(), row.getBannerId()) > 0)
        {
            throw new ServiceException("图片名称已存在");
        }
        bannerMapper.update(row);
        return buildSaveResult(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSortNo(BannerSortDTO dto, String operator)
    {
        if (dto == null || dto.getBannerId() == null)
        {
            throw new ServiceException("Banner ID不能为空");
        }
        if (dto.getSortNo() == null || dto.getSortNo() < 0)
        {
            throw new ServiceException("排序须为非负整数");
        }
        BizHomeBanner existing = bannerMapper.selectById(dto.getBannerId());
        if (existing == null)
        {
            throw new ServiceException("Banner 不存在或已删除");
        }
        if (bannerMapper.updateSortNo(dto.getBannerId(), dto.getSortNo(), operator) <= 0)
        {
            throw new ServiceException("更新排序失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteBannerByIds(Long[] bannerIds, String operator)
    {
        if (bannerIds == null || bannerIds.length == 0)
        {
            throw new ServiceException("请选择要删除的 Banner");
        }
        List<Long> idList = new ArrayList<>();
        int skipped = 0;
        for (Long bannerId : bannerIds)
        {
            BizHomeBanner row = bannerMapper.selectById(bannerId);
            if (row == null)
            {
                skipped++;
            }
            else
            {
                idList.add(bannerId);
            }
        }
        if (!idList.isEmpty())
        {
            bannerMapper.logicDeleteByIds(idList, operator);
        }
        if (idList.isEmpty() && skipped > 0)
        {
            throw new ServiceException("Banner 不存在或已删除");
        }
        if (skipped > 0)
        {
            return "删除成功，已跳过 " + skipped + " 条";
        }
        return "操作成功";
    }

    @Override
    public List<HomeBannerAppVO> listBannersForApp()
    {
        List<HomeBannerAppVO> list = new ArrayList<>();
        for (BizHomeBanner row : bannerMapper.selectEnabledForApp(BannerConstants.APP_LIST_LIMIT))
        {
            HomeBannerAppVO vo = new HomeBannerAppVO();
            vo.setBannerId(row.getBannerId());
            vo.setBannerImage(row.getBannerImage());
            vo.setSortNo(row.getSortNo());
            list.add(vo);
        }
        return list;
    }

    void validateFields(BizHomeBanner row)
    {
        if (StringUtils.isEmpty(row.getEnableFlag()))
        {
            row.setEnableFlag(BannerConstants.ENABLE_YES);
        }
        if (row.getSortNo() == null)
        {
            row.setSortNo(0);
        }
        if (StringUtils.isEmpty(row.getBannerName()))
        {
            throw new ServiceException("请输入图片名称");
        }
        if (row.getBannerName().length() > 64)
        {
            throw new ServiceException("图片名称长度不能超过64个字符");
        }
        BannerImageSupport.validateImageUrl(row.getBannerImage());
        if (row.getSortNo() < 0)
        {
            throw new ServiceException("排序须为非负整数");
        }
        validateEnableFlag(row.getEnableFlag());
    }

    private void validateEnableFlag(String flag)
    {
        if (!BannerConstants.ENABLE_YES.equals(flag) && !BannerConstants.ENABLE_NO.equals(flag))
        {
            throw new ServiceException("是否启用参数无效");
        }
    }

    private Map<String, Object> buildSaveResult(BizHomeBanner row)
    {
        Map<String, Object> data = new HashMap<>();
        data.put("bannerId", row.getBannerId());
        if (BannerImageSupport.isNonStandardAspectRatio(row.getBannerImage()))
        {
            data.put("warnAspectRatio", true);
        }
        return data;
    }

    private BannerListVO toListVo(BizHomeBanner row)
    {
        BannerListVO vo = new BannerListVO();
        vo.setBannerId(row.getBannerId());
        vo.setBannerName(row.getBannerName());
        vo.setBannerImage(row.getBannerImage());
        vo.setEnableFlag(row.getEnableFlag());
        vo.setSortNo(row.getSortNo());
        vo.setCreateTime(row.getCreateTime());
        String label = DictUtils.getDictLabel(DICT_YES_NO, row.getEnableFlag());
        if (StringUtils.isEmpty(label))
        {
            label = BannerConstants.ENABLE_YES.equals(row.getEnableFlag()) ? "是" : "否";
        }
        vo.setEnableFlagLabel(label);
        return vo;
    }
}
