package net.northking.cctp.testbug.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseWriteOnly;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.testbug.constants.MQConstant;
import net.northking.cctp.testbug.db.entity.MqSynchronizeTask;
import net.northking.cctp.testbug.db.service.MqSynchronizeTaskService;
import net.northking.cctp.testbug.dto.SynBugInfoDto;
import net.northking.cctp.testbug.schedule.service.ScheduleService;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private MqSynchronizeTaskService mqSynchronizeTaskService;
    /**
     * 日志
     */
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ScheduleServiceImpl.class);

    @Override
    public void syncBugInfo() {
        QueryByPage<MqSynchronizeTask> queryByPage = new QueryByPage<>();
        queryByPage.setPageNo(1);
        queryByPage.setPageSize(500);
        Pagination<MqSynchronizeTask> objectPagination = mqSynchronizeTaskService.pagingQueryNew(queryByPage);
        if (objectPagination.getRecordCount() == 0) {
            return;
        } else {
            List<MqSynchronizeTask> records = objectPagination.getRecords();
            if (!records.isEmpty()) {
                List<MqSynchronizeTask> resut = handleBugInfoData(records);
                // 每20条处理一次
                int count = 20;
                Integer num = resut.size();
                for (int i = 0; i < num / count + 1; i++) {
                    if (i * count == num) {
                        break;
                    }
                    int stop = (i + 1) * count > num ? num : (i + 1) * count;
                    List<MqSynchronizeTask> dataList = resut.subList(i * count, stop);
                    handleBugInfo(dataList);
                }
            }
            int pageCount = objectPagination.getPageCount();
            for (int index = 1; index < pageCount; index++) {
                queryByPage.setPageNo(index + 1);
                queryByPage.setPageSize(500);
                Pagination<MqSynchronizeTask> pagination = mqSynchronizeTaskService.pagingQueryNew(queryByPage);
                List<MqSynchronizeTask> queryList = pagination.getRecords();
                if (!queryList.isEmpty()) {
                    List<MqSynchronizeTask> resut = handleBugInfoData(queryList);
                    // 每20条处理一次
                    int count = 20;
                    Integer num = resut.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<MqSynchronizeTask> dataList = resut.subList(i * count, stop);
                        handleBugInfo(dataList);
                    }
                }
            }
        }
    }

    /**
     * 处理重复的bugId
     *
     * @param queryList
     * @return
     */
    private List<MqSynchronizeTask> handleBugInfoData(List<MqSynchronizeTask> queryList) {
        // 需要删除的ids
        List<Object> ids = new ArrayList<>();
        List<MqSynchronizeTask> result = new ArrayList<>();
        for (MqSynchronizeTask item : queryList) {
            SynBugInfoDto synBugInfoDto = JSON.parseObject(item.getTaskInfo(), SynBugInfoDto.class);
            item.setBugId(synBugInfoDto.getBugId());
        }
        // 根据bugId进行分组
        Map<String, List<MqSynchronizeTask>> collect = queryList.stream().collect(Collectors.groupingBy(MqSynchronizeTask::getBugId));
        collect.forEach((key, value) -> {
            if (value.size() > 1) {
                // 表示有重复的bug_id
                // 根据created进行排序
                List<MqSynchronizeTask> list = value.stream().sorted(Comparator.comparing(MqSynchronizeTask::getCreatedTime)).collect(Collectors.toList());
                for (int index = 0; index < list.size() - 1; index++) {
                    ids.add(list.get(index).getId());
                }
                result.add(list.get(list.size() - 1));
            } else {
                result.add(value.get(0));
            }
        });
        // 将多余的数据删除
        if (!ids.isEmpty()) {
            mqSynchronizeTaskService.deleteByPrimaryKeys(ids);
        }
        return result;
    }

    /**
     * 处理缺陷的同步问题
     *
     * @param bugInfoList
     */
    @DatabaseWriteOnly
    private void handleBugInfo(List<MqSynchronizeTask> bugInfoList) {
        // 将数据转为javabean格式
        List<SynBugInfoDto> queryList = new ArrayList<>();
        List<Object> mqSynchronizeTaskIds = new ArrayList<>();
        for (MqSynchronizeTask item : bugInfoList) {
            String taskInfo = item.getTaskInfo();
            SynBugInfoDto synBugInfoDto = JSON.parseObject(taskInfo, SynBugInfoDto.class);
            queryList.add(synBugInfoDto);
            mqSynchronizeTaskIds.add(item.getId());
        }
        // 发送消息
        amqpTemplate.convertAndSend(MQConstant.MQ_SYNCHRONIZATION_DATA_EXCHANGE, MQConstant.RoutingKey.SYN_BUG_INFO, queryList);
        // 将原数据删除
        mqSynchronizeTaskService.deleteByPrimaryKeys(mqSynchronizeTaskIds);
    }

}
