package com.dxhy.extend.rabbitmq;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.excelExport.TDxExcelExportlog;
import com.dxhy.auth.config.UserCenterConfig;
import com.dxhy.common.constant.RabbitMqConstant;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.HttpUtils;
import com.dxhy.extend.dao.TDxExcelExportlogExtendDao;
import com.dxhy.extend.entity.ExtSysMessagecontrol;
import com.dxhy.extend.model.BigBSendMesReq;
import com.dxhy.extend.service.messagecontrol.ExtMessageControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Receiver.class 推送erp消息队列， 消费者 用于处理消息
 *
 * @author dxhy
 */
@Component
@Slf4j
public class ExtReceiver  extends AbstractController {

    @Resource
    private ExtMessageControlService messageControlService;

    @Resource
    private UserCenterConfig userCenterConfig;

    @Value("${jxpt.url}")
    private String jxptBaseUrl;

    @Autowired
    private TDxExcelExportlogExtendDao tDxExcelExportlogExtendDao;


    /**
     * 导出消费者
     *
     * @param message
     *            入参
     */
    @RabbitHandler
    @RabbitListener(queues = RabbitMqConstant.TO_MSG_EXCEL_APPLY)
    public void handleMessageOne(String message) {
        log.debug("接收的消息为:{}", message);
        try {
            if (message != null) {
                JSONObject jsStr = JSONObject.parseObject(Base64.decodeStr(message));
                ExtSysMessagecontrol vo = new ExtSysMessagecontrol();
                vo.setUserAccount((String)jsStr.get("useraccount"));
                vo.setTitle((String)jsStr.get("title"));
                vo.setContent((String)jsStr.get("content"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = sdf.format(new Date());
                Date time2 = sdf.parse(time);
                vo.setCreateTime(time2);
                vo.setUpdateTime(time2);
                vo.setUrl((String)jsStr.get("url"));
                vo.setOperationStatus("0");
                messageControlService.insertMessage(vo);

                //导出消息，同步推送到大B
                BigBSendMesReq bigBSendMesReq = new BigBSendMesReq();
                //bigBSendMesReq.setInfoTitle("进项系统导出任务");
                bigBSendMesReq.setNotifyInfoType("JX_EXP");
                bigBSendMesReq.setInfo(vo.getTitle().replace("导出成功，可以下载", ""));
                bigBSendMesReq.setInfoType("5");

                String exportLogId = getParameterValue(vo.getUrl(),"downloadId");
                if(StringUtils.isNotEmpty(exportLogId)){
                    TDxExcelExportlog tDxExcelExportlog = tDxExcelExportlogExtendDao.selectById(exportLogId);
                    if(ObjectUtils.isNotEmpty(tDxExcelExportlog)){
                        bigBSendMesReq.setUserIds(new String[]{tDxExcelExportlog.getUserAccount()});
                    }
                }

                if(StringUtils.isNotEmpty(vo.getUrl())&&vo.getUrl().contains("?")){
                    String url = changeBigBDownload(vo.getUrl());
                    bigBSendMesReq.setFileUrl(jxptBaseUrl+url);
                    log.info("导出文件-推送到大B请求参数:{}",JSON.toJSONString(bigBSendMesReq));
                    String resultStr = HttpUtils.doPost(userCenterConfig.getToBigBMesUrl(), JSON.toJSONString(bigBSendMesReq));
                    log.info("导出文件-推送到大B返回参数:{}",resultStr);
                    //String testresultStr = HttpUtils.doPost("http://10.1.5.46:10000/itaxAdmin/v2/notifyInfo/addNotify", JSON.toJSONString(bigBSendMesReq));
                    //log.info("大B测试地址，后续删，返回:{}",testresultStr);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("接收消息失败:{}", ex.getMessage());
        }
    }

    /**
     * 原先进项请求的地址
     * /ftp/download?serviceType=2&downloadId=1822826294453555202
     **/
    private static String changeBigBDownload(String url) {
        url = url.substring(url.indexOf("?"));
        url = "ftp/getDownload"+url;
        return url;
    }

    public static void main(String[] args) {
        System.out.println(changeBigBDownload("/ftp/download?serviceType=2&downloadId=1822826294453555202"));
    }

    public static String getParameterValue(String url, String parameterName) throws UnsupportedEncodingException {
        // 假设URL的格式是正确的，并且只包含我们关注的查询参数
        if (url == null || parameterName == null) {
            return null;
        }

        // 找到查询参数的开始位置
        int queryStart = url.indexOf('?');
        if (queryStart == -1) {
            return null; // 没有查询参数
        }

        String queryString = url.substring(queryStart + 1);

        // 分割查询字符串为参数数组
        String[] params = queryString.split("&");
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length == 2 && keyValue[0].equals(parameterName)) {
                // 使用URLDecoder解码值（如果需要）
                return URLDecoder.decode(keyValue[1], "UTF-8");
            }
        }
        return null; // 没有找到参数
    }

}
