package mqtt

import (
	"encoding/json"
	pahomqtt "github.com/eclipse/paho.mqtt.golang"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/mqtt"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"time"
)

func Start() {
	mqtt.StartSubscribe(constant.MQTT_TOPIC, func(client pahomqtt.Client, message pahomqtt.Message) {
		payload := make(map[string]interface{})
		err := json.Unmarshal(message.Payload(), &payload)
		if err != nil {
			log.Logger.Error("车间数据json解析失败:" + err.Error())
			return
		}
		if workShop, ok := payload["WorkShop"]; ok {
			for key, item := range payload {
				if key == "WorkShop" {
					continue
				}
				deviceWorkShop := &domain.DeviceWorkShop{}
				mBytes, err := json.Marshal(item)
				if err != nil {
					continue
				}
				err = json.Unmarshal(mBytes, deviceWorkShop)
				if err != nil {
					continue
				}
				// 获取当前时间
				deviceWorkShop.CurrTime = time.Now()
				// 车间名称
				deviceWorkShop.WorkShop = workShop.(string)
				// 设备名称
				deviceWorkShop.DeviceSn = key
				workShopBytes, err := json.Marshal(deviceWorkShop)
				if err != nil {
					continue
				}
				err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err()
				if err != nil {
					log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
				}
			}
		}
		log.Logger.Info("MQTT", map[string]interface{}{
			"Topic":     message.Topic(),
			"MessageId": message.MessageID(),
			"Message":   payload,
		})
	})
}