package com.yeejoin.precontrol.common.listener.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.precontrol.common.after.runner.CompanyAndPersonTask;
import com.yeejoin.precontrol.common.entity.MessageException;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IMessageExceptionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.EmqxListener;

/**
 * @Description: mqtt监听服务
 * @Author: duanwei
 * @Date: 2020/9/15
 */
@Component
@Slf4j
public class AmosMqTtlListener extends EmqxListener {

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	IMessageExceptionService iMessageExceptionService;

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

	@Autowired
	CompanyAndPersonTask companyAndPersonTask;
	

	String jepcc = "JEPCC";

	@Override
	public void processMessage(String topic, MqttMessage message) {
		JSONObject jsonObject = JSONObject.parseObject(message.toString());
		JSONObject result = jsonObject.getJSONObject("result");
		String methodName = jsonObject.getString("methodName");
		String path = result.getString("path");
		String agencyCode = jsonObject.getString("agencyCode");
		if (!amosAgencyCode.equals(agencyCode)) {
			return;
		}
		try {
			if (StringUtils.isNotEmpty(path)) {
//				Runnable runnable = new Runnable() {
//					public void run() {
//						companyAndPersonTask.run();
//					}
//				};
				if (path.contains("department")) {
//					new Thread(runnable).start();
				} else if (path.contains("company")) {
//					iCompanyService.syncCompany(jsonObject);
//					new Thread(runnable).start();
				} else if (path.contains("agencyuser")) {
					if (jepcc.equals(agencyCode)) {
						iPersonService.syncPerson(jsonObject);
					} else {
						iPersonService.syncCommonPerson(jsonObject);
					}
//					new Thread(runnable).start();
				}
			}
		} catch (Exception e) {
			log.info("平台同步消息失败:{}", e.getMessage());
			e.printStackTrace();
			MessageException messageException = new MessageException();
			messageException.setJson(jsonObject.toJSONString());
			messageException.setPath(path);
			messageException.setMethod(methodName);
			messageException.setMessage(e.getMessage());
			iMessageExceptionService.save(messageException);
		}
		log.info("平台推送消息同步完成");
	}
}
