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.entity.vv.VvAllDataEntity;
import com.heyu.api.data.entity.vv.VvChartConfigEntity;
import com.heyu.api.utils.ChartUtil;
import com.heyu.api.data.utils.ExpressionParse;
import com.heyu.api.data.utils.GouDeZhaoDDUtils;
import com.heyu.api.data.utils.LineChartDTO;
import com.heyu.api.oss.OssFileUploadService;
import com.heyu.api.oss.OssUploadResult;
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.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class SendDingDingQueueSimpleRabbitListener {


    @Autowired
    private VvAllDataDao vvAllDataDao;

    @Autowired
    private ChartUtil chartUtil;

    @Autowired
    private OssFileUploadService ossFileUploadService;

    @RabbitHandler
    @RabbitListener(queues = "#{sendDingDingQueue.name}", containerFactory = "accountAmountQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        try {


            log.info("SendDingDingQueueSimpleRabbitListener请求参数是message :{}", message);

            VvChartConfigEntity vvChartConfigEntity = JSONObject.parseObject(message, VvChartConfigEntity.class);
            String configSql = vvChartConfigEntity.getSqlConfig();
            String paramsConfig = vvChartConfigEntity.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);
            String headerName = vvChartConfigEntity.getHeaderTitle();
            String xName = vvChartConfigEntity.getYTitle();
            String yName = vvChartConfigEntity.getYTitle();

            List<LineChartDTO> list = new ArrayList<>();

            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);
                    LineChartDTO lineChartDTO = new LineChartDTO();
                    lineChartDTO.setName(vvAllDataEntity.getName());
                    lineChartDTO.setX(vvAllDataEntity.getX());
                    lineChartDTO.setY(vvAllDataEntity.getY());
                    list.add(lineChartDTO);
                }
            }
            String chartPic = chartUtil.makeLineAndShapeChart2(headerName, xName, yName, list);

            File file1 = new File(chartPic);

            String picUrl = "repayPic/repayChart" +System.currentTimeMillis()+ ".jpg";

            InputStream inputStream = new FileInputStream(file1);

            OssUploadResult ossUploadResult = ossFileUploadService.uploadImageToOss(inputStream, picUrl, Integer.parseInt(String.valueOf(file1.length())));

            file1.delete();

            String url = ossUploadResult.getUrl();
            log.info("SendDingDingQueueSimpleRabbitListener chartPic :{} url:{}",chartPic,url);
            GouDeZhaoDDUtils.sendMarkDownOrder(headerName,url);

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