package com.gxwebsoft.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.cms.entity.CmsBannerGroup;
import com.gxwebsoft.cms.entity.CmsBannerItem;
import com.gxwebsoft.cms.mapper.CmsBannerGroupMapper;
import com.gxwebsoft.cms.mapper.CmsBannerItemMapper;
import com.gxwebsoft.cms.param.CmsBannerGroupParam;
import com.gxwebsoft.cms.service.CmsBannerGroupService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 轮播组Service实现
 *
 * @author WorkBuddy
 * @since 2026-07-19
 */
@Service
public class CmsBannerGroupServiceImpl extends ServiceImpl<CmsBannerGroupMapper, CmsBannerGroup> implements CmsBannerGroupService {

    @Resource
    private CmsBannerItemMapper bannerItemMapper;

    @Override
    public PageResult<CmsBannerGroup> pageRel(CmsBannerGroupParam param) {
        PageParam<CmsBannerGroup, CmsBannerGroupParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        IPage<CmsBannerGroup> result = page(page, page.getOrderWrapper());
        List<CmsBannerGroup> records = result.getRecords();
        // 批量填充 items
        fillItems(records);
        return new PageResult<>(records, result.getTotal());
    }

    @Override
    public List<CmsBannerGroup> listRel(CmsBannerGroupParam param) {
        PageParam<CmsBannerGroup, CmsBannerGroupParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<CmsBannerGroup> records = list(page.getOrderWrapper());
        fillItems(records);
        return records;
    }

    @Override
    public CmsBannerGroup getByIdRel(Integer groupId) {
        CmsBannerGroup group = getById(groupId);
        if (group == null) {
            return null;
        }
        List<CmsBannerItem> items = listItemsByGroupId(groupId);
        group.setItems(items);
        return group;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveGroup(CmsBannerGroup group) {
        // 先保存组
        boolean ok = save(group);
        if (!ok) {
            return false;
        }
        // 再保存组内items
        saveItems(group.getGroupId(), group.getItems());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGroup(CmsBannerGroup group) {
        // 更新组主信息
        boolean ok = updateById(group);
        if (!ok) {
            return false;
        }
        Integer groupId = group.getGroupId();
        // 全量替换items: 先删除旧items, 再插入新items
        if (group.getItems() != null) {
            bannerItemMapper.delete(new LambdaQueryWrapper<CmsBannerItem>()
                    .eq(CmsBannerItem::getGroupId, groupId));
            saveItems(groupId, group.getItems());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeGroup(Integer groupId) {
        // 逻辑删除组
        boolean ok = removeById(groupId);
        if (!ok) {
            return false;
        }
        // 逻辑删除组内items
        bannerItemMapper.delete(new LambdaQueryWrapper<CmsBannerItem>()
                .eq(CmsBannerItem::getGroupId, groupId));
        return true;
    }

    // ----------------- private -----------------

    /**
     * 查询某个组下的所有轮播项(按sort_number升序)
     */
    private List<CmsBannerItem> listItemsByGroupId(Integer groupId) {
        if (groupId == null) {
            return Collections.emptyList();
        }
        return bannerItemMapper.selectList(new LambdaQueryWrapper<CmsBannerItem>()
                .eq(CmsBannerItem::getGroupId, groupId)
                .orderByAsc(CmsBannerItem::getSortNumber));
    }

    /**
     * 批量查询多个组的items并按group分组
     */
    private Map<Integer, List<CmsBannerItem>> listItemsByGroupIds(List<Integer> groupIds) {
        if (groupIds == null || groupIds.isEmpty()) {
            return Collections.emptyMap();
        }
        List<CmsBannerItem> allItems = bannerItemMapper.selectList(new LambdaQueryWrapper<CmsBannerItem>()
                .in(CmsBannerItem::getGroupId, groupIds)
                .orderByAsc(CmsBannerItem::getSortNumber));
        return allItems.stream().collect(Collectors.groupingBy(CmsBannerItem::getGroupId));
    }

    /**
     * 批量给group列表填充items
     */
    private void fillItems(List<CmsBannerGroup> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        List<Integer> groupIds = records.stream()
                .map(CmsBannerGroup::getGroupId)
                .collect(Collectors.toList());
        Map<Integer, List<CmsBannerItem>> itemsMap = listItemsByGroupIds(groupIds);
        for (CmsBannerGroup g : records) {
            g.setItems(itemsMap.getOrDefault(g.getGroupId(), new ArrayList<>()));
        }
    }

    /**
     * 批量保存组内items
     */
    private void saveItems(Integer groupId, List<CmsBannerItem> items) {
        if (groupId == null || items == null || items.isEmpty()) {
            return;
        }
        for (int i = 0; i < items.size(); i++) {
            CmsBannerItem item = items.get(i);
            item.setItemId(null); // 新增时清除前端可能传入的ID
            item.setGroupId(groupId);
            if (item.getSortNumber() == null) {
                item.setSortNumber(i);
            }
            if (item.getLinkType() == null) {
                item.setLinkType(0);
            }
            bannerItemMapper.insert(item);
        }
    }
}
