package com.seer.teach.mp.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpDownloader;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.service.CommonFileService;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mp.app.controller.req.AppMpAgentActivityQrCodeQueryReq;
import com.seer.teach.mp.app.controller.req.MpGenerateQrCodeReq;
import com.seer.teach.mp.app.controller.resp.AgentActivityParticipantResp;
import com.seer.teach.mp.app.controller.resp.MpQrCodeResp;
import com.seer.teach.mp.app.service.AppOfficialQrCodeService;
import com.seer.teach.mp.app.service.IAppAgentActivityParticipantService;
import com.seer.teach.mp.app.service.IAppAgentService;
import com.seer.teach.mp.entity.MpActivityEntity;
import com.seer.teach.mp.entity.MpAgentActivityParticipantEntity;
import com.seer.teach.mp.service.IMpActivityService;
import com.seer.teach.mp.service.IMpAgentActivityParticipantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * APP端代理商活动参与记录服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-12-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppAgentActivityParticipantServiceImpl implements IAppAgentActivityParticipantService {

    private final IMpAgentActivityParticipantService agentActivityParticipantService;

    private final IAppAgentService appAgentService;

    private final IMpActivityService mpActivityService;

    private final AppOfficialQrCodeService officialQrCodeService;

    private final CommonFileService commonFileService;

    @Override
    public List<AgentActivityParticipantResp> getParticipantsByActivityAndAgent(Integer agentId, Integer userId) {
        var userAgentId = appAgentService.getAgentIdByUserId(userId);
        if (Objects.isNull(userAgentId)) {
            return List.of();
        }
        log.info("userAgentId:{}", userAgentId);
        if(userAgentId.intValue() != agentId){
            throw new CommonException(ResultCodeEnum.RELATION_NOT_FOUND);
        }
        var participants = agentActivityParticipantService.getListByAgentId(agentId);

        if (CollectionUtil.isEmpty(participants)) {
            return List.of();
        }
        Set<Integer> activityIds = participants.stream().map(MpAgentActivityParticipantEntity::getActivityId).collect(Collectors.toSet());

        List<MpActivityEntity> parentInfos = mpActivityService.listByIds(activityIds);

        var activityInfoMap = parentInfos.stream().collect(Collectors.toMap(MpActivityEntity::getId, activity -> activity));

        return participants.stream()
            .map(entity -> convertToDto(entity, activityInfoMap))
            .collect(Collectors.toList());
    }

    @Override
    public String getQrCode(AppMpAgentActivityQrCodeQueryReq req, Integer userId) {
        Integer activityId = req.getActivityId();
        Integer agentId = req.getAgentId();
        log.info("getQrCode param activityId:{},agentId:{}", activityId, agentId);
        MpActivityEntity activity = mpActivityService.getById(activityId);
        AssertUtils.notNull(activity, ResultCodeEnum.INVALID_ACTIVITY);

        if(activity.getStatus() != 1){
            throw new CommonException(ResultCodeEnum.INVALID_ACTIVITY);
        }
        MpAgentActivityParticipantEntity relation = agentActivityParticipantService.getParticipantsByActivityAndAgent(activityId, agentId);
        AssertUtils.notNull(relation, ResultCodeEnum.INVALID_ACTIVITY);
        if(StringUtils.isNotBlank(relation.getQrCodeUrl())){
            return relation.getQrCodeUrl();
        }
        MpGenerateQrCodeReq generateQrCodeReq = new MpGenerateQrCodeReq();
        generateQrCodeReq.setSceneStr("agentId=" + agentId + "&activityId=" + activityId);
        generateQrCodeReq.setAppId(req.getAppId());
        generateQrCodeReq.setType(2);
        MpQrCodeResp mpQrCodeResp = officialQrCodeService.generateQrCode(generateQrCodeReq);
        if(StringUtils.isNotEmpty(mpQrCodeResp.getQrCodeUrl())){
            try {
                byte[] bytes = HttpDownloader.downloadBytes(mpQrCodeResp.getQrCodeUrl());
                InputStream inputStream = new ByteArrayInputStream(bytes);
                String url = commonFileService.upload(inputStream,"qrcode", "agent_activity",  MediaType.IMAGE_PNG_VALUE);
                relation.setQrCodeUrl(url);
            }catch (Exception e){
                log.error("download qrcode error", e);
                relation.setQrCodeUrl(mpQrCodeResp.getQrCodeUrl());
            }
        }
        agentActivityParticipantService.updateById(relation);
        return mpQrCodeResp.getQrCodeUrl();
    }


    private AgentActivityParticipantResp convertToDto(MpAgentActivityParticipantEntity entity, Map<Integer, MpActivityEntity> activityInfoMap) {
        AgentActivityParticipantResp resp = new AgentActivityParticipantResp();
        resp.setId(entity.getId());
        resp.setActivityId(entity.getActivityId());
        resp.setAgentId(entity.getAgentId());
        MpActivityEntity activity = activityInfoMap.get(entity.getActivityId());
        if(Objects.nonNull(activity)){
            resp.setActivityName(activity.getActivityName());
        }
        return resp;
    }
}