package blockchain

import (
	"encoding/json"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/config"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils/remoteUtil"
	"strconv"
)

func SaveToChain(token string, userIp string, config *config.Config) func(task models.Task, id int64) error {
	return func(task models.Task, id int64) error {
		if token == "" {
			return nil
		}
		// 数据上链
		bytes, err := json.Marshal(task)
		if err != nil {
			return err
		}
		err = remoteUtil.Evidence(remoteUtil.EvidenceParam{
			UserIp:          userIp,
			Url:             config.BlockChain.Url,
			ContractAddress: config.BlockChain.ContractAddress,
			FunctionName:    config.BlockChain.FunctionName,
			Type:            config.BlockChain.Type,
			Token:           token,
			Args:            []string{strconv.FormatInt(id, 10), string(bytes)},
		})
		if err != nil {
			return err
		}

		return nil
	}
}
