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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.admin.controller.req.AgentActivityParticipantQueryReq;
import com.seer.teach.mp.admin.controller.req.AgentActivityParticipantReq;
import com.seer.teach.mp.admin.controller.req.AgentGenerateQrCodeReq;
import com.seer.teach.mp.admin.controller.resp.AdminAgentActivityParticipantResp;
import com.seer.teach.mp.admin.controller.resp.AdminAgentQrCodeResp;
import com.seer.teach.mp.admin.convert.AdminAgentActivityParticipantConvert;
import com.seer.teach.mp.admin.service.AdminOfficialQrCodeService;
import com.seer.teach.mp.admin.service.IAdminAgentActivityRelationService;
import com.seer.teach.mp.entity.MpActivityEntity;
import com.seer.teach.mp.entity.MpAgentActivityParticipantEntity;
import com.seer.teach.mp.entity.MpAgentEntity;
import com.seer.teach.mp.service.IMpActivityService;
import com.seer.teach.mp.service.IMpAgentActivityParticipantService;
import com.seer.teach.mp.service.IMpAgentService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 代理商活动参与记录表 管理端服务实现类
 * </p>
 *
 * @author
 * @since 2025-12-30
 */
@Service
@RequiredArgsConstructor
public class AdminAgentActivityRelationServiceImpl implements IAdminAgentActivityRelationService {

    private final IMpAgentActivityParticipantService mpAgentActivityParticipantService;

    private final IMpAgentService mpAgentService;

    private final IMpActivityService mpActivityService;

    private final AdminOfficialQrCodeService officialQrCodeService;

    @Override
    public PageListBean<AdminAgentActivityParticipantResp> pageList(AgentActivityParticipantQueryReq query) {
        Page<MpAgentActivityParticipantEntity> page = new Page<>(query.getPageNum(), query.getPageSize());

        LambdaQueryWrapper<MpAgentActivityParticipantEntity> wrapper = new LambdaQueryWrapper<>();
        // 根据活动ID查询
        if (query.getActivityName() != null) {
            wrapper.like(MpAgentActivityParticipantEntity::getActivityName, query.getActivityName());
        }
        // 根据代理商ID查询
        if (query.getAgentName() != null) {
            wrapper.like(MpAgentActivityParticipantEntity::getAgentName, query.getAgentName());
        }
        if (query.getAgentId() != null) {
            wrapper.eq(MpAgentActivityParticipantEntity::getAgentId, query.getAgentId());
        }
        Page<MpAgentActivityParticipantEntity> result = mpAgentActivityParticipantService.page(page, wrapper);
        return PageConverterUtils.convertPageListBean(result, AdminAgentActivityParticipantConvert.INSTANCE::convertToRespList);
    }


    @Override
    public boolean saveParticipant(AgentActivityParticipantReq req) {
        // 检查是否已存在相同的活动、代理商和家长记录
        LambdaQueryWrapper<MpAgentActivityParticipantEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MpAgentActivityParticipantEntity::getActivityId, req.getActivityId())
                .eq(MpAgentActivityParticipantEntity::getAgentId, req.getAgentId());

        long count = mpAgentActivityParticipantService.count(wrapper);
        if (count > 0) {
            throw new RuntimeException("该代理商活动参与记录已存在");
        }
        MpAgentActivityParticipantEntity result = AdminAgentActivityParticipantConvert.INSTANCE.convertToEntity(req);
        return mpAgentActivityParticipantService.save(result);
    }

    @Override
    public boolean updateParticipant(MpAgentActivityParticipantEntity entity) {
        // 检查是否存在相同的活动、代理商和家长记录（排除当前记录）
        LambdaQueryWrapper<MpAgentActivityParticipantEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MpAgentActivityParticipantEntity::getActivityName, entity.getActivityName())
                .eq(MpAgentActivityParticipantEntity::getAgentName, entity.getAgentName())
                .ne(MpAgentActivityParticipantEntity::getId, entity.getId());

        long count = mpAgentActivityParticipantService.count(wrapper);
        if (count > 0) {
            throw new RuntimeException("该代理商活动参与记录已存在");
        }
        Integer agentId = mpAgentService.lambdaQuery().eq(MpAgentEntity::getAgentName, entity.getAgentName()).one().getId();
        Integer activityId = mpActivityService.lambdaQuery().eq(MpActivityEntity::getActivityName, entity.getActivityName()).one().getId();
        entity.setActivityId(activityId);
        entity.setAgentId(agentId);
        return mpAgentActivityParticipantService.updateById(entity);
    }

    @Override
    public AdminAgentActivityParticipantResp getById(Integer id) {
        MpAgentActivityParticipantEntity entity = mpAgentActivityParticipantService.getById(id);
        return AdminAgentActivityParticipantConvert.INSTANCE.convertToResp(entity);
    }

    @Override
    public Boolean deleteById(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return mpAgentActivityParticipantService.removeByIds(ids);
    }

    @Override
    public String getQrCode(Integer agentId, Integer activityId, String appId, Integer userId) {
        MpActivityEntity activity = mpActivityService.getById(activityId);
        AssertUtils.notNull(activity, ResultCodeEnum.INVALID_ACTIVITY);

        if (activity.getStatus() != 1) {
            throw new CommonException(ResultCodeEnum.INVALID_ACTIVITY);
        }
        MpAgentActivityParticipantEntity relation = mpAgentActivityParticipantService.getParticipantsByActivityAndAgent(activityId, agentId);
        AssertUtils.notNull(relation, ResultCodeEnum.INVALID_ACTIVITY);
        if (StringUtils.isNotBlank(relation.getQrCodeUrl())) {
            return relation.getQrCodeUrl();
        }
        AgentGenerateQrCodeReq req = new AgentGenerateQrCodeReq();
        req.setSceneStr("agentId=" + agentId + "&activityId=" + activityId);
        req.setAppId(appId);
        req.setType(2);
        AdminAgentQrCodeResp QrCodeResp = officialQrCodeService.generateQrCode(req);
        relation.setQrCodeUrl(QrCodeResp.getQrCodeUrl());
        mpAgentActivityParticipantService.updateById(relation);
        return QrCodeResp.getQrCodeUrl();
    }

}