package com.yeejoin.amos.boot.module.jg.biz.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.StartPlatformTokenService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.emq.EmqxListener;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.stream.Stream;

@Component
@Slf4j
public class PlatformUserTopicMessage extends EmqxListener {

    @Resource
    protected EmqKeeper emqKeeper;

    @Value("${amos.operation.log}")
    private String amosOperationLog;

    @Value("${amos.agency.code}")
    private String amosAgencyCode;

    @Autowired
    private StartPlatformTokenService platformTokenService;

    @Autowired
    private ICommonService commonService;

    @PostConstruct
    void init() throws Exception {
        emqKeeper.subscript(amosOperationLog, 2, this);
    }

    @Override
    public void processMessage(String topic, MqttMessage message) {
        platformTokenService.getToken();
        parseMessage(message)
                .filter(jsonObject -> amosAgencyCode.equals(jsonObject.getString("agencyCode")))
                .map(jsonObject -> jsonObject.getJSONObject("result"))
                .filter(result -> StringUtils.isNotEmpty(result.getString("path")))
                .flatMap(this::streamDataResult)
                .forEach(this::processDataResult);
        log.info("平台推送消息同步完成");
    }

    private Stream<JSONObject> streamDataResult(Object dataResult) {
        if (dataResult instanceof JSONObject) {
            return Stream.of((JSONObject) dataResult);
        } else if (dataResult instanceof JSONArray) {
            JSONArray dataResultArray = (JSONArray) dataResult;
            return dataResultArray.stream()
                    .map(JSONObject.class::cast);
        } else {
            log.warn("未知的数据类型: {}", dataResult.getClass().getName());
            return Stream.empty();
        }
    }

    private Stream<JSONObject> parseMessage(MqttMessage message) {
        try {
            JSONObject jsonObject = JSON.parseObject(message.toString());
            return Stream.of(jsonObject);
        } catch (Exception e) {
            log.error("消息解析失败: {}", message.toString(), e);
            return Stream.empty();
        }
    }

    private void processDataResult(JSONObject dataResultObject) {
        try {
            String companyType = "监管机构";
            String companyType2 = "行政审批局";
            String companyTypeValue = dataResultObject.getString("companyType");
            if (StringUtils.isNotEmpty(companyTypeValue) && (companyTypeValue.contains(companyType) || companyTypeValue.contains(companyType2))) {
                commonService.creatApproveTree();
            }
        } catch (Exception e) {
            log.error("平台同步消息处理失败: {}", dataResultObject, e);
        }
    }
}
