// Package adl400Api 电表接口
package adl400TtyApi

import (
	"log"
	"strings"

	"github.com/gogf/gf/v2/util/gconv"
	"github.com/towgo/towgo/towgo"
	"tgk-touch/internal/global"
	"tgk-touch/internal/library/meterControl"
	"tgk-touch/internal/model/config"
	"tgk-touch/internal/module/meterFirm"
)

var mc2 meterControl.IMeterControl
var deviceInfo config.DeviceInfo

func Init() {
	deviceInfo = g.Config().DeviceInfo
	mc2 = meterFirm.Manager().GetMeterControl()
	meterFirm.Manager().RegisterReloadCallback(Reload)
	initReadFunc()
	initWriteFunc()
}
func getMc() meterControl.IMeterControl {
	log.Println("getMc==", mc2, meterFirm.Manager().Get())
	if mc2 == nil {
		mc2 = meterFirm.Manager().GetMeterControl()
	}
	return mc2
}
func Reload() {
	mc2 = meterFirm.Manager().GetMeterControl()
}
func initReadFunc() {
	towgo.SetFunc("/adl400/readPhaseData", readPhaseData)
	// 读取通信地址
	towgo.SetFunc("/adl400/getMsgAddress", getMsgAddress)
	// 读取日冻结时间
	towgo.SetFunc("/adl400/getDailyFreezingTime", getDailyFreezingTime)
	// 读取月冻结时间
	towgo.SetFunc("/adl400/getMonthlyFreezingTime", getReadMonthlyFreezingTime)
	// 读取冻结数据
	towgo.SetFunc("/adl400/getFreezeTheData", getFreezeTheData)
	// 读取时间
	towgo.SetFunc("/adl400/geTime", geDeviceTime)
}
func initWriteFunc() {
	// 写入通信地址
	towgo.SetFunc("/adl400/setMsgAddress", setMsgAddress)
}
func getMeterAddr(cuid string) byte {
	// 去掉 "0x" 前缀，按 16 进制解析
	return gconv.Byte(strings.TrimPrefix(deviceInfo.MeterAddr, "0x"))
}
