package com.heyu.api.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heyu.api.data.dao.vv.VvAllDataDao;
import com.heyu.api.data.dto.VvCreateDataConfigDTO;
import com.heyu.api.data.entity.vv.VvAllDataEntity;
import com.heyu.api.data.utils.ExpressionParse;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CreateDataQueueSimpleRabbitListener {

    @Value("${eb.config.rabbitQueue.createDataQueue}")
    private String createDataQueue;

    @Autowired
    private VvAllDataDao vvAllDataDao;

    @RabbitHandler
    @RabbitListener(queues = "#{createDataQueue.name}", containerFactory = "accountAmountQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        try {
            log.info("CreateDataQueueSimpleRabbitListener 请求参数是message :{}", message);
            VvCreateDataConfigDTO vvCreateDataConfigDTO = JSONObject.parseObject(message, VvCreateDataConfigDTO.class);
            VvAllDataEntity vvAllData = vvAllDataDao.selectVvAllDataByRunIdRunDate(vvCreateDataConfigDTO.getId(), vvCreateDataConfigDTO.getRunDate());
            if (vvAllData != null) {
                return;
            }

            String configSql = vvCreateDataConfigDTO.getSqlConfig();
            String paramsConfig = vvCreateDataConfigDTO.getParamsConfig();
            Map valuesMap = new HashMap();
            Map<String,Object> paramMap = JSONObject.parseObject(paramsConfig, Map.class);
            for(Map.Entry<String,Object> entry : paramMap.entrySet()){
                valuesMap.put(entry.getKey(), ExpressionParse.getValue(entry.getValue() + ""));
            }
            StrSubstitutor sub = new StrSubstitutor(valuesMap);
            String resolvedString = sub.replace(configSql);
            List<Map<String, Object>> mapList = vvAllDataDao.selectSQL(resolvedString);
            if (!CollectionUtils.isEmpty(mapList)) {
                for (Map<String, Object> objectMap : mapList) {
                    VvAllDataEntity vvAllDataEntity = JSONObject.parseObject(JSON.toJSONString(objectMap), VvAllDataEntity.class);
                    vvAllDataEntity.setCreateTimestamp(System.currentTimeMillis());
                    vvAllDataEntity.setRunId(vvCreateDataConfigDTO.getId()+"");
                    vvAllDataEntity.setRunDate(vvCreateDataConfigDTO.getRunDate());
                    vvAllDataDao.insert(vvAllDataEntity);
                }
            }

        } catch (Exception e) {
            log.error("urlStatisticQueue handle", e);
        } finally {
            try {
                log.info("urlStatisticQueue消息{},消息确认完成", message);
                channel.basicAck(delivertTag, true);
            } catch (IOException e) {
                log.error("urlStatisticQueue消息确认异常", e);
            }
        }
    }
}
