package com.yeejoin.amos.boot.module.jg.biz.event.listener;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.api.dto.ChangeDataDto;
import com.yeejoin.amos.boot.module.jg.api.dto.ESDataChangeLogDto;
import com.yeejoin.amos.boot.module.jg.biz.dao.ESDataChangeLogDao;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContextModel;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class ChangeDataEventListener {

    @Value("${changeData.deal.thread.number:1}")
    private int threadNumber;

    private final ESDataChangeLogDao esDataChangeLogDao;

    private final BlockingQueue<ChangeDataEvent> queue = new LinkedBlockingQueue<>();

    public ChangeDataEventListener(ESDataChangeLogDao esDataChangeLogDao) {
        this.esDataChangeLogDao = esDataChangeLogDao;

    }

    @EventListener(value = ChangeDataEvent.class)
    public void handleTransactionalEvent(ChangeDataEvent event) {
        log.info("收到用户变更业务数据消息:{}", JSONObject.toJSONString(event));
        queue.add(event);
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        ChangeDataEvent event = queue.take();
                        this.dealData(event);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }

    private void dealData(ChangeDataEvent event) {
        List<ChangeDataDto> changeDataDtos = event.getData();
        RequestContextModel requestContextModel = event.getRequestContext();
        Date date = new Date();
        List<ESDataChangeLogDto> logs = changeDataDtos.parallelStream().map(changeDataDto -> {
            ESDataChangeLogDto changeLogDto = new ESDataChangeLogDto();
            changeLogDto.setColumnKey(changeDataDto.getColumnKey());
            changeLogDto.setColumnKeyLabel(changeDataDto.getColumnLabel());
            changeLogDto.setBeforeData(changeDataDto.getColumnOldValue());
            changeLogDto.setAfterData(changeDataDto.getColumnNewValue());
            changeLogDto.setUserId(requestContextModel.getExcutedUserId());
            changeLogDto.setCreateDate(date.getTime());
            changeLogDto.setRequestDate(DateUtil.formatDateTime(date));
            changeLogDto.setChangeId(changeDataDto.getChangeId());
            changeLogDto.setColumnFamily(changeDataDto.getColumnFamily());
            changeLogDto.setBizType(changeDataDto.getBizType());
            changeLogDto.setBatchId(requestContextModel.getTraceId());
            return changeLogDto;
        }).collect(Collectors.toList());
        esDataChangeLogDao.saveAll(logs);
        log.info("es 操作日志数据入库成功：{}条", logs.size());
    }
}
