package net.northking.cctp.dw.bus;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.dw.api.service.MtCaseDesignApiService;
import net.northking.cctp.dw.constant.DWConstant;
import net.northking.cctp.dw.db.entity.MtCaseDesignChart;
import net.northking.cctp.dw.db.service.MtCaseDesignChartService;
import net.northking.cctp.dw.dto.DwCaseDesignInfoDto;
import net.northking.cctp.dw.dto.DwCaseDesignInfoUpdateDto;
import net.northking.cctp.dw.utils.DateDealUtils;
import net.northking.cctp.platform.db.entity.CltDictItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.stream.Collectors;


//@Component
public class CaseDesginDataListener {

    private final static Logger logger = LoggerFactory.getLogger(CaseDesginDataListener.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private MtCaseDesignApiService mtCaseDesignApiService;

    @Autowired
    private MtCaseDesignChartService mtCaseDesignChartService;


    /**
     * 处理用例设计进度图
     *
     * @param dataList
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = DWConstant.MQ_HANDLE_DATA_EXCHANGE, type = ExchangeTypes.TOPIC),
            value = @Queue(name = DWConstant.BugQueue.CASE_DESGIN_COMPLETE_PRODUCER_DATA_QUEUE),
            key = DWConstant.BugRoutingKey.CASE_DESGIN_COMPLETE_PRODUCER_DATA))
    public void caseDesginCompleteDataListener(List<DwCaseDesignInfoDto> dataList) {
        logger.info("==================caseDesginCompleteDataListener======================开始消费");
        if (dataList != null && !dataList.isEmpty()) {
            // 获取系统id
            List<String> projectIds = dataList.stream().map(DwCaseDesignInfoDto::getProjectId).collect(Collectors.toList());
            DwCaseDesignInfoDto dwCaseDesignInfoDto = new DwCaseDesignInfoDto();
            dwCaseDesignInfoDto.setTenantId(dataList.get(0).getTenantId());
            dwCaseDesignInfoDto.setProjectIds(projectIds);
            // 处理用例设计进度图
            transactionTemplate.execute(status -> {
                // 首先删除数据
                mtCaseDesignApiService.deleteCompleteByProjectIds(dwCaseDesignInfoDto);
                // 再插入数据
                dwCaseDesignInfoDto.setLastSat(DateDealUtils.getLastSat());
                mtCaseDesignApiService.caseDesignComplete(dwCaseDesignInfoDto);

                return Boolean.TRUE;
            });
        }
        logger.info("==================caseDesginCompleteDataListener======================结束消费");
    }

    /**
     * 处理用例设计统计图
     *
     * @param dataList
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = DWConstant.MQ_HANDLE_DATA_EXCHANGE, type = ExchangeTypes.TOPIC),
            value = @Queue(name = DWConstant.BugQueue.CASE_DESGIN_CHART_PRODUCER_DATA_QUEUE),
            key = DWConstant.BugRoutingKey.CASE_DESGIN_CHART_PRODUCER_DATA))
    public void caseDesginChartDataListener(List<DwCaseDesignInfoDto> dataList) {
        logger.info("==================caseDesginChartDataListener======================开始消费");
        if (dataList != null && !dataList.isEmpty()) {
            // 获取系统id
            List<String> projectIds = dataList.stream().map(DwCaseDesignInfoDto::getProjectId).collect(Collectors.toList());
            DwCaseDesignInfoDto dwCaseDesignInfoDto = new DwCaseDesignInfoDto();
            dwCaseDesignInfoDto.setTenantId(dataList.get(0).getTenantId());
            dwCaseDesignInfoDto.setProjectIds(projectIds);
            // 处理用例设计统计图
            if (redisTemplate.opsForValue().get("UITEST-dict::" + dwCaseDesignInfoDto.getTenantId() + ":caseType") != null) {
                transactionTemplate.execute(status -> {
                    // 每次导入数据之前先清空表数据
                    MtCaseDesignChart mtCaseDesignChart = new MtCaseDesignChart();
                    mtCaseDesignChart.setCreatedTime(DateDealUtils.getCurrentDate());
                    mtCaseDesignChart.setProjectIds(projectIds);
                    mtCaseDesignChartService.deleteByExampleByProjectIds(mtCaseDesignChart);
                    // 再插入数据
                    List<CltDictItem> cltDictItems = JSON.parseArray(JSON.toJSONString(redisTemplate.opsForValue().get("UITEST-dict::" + dwCaseDesignInfoDto.getTenantId() + ":caseType")), CltDictItem.class);
                    DwCaseDesignInfoUpdateDto dwCaseDesignInfoUpdateDto = new DwCaseDesignInfoUpdateDto();
                    dwCaseDesignInfoUpdateDto.setProjectIds(projectIds);
                    dwCaseDesignInfoUpdateDto.setDictItems(cltDictItems);
                    dwCaseDesignInfoUpdateDto.setTenantId(dwCaseDesignInfoDto.getTenantId());
                    mtCaseDesignChartService.syncDesignNoticeByProjectIds(dwCaseDesignInfoUpdateDto);

                    return Boolean.TRUE;
                });
            }
        }
        logger.info("==================caseDesginChartDataListener======================结束消费");
    }


}
