package com.fs.newAdv.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.newAdv.domain.Lead;
import com.fs.newAdv.enums.SystemEventTypeEnum;
import com.fs.newAdv.event.ConversionEventPublisher;
import com.fs.newAdv.mapper.LeadMapper;
import com.fs.newAdv.service.ILeadService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qwApi.domain.QwExternalContactResult;
import com.fs.qwApi.service.QwApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 域名管理Service实现类
 *
 * @author zhangqin
 * @date 2025-11-06
 */
@Slf4j
@Service
public class LeadServiceImpl extends ServiceImpl<LeadMapper, Lead> implements ILeadService {


    @Autowired
    private ConversionEventPublisher conversionEventPublisher;

    @Autowired
    private QwApiService qwApiService;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;

    @Override
    public Lead getByTraceId(String traceId) {
        List<Lead> list = this.list(new LambdaQueryWrapper<Lead>()
                .eq(Lead::getTraceId, traceId));
        if (list.size() > 1) {
            log.error("查询投流线索信息不唯一:{}", traceId);
        }
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    @Async
    public void updateGroupAddMemberLead(String userId, String chatId, String corpId, String unionid) {
        // 末次归因逻辑
        Lead lead = this.getOne(new LambdaQueryWrapper<Lead>()
                .eq(Lead::getUnionid, unionid)
                .eq(Lead::getAddContactQw, 0)
                .last("LIMIT 1"));
        if (lead != null) {
            lead.setCorpId(corpId);
            lead.setChatId(chatId);
            lead.setUserId(userId);
            lead.setAddContactQw(1);
            this.updateById(lead);

            if (ObjectUtil.isNotEmpty(lead.getLandingPageTs()) && lead.getLandingPageTs().toLocalDate().isEqual(LocalDate.now())) {
                // 当日加群事件回调
                conversionEventPublisher.publishConversionEvent(lead.getTraceId(), SystemEventTypeEnum.GROUP_TODAY);
            }
        } else {
            log.info("用户加群线索信息不存在:{}", userId);
        }


    }

    @Override
    @Async
    public CompletableFuture<String> updateAddMemberLead(String externalUserID, String userID, String corpId, String state) {
        QwExternalContactResult externalContactResult = qwApiService.getExternalcontact(externalUserID, corpId);
        String unionid = externalContactResult.getExternal_contact().getUnionid();
        // 末次归因逻辑
        Lead lead = this.getOne(new LambdaQueryWrapper<Lead>()
                .eq(Lead::getUnionid, unionid)
                .eq(Lead::getAddContactQwGroup, 0)
                .last("LIMIT 1"));
        if (lead != null) {
            lead.setExternalUserId(externalUserID);
            lead.setCorpId(corpId);
            lead.setUserId(userID);
            lead.setAddContactQwGroup(1);
            this.updateById(lead);

            // 绑定企微用户线索关系
            QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalByExternalIdAndCompanyIdToIdAndFs(externalUserID, userID, corpId);
            if (qwExternalContact != null){
                QwExternalContact temp = new QwExternalContact();
                temp.setId(qwExternalContact.getId());
                temp.setTraceId(lead.getTraceId());
                qwExternalContactMapper.updateById(temp);
            }else {
                log.info("广告归因企微用户信息不存在:{} {} {} ", externalUserID, userID,corpId);
            }
            if (ObjectUtil.isNotEmpty(lead.getLandingPageTs()) && lead.getLandingPageTs().toLocalDate().isEqual(LocalDate.now())) {
                // 当日加微事件回调
                conversionEventPublisher.publishConversionEvent(lead.getTraceId(), SystemEventTypeEnum.WEI_CHAT_TODAY);
            }
            return CompletableFuture.completedFuture(lead.getTraceId());
        } else {
            log.info("广告归因线索不存在:{} {} {}", externalUserID, userID,corpId);
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    @Async
    public void weChatAuthorizationLead(String traceId, String unionId, String mpOpenId, String phone) {
       try{
           Lead byTraceId = this.getByTraceId(traceId);
           if (byTraceId == null) {
               return;
           }
           this.update(new LambdaUpdateWrapper<Lead>()
                   .eq(Lead::getTraceId, traceId)
                   .set(Lead::getUnionid, unionId)
                   .set(Lead::getPhone, phone)
                   .set(Lead::getOpenid, mpOpenId)
                   .set(Lead::getMiniAuth, 1));
           if (ObjectUtil.isNotEmpty(byTraceId.getLandingPageTs()) && byTraceId.getLandingPageTs().toLocalDate().isEqual(LocalDate.now())) {
               // 微信授权且当日创建事件
               conversionEventPublisher.publishConversionEvent(traceId, SystemEventTypeEnum.AUTH_TODAY_CREATE);
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    @Override
    @Async
    public void updateAuthIndex(String traceId, Integer type) {
        LambdaUpdateWrapper<Lead> eq = new LambdaUpdateWrapper<Lead>().eq(Lead::getTraceId, traceId);
        if (type == 1) {
            eq.set(Lead::getMiniAuthIndex, 1);
        } else if (type == 2) {
            eq.set(Lead::getMiniQrCodeIndex, 1);
        }
        boolean update = this.update(eq);
        if (!update) {
            log.error("更新授权页标识失败:{}", traceId);
        }
    }

    @Override
    public void updateAuthIndex(String traceId) {
        boolean update = this.update(new LambdaUpdateWrapper<Lead>()
                .eq(Lead::getTraceId, traceId)
                .set(Lead::getMiniLaunchIndexCount, 1));
        if (!update){
            log.error("发起进入小程序失败:{}", traceId);
        }
    }

    @Override
    public List<Lead> getToDayGroupNum() {
        return this.baseMapper.getToDayGroupNum();
    }

    @Override
    public List<Lead> getYesterdayGroupNum() {
        return this.baseMapper.getYesterdayGroupNum();
    }

    @Override
    public List<Lead> getToDayWeiChatNum() {
        return this.baseMapper.getToDayWeiChatNum();
    }

    @Override
    public List<Lead> getYesterdayWeiChatNum() {
        return this.baseMapper.getYesterdayWeiChatNum();
    }
}

