package protocol

import (
	"encoding/hex"
	"github.com/gogf/gf/os/glog"
	"strconv"
)

type Dlt_0x33323535 struct {
	//接收表号
	DeviceAddress []byte
	//表号
	DeviceID string
	// 当前A相电流
	CurrentA float64
	// 当前B相电流
	CurrentB float64
	// 当前C相电流
	CurrentC float64
}

func (e *Dlt_0x33323535) MsgID() MsgID {
	return Msgdlt_0x33323535
}

func (e *Dlt_0x33323535) Encode(ctx *PacketContext) ([]byte, error) {
	writer := NewWriter()
	// 接收符号
	writer.Write([]byte{0x68})
	writer.Write(ctx.GetReceiveAddress())
	writer.Write([]byte{0x68, 0x11, 0x04, 0x33, 0x32, 0x35, 0x35})

	//cs效验位
	var one byte
	for _, v := range writer.Bytes() {
		one += v
	}
	writer.WriteByte(one)
	// 功能码
	writer.WriteByte(0x16)
	return writer.Bytes(), nil
}

func (e *Dlt_0x33323535) Decode(ctx *PacketContext, dataByte []byte) (data Data, err error) {
	bytea := dataByte[1:7]
	for i, j := 0, len(bytea)-1; i < j; i, j = i+1, j-1 {
		bytea[i], bytea[j] = bytea[j], bytea[i]
	}
	e.DeviceID = hex.EncodeToString(bytea)
	//正向总电能每个字节-33,1-4,分别为,小数位,个位,百位,万位
	byteb := make([]byte, 9)
	for i := 0; i < 2; i++ {
		byteb[i] = dataByte[14+i] - 0x33
	}

	_ = e.stringToCurrentBlock(hex.EncodeToString(byteb))

	glog.Debugf("数据读取成功：表号:%s,当前A相电流:%2fA,B相电流:%2fA,C相电流:%2fA", e.DeviceID, e.CurrentA, e.CurrentB, e.CurrentC)
	data.AI = e.CurrentA
	data.BI = e.CurrentB
	data.CI = e.CurrentC
	data.DataType = IsIData
	return data, nil
}

func (e *Dlt_0x33323535) stringToCurrentBlock(s string) error {
	a0, _ := strconv.ParseFloat(s[0:2], 64)
	a1, _ := strconv.ParseFloat(s[2:4], 64)
	a2, _ := strconv.ParseFloat(s[4:6], 64)
	b0, _ := strconv.ParseFloat(s[6:8], 64)
	b1, _ := strconv.ParseFloat(s[8:10], 64)
	b2, _ := strconv.ParseFloat(s[10:12], 64)
	c0, _ := strconv.ParseFloat(s[12:14], 64)
	c1, _ := strconv.ParseFloat(s[14:16], 64)
	c2, _ := strconv.ParseFloat(s[16:18], 64)
	e.CurrentA = a0*0.001 + a1*0.1 + a2*10
	e.CurrentB = b0*0.001 + b1*0.1 + b2*10
	e.CurrentC = c0*0.001 + c1*0.1 + c2*10
	return nil
}
