package com.jeesharp.business.modules.setting.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.setting.convert.MarketingActivityRuleConvert;
import com.jeesharp.business.modules.setting.dto.MarketingActivityRuleSaveDTO;
import com.jeesharp.business.modules.setting.entity.MarketingActivityRule;
import com.jeesharp.business.modules.setting.service.MarketingActivityRuleService;
import com.jeesharp.business.modules.setting.service.MarketingActivityService;
import com.jeesharp.business.modules.setting.vo.MarketingActivityRuleListVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityRuleQueryVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityRuleVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 活动营销规则应用服务：后台规则查询、维护及活动名称展示编排。
 *
 * @author jeesharp
 * @since 2026-06-04
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MarketingActivityRuleApplicationService {

    private final MarketingActivityRuleService marketingActivityRuleService;
    private final MarketingActivityService marketingActivityService;

    public MarketingActivityRuleVO get(String id) {
        MarketingActivityRule entity = marketingActivityRuleService.get(id);
        if (entity == null) {
            return null;
        }
        MarketingActivityRuleVO vo = MarketingActivityRuleConvert.INSTANCE.toInfoVO(entity);
        enrichInfoDisplay(vo);
        return vo;
    }

    public PageRespVO<MarketingActivityRuleListVO> findPage(Page<MarketingActivityRule> page, MarketingActivityRuleQueryVO query) {
        MarketingActivityRuleQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<MarketingActivityRule> result = marketingActivityRuleService.findPage(page, prepared);
        PageRespVO<MarketingActivityRuleListVO> pageVo = MarketingActivityRuleConvert.INSTANCE.toPageRespVO(result);
        enrichListDisplay(pageVo.getRecords());
        return pageVo;
    }

    @Transactional(readOnly = false)
    public void save(MarketingActivityRuleSaveDTO dto) {
        MarketingActivityRule entity = MarketingActivityRuleConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            marketingActivityRuleService.createMarketingActivityRule(entity);
            return;
        }
        marketingActivityRuleService.updateMarketingActivityRule(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        marketingActivityRuleService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 管理端活动名称/编码筛选 → activityIdIn。
     */
    private MarketingActivityRuleQueryVO prepareQuery(MarketingActivityRuleQueryVO query) {
        MarketingActivityRuleQueryVO q = query != null ? query : new MarketingActivityRuleQueryVO();
        if (StrUtil.isNotBlank(q.getActivityName())) {
            List<String> activityIds = marketingActivityService.findIdsByNameLike(q.getActivityName().trim());
            q.setActivityName(null);
            if (CollUtil.isEmpty(activityIds)) {
                return null;
            }
            q.setActivityIdIn(activityIds);
        }
        return q;
    }

    private void enrichListDisplay(List<MarketingActivityRuleListVO> rows) {
        if (CollUtil.isEmpty(rows)) {
            return;
        }
        List<String> activityIds = rows.stream()
            .map(MarketingActivityRuleListVO::getActivityId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .toList();
        Map<String, String> activityNameMap = marketingActivityService.mapActivityNameByIds(activityIds);
        for (MarketingActivityRuleListVO row : rows) {
            if (StrUtil.isNotBlank(row.getActivityId())) {
                row.setActivityName(activityNameMap.get(row.getActivityId()));
            }
        }
    }

    private void enrichInfoDisplay(MarketingActivityRuleVO vo) {
        if (vo == null || StrUtil.isBlank(vo.getActivityId())) {
            return;
        }
        Map<String, String> nameMap = marketingActivityService.mapActivityNameByIds(List.of(vo.getActivityId()));
        vo.setActivityName(nameMap.get(vo.getActivityId()));
    }

    private static PageRespVO<MarketingActivityRuleListVO> emptyPage(Page<MarketingActivityRule> page) {
        PageRespVO<MarketingActivityRuleListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page != null ? page.getPageNo() : 1L);
        empty.setPageSize(page != null ? page.getPageSize() : 10L);
        return empty;
    }
}
