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

import cn.hutool.core.bean.BeanUtil;
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.api.entity.JgBizChangeLog;
import com.yeejoin.amos.boot.module.jg.biz.dao.ESDataChangeLogDao;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgBizChangeLogServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import org.typroject.tyboot.core.foundation.context.RequestContextModel;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
import java.util.stream.IntStream;

/**
 * @author Administrator
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ChangeLogInsertListener {

    private static final Map<String, String> bizTypeTableMap = new HashMap<>();

    static {
        bizTypeTableMap.put("useRegister", "tzs_jg_use_registration");
        bizTypeTableMap.put("singleManageEquipEdit", "idx_biz_jg_use_info");
    }

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

    private final ESDataChangeLogDao esDataChangeLogDao;

    private final JgBizChangeLogServiceImpl bizChangeLogService;


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


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

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        IntStream.range(0, threadNumber).forEach(i -> {
            executorService.execute(() -> {
                while (true) {
                    try {
                        ChangeDataEvent event = queue.take();
                        processEvent(event);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });
        });
    }

    private void processEvent(ChangeDataEvent event) {
        List<ChangeDataDto> changeDataDtos = event.getData();
        RequestContextModel requestContextModel = event.getRequestContext();
        Date date = new Date();
        // 1.主表保存
        JgBizChangeLog changeLog = saveLog(event);
        // 2.子表字段保存
        List<ESDataChangeLogDto> logs = saveColumnsChange2Es(changeDataDtos, requestContextModel, date, changeLog);
        log.info("es 操作日志数据入库成功：{}条", logs.size());
    }

    private List<ESDataChangeLogDto> saveColumnsChange2Es(List<ChangeDataDto> changeDataDtos, RequestContextModel requestContextModel, Date date, JgBizChangeLog changeLog) {
        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(changeLog.getSequenceNbr() + "");
            return changeLogDto;
        }).collect(Collectors.toList());
        if (!logs.isEmpty()) {
            esDataChangeLogDao.saveAll(logs);
        }
        return logs;
    }

    private JgBizChangeLog saveLog(ChangeDataEvent event) {
        JgBizChangeLog changeLog = new JgBizChangeLog();
        BeanUtil.copyProperties(event.getBizRelationData(), changeLog);
        changeLog.setBizTable(bizTypeTableMap.get(changeLog.getBizType()));
        changeLog.setRecDate(new Date());
        changeLog.setRecUserId(event.getRequestContext().getExcutedUserId());
        // todo 使用上下文这个作为id 便于其他业务和其进行关联
        changeLog.setSequenceNbr(Long.parseLong(event.getRequestContext().getTraceId()));
        bizChangeLogService.getBaseMapper().insert(changeLog);
        return changeLog;
    }
}
