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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.setting.convert.MarketingActivityConvert;
import com.jeesharp.business.modules.setting.convert.MarketingActivityRuleConvert;
import com.jeesharp.business.modules.setting.convert.MarketingActivityScopeConvert;
import com.jeesharp.business.modules.setting.convert.MarketingPosterTemplateConvert;
import com.jeesharp.business.modules.setting.dto.MarketingActivitySaveDTO;
import com.jeesharp.business.modules.setting.entity.MarketingActivity;
import com.jeesharp.business.modules.setting.entity.MarketingActivityRule;
import com.jeesharp.business.modules.setting.entity.MarketingActivityScope;
import com.jeesharp.business.modules.setting.entity.MarketingPosterTemplate;
import com.jeesharp.business.modules.setting.service.MarketingActivityRuleService;
import com.jeesharp.business.modules.setting.service.MarketingActivityScopeService;
import com.jeesharp.business.modules.setting.service.MarketingActivityService;
import com.jeesharp.business.modules.setting.service.MarketingPosterTemplateService;
import com.jeesharp.business.modules.setting.vo.MarketingActivityListVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityMobileDetailVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityQueryVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityRuleVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityScopeVO;
import com.jeesharp.business.modules.setting.vo.MarketingActivityVO;
import com.jeesharp.business.modules.setting.vo.MarketingPosterTemplateVO;
import com.jeesharp.business.modules.setting.vo.MarketingPosterTemplateQueryVO;
import com.jeesharp.business.modules.setting.vo.MarketingShareConfigVO;
import com.jeesharp.business.modules.setting.vo.PromotionGiftConfigVO;
import com.jeesharp.business.modules.setting.vo.PromotionGiftRuleVO;
import com.jeesharp.business.modules.setting.vo.ShareCommissionConfigVO;
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.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MarketingActivityApplicationService {

    private final MarketingActivityService marketingActivityService;
    private final MarketingActivityRuleService marketingActivityRuleService;
    private final MarketingActivityScopeService marketingActivityScopeService;
    private final MarketingPosterTemplateService marketingPosterTemplateService;

    public MarketingActivityVO get(String id) {
        return MarketingActivityConvert.INSTANCE.toInfoVO(marketingActivityService.get(id));
    }

    public PageRespVO<MarketingActivityListVO> findPage(Page<MarketingActivity> page, MarketingActivityQueryVO query) {
        Page<MarketingActivity> result = marketingActivityService.findPage(page, query);
        return MarketingActivityConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MarketingActivitySaveDTO dto) {
        MarketingActivity entity = MarketingActivityConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            marketingActivityService.createMarketingActivity(entity);
            return;
        }
        marketingActivityService.updateMarketingActivity(entity);
    }

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

    public List<MarketingActivityListVO> listForMobile(String scene, String activityType, String status) {
        String finalStatus = StrUtil.blankToDefault(status, "enabled");
        return MarketingActivityConvert.INSTANCE.toListVO(
                marketingActivityService.listEnabledForMobile(scene, activityType, finalStatus)
        );
    }

    public MarketingActivityMobileDetailVO getMobileDetail(String id) {
        MarketingActivity entity = marketingActivityService.get(id);
        if (entity == null) {
            return null;
        }
        MarketingActivityMobileDetailVO vo = new MarketingActivityMobileDetailVO();
        vo.setId(entity.getId());
        vo.setActivityCode(entity.getActivityCode());
        vo.setActivityName(entity.getActivityName());
        vo.setActivityType(entity.getActivityType());
        vo.setScene(entity.getActivityScene());
        vo.setShareTitle(entity.getShareTitle());
        vo.setShareSubtitle(entity.getShareSubtitle());
        vo.setShareImageUrl(entity.getShareImageUrl());
        vo.setSharePath(entity.getSharePath());
        vo.setStatus(entity.getStatus());
        vo.setStartTime(entity.getStartTime());
        vo.setEndTime(entity.getEndTime());
        vo.setRules(marketingActivityRuleService.listByActivityId(entity.getId())
                .stream()
                .map(MarketingActivityRuleConvert.INSTANCE::toInfoVO)
                .toList());
        vo.setScopes(marketingActivityScopeService.listByActivityId(entity.getId())
                .stream()
                .map(MarketingActivityScopeConvert.INSTANCE::toInfoVO)
                .toList());
        if (StrUtil.isNotBlank(entity.getPosterTemplateId())) {
            MarketingPosterTemplate template = marketingPosterTemplateService.get(entity.getPosterTemplateId());
            if (template != null) {
                vo.setPosterUrl(template.getPreviewImageUrl());
                vo.setPosterTemplate(MarketingPosterTemplateConvert.INSTANCE.toInfoVO(template));
            }
        }
        return vo;
    }

    public MarketingShareConfigVO getShareConfig(String activityId, String scene, String bizType, String bizId) {
        MarketingActivity entity = marketingActivityService.get(activityId);
        if (entity == null) {
            return null;
        }
        MarketingShareConfigVO vo = new MarketingShareConfigVO();
        vo.setActivityId(entity.getId());
        vo.setShareTitle(entity.getShareTitle());
        vo.setShareSubtitle(entity.getShareSubtitle());
        vo.setShareImageUrl(entity.getShareImageUrl());
        vo.setSharePath(entity.getSharePath());
        vo.setInviteCode("INV" + entity.getId().substring(Math.max(0, entity.getId().length() - 6)).toUpperCase());
        if (StrUtil.isNotBlank(entity.getPosterTemplateId())) {
            MarketingPosterTemplate template = marketingPosterTemplateService.get(entity.getPosterTemplateId());
            if (template != null) {
                vo.setPosterUrl(template.getPreviewImageUrl());
            }
        }
        vo.setQrCodeUrl(StrUtil.blankToDefault(vo.getPosterUrl(), entity.getShareImageUrl()));
        return vo;
    }

    public PromotionGiftConfigVO getPromotionGiftDetail(String activityId, String scene) {
        MarketingActivity entity = resolveFirstActivity(activityId, scene, "promotion_gift");
        if (entity == null) {
            return null;
        }
        PromotionGiftConfigVO vo = new PromotionGiftConfigVO();
        vo.setActivityId(entity.getId());
        vo.setActivityName(entity.getActivityName());
        vo.setRewardDesc(StrUtil.blankToDefault(entity.getShareSubtitle(), entity.getShareTitle()));
        vo.setValidPeriod(buildPeriod(entity));
        vo.setInviteCode("INV" + entity.getId().substring(Math.max(0, entity.getId().length() - 6)).toUpperCase());
        if (StrUtil.isNotBlank(entity.getPosterTemplateId())) {
            MarketingPosterTemplate template = marketingPosterTemplateService.get(entity.getPosterTemplateId());
            if (template != null) {
                vo.setPosterUrl(template.getPreviewImageUrl());
            }
        }
        List<PromotionGiftRuleVO> rewardRules = new ArrayList<>();
        for (MarketingActivityRule rule : marketingActivityRuleService.listByActivityId(entity.getId())) {
            PromotionGiftRuleVO item = new PromotionGiftRuleVO();
            item.setTargetRole(rule.getRewardRole());
            item.setRewardType(rule.getRewardType());
            item.setRewardValue(rule.getRewardValue() == null ? null : rule.getRewardValue().stripTrailingZeros().toPlainString());
            item.setTriggerCondition(rule.getTriggerEvent());
            rewardRules.add(item);
        }
        vo.setRewardRules(rewardRules);
        return vo;
    }

    public ShareCommissionConfigVO getShareCommissionDetail(String activityId, String bizType, String bizId) {
        MarketingActivity entity = resolveFirstActivity(activityId, null, "share_commission");
        if (entity == null) {
            return null;
        }
        ShareCommissionConfigVO vo = new ShareCommissionConfigVO();
        vo.setActivityId(entity.getId());
        List<String> tips = new ArrayList<>();
        for (MarketingActivityRule rule : marketingActivityRuleService.listByActivityId(entity.getId())) {
            vo.setCommissionType(rule.getRewardRatio() != null ? "ratio" : "fixed");
            vo.setCommissionRate(rule.getRewardRatio());
            vo.setCommissionAmount(rule.getRewardValue() == null ? null : rule.getRewardValue().stripTrailingZeros().toPlainString());
            vo.setMaxRewardAmount(rule.getMaxRewardAmount() == null ? null : rule.getMaxRewardAmount().stripTrailingZeros().toPlainString());
            vo.setSettleMode(rule.getSettleMode());
            if (StrUtil.isNotBlank(rule.getTriggerEvent())) {
                tips.add(rule.getTriggerEvent());
            }
        }
        if (tips.isEmpty()) {
            tips.add("分享后好友完成指定动作即可发放奖励");
        }
        vo.setTips(tips);
        return vo;
    }

    public MarketingPosterTemplateVO getPosterTemplate(String activityId, String templateType, String scene) {
        MarketingPosterTemplate template = null;
        if (StrUtil.isNotBlank(activityId)) {
            MarketingActivity entity = marketingActivityService.get(activityId);
            if (entity != null && StrUtil.isNotBlank(entity.getPosterTemplateId())) {
                template = marketingPosterTemplateService.get(entity.getPosterTemplateId());
            }
        }
        if (template == null) {
            MarketingPosterTemplateQueryVO query = new MarketingPosterTemplateQueryVO();
            query.setTemplateType(templateType);
            query.setStatus("enabled");
            List<MarketingPosterTemplate> list = marketingPosterTemplateService.findList(query);
            if (!list.isEmpty()) {
                template = list.get(0);
            }
        }
        return template == null ? null : MarketingPosterTemplateConvert.INSTANCE.toInfoVO(template);
    }

    private MarketingActivity resolveFirstActivity(String activityId, String scene, String activityType) {
        if (StrUtil.isNotBlank(activityId)) {
            MarketingActivity entity = marketingActivityService.get(activityId);
            if (entity == null) {
                return null;
            }
            if (StrUtil.isNotBlank(activityType) && !StrUtil.equals(entity.getActivityType(), activityType)) {
                return null;
            }
            return entity;
        }
        List<MarketingActivity> list = marketingActivityService.listEnabledForMobile(scene, activityType, "enabled");
        return list.isEmpty() ? null : list.get(0);
    }

    private String buildPeriod(MarketingActivity entity) {
        if (entity.getStartTime() == null && entity.getEndTime() == null) {
            return null;
        }
        return String.valueOf(entity.getStartTime()) + " ~ " + String.valueOf(entity.getEndTime());
    }
}
