package config

import (
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/util"
	"encoding/json"
	"strings"
	"time"
)

type taskTrigger struct {
	TriggerId         int    `json:"triggerId"`
	TriggerName       string `json:"triggerName"`
	TriggerScriptPath string `json:"triggerScriptPath"`
	TriggerType       string `json:"triggerType"`
}

type PlatformConfigStruct struct {
	TaskConfigId    string        `json:"taskConfigId"`   // 配置ID
	TaskConfigName  string        `json:"taskConfigName"` // 配置名称
	DropUploadData  bool          `json:"dropUploadData"` // 更新任务时 true 先上传旧任务 false 删除旧任务
	TaskMaxTime     int           `json:"taskMaxTime"`
	TaskBeforeTime  int           `json:"taskBeforeTime"`
	TaskAfterTime   int           `json:"taskAfterTime"`
	TaskCachePolicy string        `json:"taskCachePolicy"`
	EquipmentTopic  string        `json:"equipmentTopic"` // topic序列
	Lru             []string      `json:"LRU"`
	TaskTriggers    []taskTrigger `json:"taskTriggers"`
}

type response struct {
	Data    PlatformConfigStruct `json:"data"`
	Success bool                 `json:"success"`
	Message string               `json:"message"`
	Code    int                  `json:"code"`
	NowTime string               `json:"nowTime"`
}

var (
	PlatformConfig  PlatformConfigStruct
	SubscribeTopics []string
)

// InitPlatformConfig 初始化数据闭环平台的配置
func InitPlatformConfig() {
	var err error
	c_log.GlobalLogger.Info("获取数据闭环平台配置 - 开始")
	// 1 如果车辆没有配置任务，则阻塞在这里，不启动任务
	for {
		time.Sleep(time.Duration(2) * time.Second)
		// 判断是否有配置，第一次访问状态应该为：CHANGE（一共三种状态 CHANGE|UNCHANGE|NONE）
		PlatformConfig, err = getConfig()
		if err != nil {
			c_log.GlobalLogger.Error("获取配置status失败：", err)
			continue
		}
		if checkPlatformConfig() {
			SubscribeTopics = strings.Split(PlatformConfig.EquipmentTopic, ",")
			// 去掉首尾空格
			for i, topic := range SubscribeTopics {
				SubscribeTopics[i] = strings.TrimSpace(topic)
			}
			break
		}
	}
	c_log.GlobalLogger.Info("获取数据闭环平台配置 - 成功。")
}

/*
	{
	  "data": {
	    "accessToken": "YWRmYWRzZmFzZGZhZHNmYWRmYWRm=",
	    "expireTime": "28800",
	    "equipmentNo": "robot-001"
	  },
	  "success": true,
	  "message": "ok",
	  "code": 1,
	  "nowTime": "2023-12-09 22:41:00"
	}
*/
// GetAccessToken 认证接口，获取access_token
func GetAccessToken() (string, error) {
	respJson, err := util.HttpPostJsonResponseString(
		CloudConfig.Platform.UrlDeviceAuth,
		map[string]string{
			"equipmentNo": LocalConfig.EquipmentNo,
			"secretKey":   LocalConfig.SecretKey,
		},
	)
	if err != nil {
		return "", nil
	}
	respMap, err := util.JsonStringToMap(respJson)
	if err != nil {
		c_log.GlobalLogger.Error("解析返回结果", respJson, "失败：", err)
		return "", nil
	}

	dataMap, ok := respMap["data"].(map[string]interface{})
	if !ok {
		c_log.GlobalLogger.Error("解析返回结果.data", dataMap, "失败：", err)
		return "", nil
	}
	return dataMap["accessToken"].(string), nil
}

/*
	{
	  "data": {
	    "status": "UNCHANGE"
	    "taskConfigld": "xxx"
	  },
	  "success": true,
	  "message": "ok",
	  "code": 1,
	  "nowTime": "2023-12-09 21:08:49"
	}
*/
//GetStatus 根据taskConfigId获取任务status，如果传入空代表车端没有配置，直接获取新的配置
func GetStatus(taskConfigId string) (string, error) {
	token, err := GetAccessToken()
	if err != nil {
		return "", err
	}
	resp, err := util.HttpGetStringAddHeadersResponseString(
		CloudConfig.Platform.UrlTaskPoll,
		map[string]string{
			"authorization": token,
		},
		map[string]string{
			"equipmentNo":  LocalConfig.EquipmentNo,
			"taskConfigId": taskConfigId,
		},
	)

	if err != nil {
		c_log.GlobalLogger.Error("访问接口", CloudConfig.Platform.UrlTask, "失败：", err)
		return "", err
	}
	respMap, err := util.JsonStringToMap(resp)
	if err != nil {
		c_log.GlobalLogger.Error("解析【返回结果1】", resp, "失败：", err)
		return "", err
	}
	dataMap, ok := respMap["data"].(map[string]interface{})
	if !ok {
		c_log.GlobalLogger.Errorf("解析【返回结果.data】的类型不是(map[string]interface{})，【dataMap】=%v", dataMap)
		return "", err
	}
	return dataMap["status"].(string), nil
}

func getConfig() (PlatformConfigStruct, error) {
	token, err := GetAccessToken()
	if err != nil {
		return PlatformConfigStruct{}, err
	}
	// 下载插件和获取配置
	// 2 访问配置获取接口
	resp, err := util.HttpGetStringAddHeadersResponseString(
		CloudConfig.Platform.UrlTask,
		map[string]string{
			"authorization": token,
		},
		map[string]string{
			"equipmentNo": LocalConfig.EquipmentNo,
		},
	)
	if err != nil {
		c_log.GlobalLogger.Error("访问接口", CloudConfig.Platform.UrlTask, "失败：", err)
		return PlatformConfigStruct{}, err
	}
	var result response
	err = json.Unmarshal([]byte(resp), &result)
	if err != nil {
		c_log.GlobalLogger.Error("解析【返回结果】", resp, "失败：", err)
		return PlatformConfigStruct{}, err
	}
	return result.Data, nil
}

func checkPlatformConfig() bool {
	if PlatformConfig.TaskConfigId == "" {
		c_log.GlobalLogger.Error("数据闭环平台没有配置任务。")
		return false
	}
	if PlatformConfig.EquipmentTopic == "" {
		c_log.GlobalLogger.Error("数据闭环平台没有配置topic序列。")
		return false
	}
	return true
}
