package com.tzld.piaoquan.api.job.contentplatform;

import com.aliyun.odps.data.Record;
import com.tzld.piaoquan.api.common.enums.contentplatform.ContentPlatformGzhPlanTypeEnum;
import com.tzld.piaoquan.api.common.enums.contentplatform.QwPlanTypeEnum;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformIllegalMsgMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformIllegalVideoMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ext.ContentPlatformPlanMapperExt;
import com.tzld.piaoquan.api.model.po.contentplatform.*;
import com.tzld.piaoquan.growth.common.utils.DateUtil;
import com.tzld.piaoquan.growth.common.utils.OdpsUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ContentPlatformIllegalVideoJob {

    @Resource
    private ContentPlatformIllegalVideoMapper illegalVideoMapper;
    @Resource
    private ContentPlatformIllegalMsgMapper illegalMsgMapper;
    @Resource
    private ContentPlatformPlanMapperExt planMapperExt;

    @XxlJob("checkContentPlatformIllegalVideoJob")
    public ReturnT<String> checkContentPlatformIllegalVideoJob(String param) {
        String dtMin = DateUtil.getBeforeDayDateString(1, "yyyyMMdd") + "000000";
        if (StringUtils.isNotBlank(param)) {
            dtMin = param;
        }
        String sql = String.format("select dt, content, title from loghubods.wxgzh_message_log_per5min where dt > %s and title like '%%封禁%%';", dtMin);
        List<Record> dataList = OdpsUtil.getOdpsData(sql);
        Long now = System.currentTimeMillis();
        if (CollectionUtils.isNotEmpty(dataList)) {
            List<ContentPlatformIllegalVideo> saveList = new ArrayList<>();
            for (Record record : dataList) {
                ContentPlatformIllegalVideo item = new ContentPlatformIllegalVideo();
                Long dt = Long.parseLong((String) record.get(0));
                String content = (String) record.get(1);
                String title = (String) record.get(2);
                item.setDateStr(String.valueOf(dt));
                String videoId = getVideoIdFromContent(content);
                if (Objects.isNull(videoId)) {
                    continue;
                }
                item.setVideoId(Long.parseLong(videoId));
                item.setContent(content);
                item.setTitle(title);
                item.setCreateTimestamp(now);
                saveList.add(item);
            }
            List<Long> videoIdList = saveList.stream().map(ContentPlatformIllegalVideo::getVideoId).collect(Collectors.toList());
            List<ContentPlatformIllegalVideo> existIllegalVideo = getIllegalVideoList(videoIdList);
            List<Long> existVideoIdList = existIllegalVideo.stream().map(ContentPlatformIllegalVideo::getVideoId).collect(Collectors.toList());
            List<ContentPlatformIllegalVideo> filterList = saveList.stream().filter(item -> !existVideoIdList.contains(item.getVideoId())).collect(Collectors.toList());
            // save
            if (CollectionUtils.isNotEmpty(filterList)) {
                planMapperExt.batchInsertContentPlatformIllegalVideo(filterList);
            }
        }
        // 发送违规通知
        sendIllegalVideoNotify(dtMin);

        return ReturnT.SUCCESS;
    }

    private void sendIllegalVideoNotify(String dtMin) {
        List<ContentPlatformIllegalVideo> illegalVideoList = getIllegalVideoListByDt(dtMin);
        if (CollectionUtils.isEmpty(illegalVideoList)) {
            return;
        }
        for (ContentPlatformIllegalVideo item : illegalVideoList) {
            // 公众号-自动回复、公众号-服务号推送、公众号-公众号推送、企微-社群、企微-自动回复
            List<PlanIllegalVideoDTO> gzhPlanIllegalVideoList = planMapperExt.getGzhPlanIllegalVideoList(item.getVideoId());
            List<PlanIllegalVideoDTO> qwPlanIllegalVideoList = planMapperExt.getQwPlanIllegalVideoList(item.getVideoId());
            List<PlanIllegalVideoDTO> allPlanIllegalVideoList = new ArrayList<>();
            allPlanIllegalVideoList.addAll(gzhPlanIllegalVideoList);
            allPlanIllegalVideoList.addAll(qwPlanIllegalVideoList);
            if (CollectionUtils.isEmpty(allPlanIllegalVideoList)) {
                continue;
            }
            Map<Long, Map<Long, List<PlanIllegalVideoDTO>>> accountVideoPlanMap = allPlanIllegalVideoList.stream()
                    .collect(Collectors.groupingBy(PlanIllegalVideoDTO::getAccountId, Collectors.groupingBy(PlanIllegalVideoDTO::getVideoId)));
            for (Map.Entry<Long, Map<Long, List<PlanIllegalVideoDTO>>> accountEntry : accountVideoPlanMap.entrySet()) {
                Long accountId = accountEntry.getKey();
                Map<Long, List<PlanIllegalVideoDTO>> videoPlanMap = accountEntry.getValue();
                for (Map.Entry<Long, List<PlanIllegalVideoDTO>> videoEntry : videoPlanMap.entrySet()) {
                    Long videoId = videoEntry.getKey();
                    List<PlanIllegalVideoDTO> planList = videoEntry.getValue();
                    // 发送通知
                    sendNotifyMsg(accountId, videoId, planList);
                }
            }
        }
    }

    private void sendNotifyMsg(Long accountId, Long videoId, List<PlanIllegalVideoDTO> planList) {
        ContentPlatformIllegalMsg existMsg = getIllegalMsg(accountId, videoId);
        if (Objects.nonNull(existMsg)) {
            return;
        }
        Set<String> businessTypeList = new HashSet<>();
        for (PlanIllegalVideoDTO plan : planList) {
            String channel = plan.getChannel();
            if (StringUtils.equals(channel, "公众号")) {
                // 公众号-自动回复、公众号-服务号推送、公众号-公众号推送
                ContentPlatformGzhPlanTypeEnum gzhPlanTypeEnum = ContentPlatformGzhPlanTypeEnum.from(plan.getType());
                businessTypeList.add("“" + channel + "-" + gzhPlanTypeEnum.getDescription() + "”");
            } else if (StringUtils.equals(channel, "企微")) {
                // 企微-社群、企微-自动回复
                QwPlanTypeEnum qwPlanTypeEnum = QwPlanTypeEnum.from(plan.getType());
                businessTypeList.add("“" + channel + "-" + qwPlanTypeEnum.getDescription() + "”");
            }
        }
        String businessType = String.join("、", businessTypeList);
        Long now = System.currentTimeMillis();
        ContentPlatformIllegalMsg illegalMsg = new ContentPlatformIllegalMsg();
        illegalMsg.setAccountId(accountId);
        illegalMsg.setVideoId(videoId);
        illegalMsg.setTitle(planList.get(0).getTitle());
        illegalMsg.setBusinessType(businessType);
        String videoTitle = illegalMsg.getTitle();
        if (videoTitle.length() >= 20) {
            videoTitle = videoTitle.substring(0, 19) + "...";
        }
        illegalMsg.setIllegalTitle("视频“" + videoTitle + "”被封禁，请及时替换");
        illegalMsg.setIllegalContent("您在" + illegalMsg.getBusinessType() + "栏目中使用的视频“" +
                videoTitle + "”（视频ID：" + illegalMsg.getVideoId() + "）被微信封禁，请及时替换为其他视频。");
        illegalMsg.setStatus(0);
        illegalMsg.setCreateTimestamp(now);
        illegalMsg.setUpdateTimestamp(now);
        illegalMsgMapper.insertSelective(illegalMsg);
    }

    private ContentPlatformIllegalMsg getIllegalMsg(Long accountId, Long videoId) {
        ContentPlatformIllegalMsgExample example = new ContentPlatformIllegalMsgExample();
        example.createCriteria().andAccountIdEqualTo(accountId).andVideoIdEqualTo(videoId);
        List<ContentPlatformIllegalMsg> list = illegalMsgMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    private List<ContentPlatformIllegalVideo> getIllegalVideoListByDt(String dtMin) {
        ContentPlatformIllegalVideoExample example = new ContentPlatformIllegalVideoExample();
        example.createCriteria().andDateStrGreaterThan(dtMin);
        return illegalVideoMapper.selectByExample(example);
    }

    private List<ContentPlatformIllegalVideo> getIllegalVideoList(List<Long> videoIdList) {
        ContentPlatformIllegalVideoExample example = new ContentPlatformIllegalVideoExample();
        example.createCriteria().andVideoIdIn(videoIdList);
        return illegalVideoMapper.selectByExample(example);
    }


    public static String getVideoIdFromContent(String content) {
        if (content == null || content.isEmpty()) {
            return null;
        }
        // 匹配 "id=数字" 部分
        Pattern pattern = Pattern.compile("id%3D(\\d+)");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

}
