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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tcm.api.service.IEquipmentCategoryService;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.StartPlatformTokenService;
import com.yeejoin.amos.boot.module.tcm.flc.api.service.IRegUnitInfoService;
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;

@Component
@Slf4j
public class PlatformUserTopicMessage extends EmqxListener {
    @Resource
    protected EmqKeeper emqKeeper;

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

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

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

    @Autowired
    RedisUtils redisUtil;

    @Autowired
    IEquipmentCategoryService equipmentCategoryService;

    @Autowired
    IRegUnitInfoService regUnitInfoService;

    @Autowired
    StartPlatformTokenService platformTokenService;

    @Override
    public void processMessage(String topic, MqttMessage message) {
        platformTokenService.setRequestContext();
        JSONObject jsonObject = JSON.parseObject(message.toString());
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject dataResult = result.getJSONObject("result");
        String path = result.getString("path");
        String agencyCode = jsonObject.getString("agencyCode");
        if (!amosAgencyCode.equals(agencyCode)) {
            return;
        }
        try {
            if (StringUtils.isNotEmpty(path)) {
                if (path.contains("company") && !"company".equals(dataResult.get("level"))) {
//                    equipmentCategoryService.creatTree();
                } else if (path.contains("agencyuser")) {
                    regUnitInfoService.updateAdminInfo(dataResult);
                }
            }
        } catch (Exception e) {
            log.info("平台同步消息失败:{}", e.getMessage());
            e.printStackTrace();
        }
        log.info("平台推送消息同步完成");
    }
}
