package Adl400Impl

import (
	"fmt"
	"tgk-touch/internal/global"
	"tgk-touch/internal/library/ADL400"
	"time"
)

func (a *Adl400Impl) ReadYear(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003E.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0]

	bytes := []byte{byte(value >> 8), byte(value)}
	_, year := int(bytes[0]), int(bytes[1])
	return year, nil
}
func (a *Adl400Impl) ReadMonth(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003E.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0] // 低字节为月份
	bytes := []byte{byte(value >> 8), byte(value)}
	month, _ := int(bytes[0]), int(bytes[1])
	return month, nil
}
func (a *Adl400Impl) ReadDay(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003D.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0]
	//hour := value >> 8                   // 高字节=小时（9）
	day := value & 0xFF // 低字节=日（27）
	return int(day), nil
}
func (a *Adl400Impl) ReadHour(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003D.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0]
	hour := value >> 8 // 高字节=小时（9）
	//day := value & 0xFF // 低字节=日（27）
	return int(hour), nil
}
func (a *Adl400Impl) ReadMinute(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003C.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0]
	//second := value >> 8  // 高字节=小时（9）
	minute := value & 0xFF // 低字节=日（27）
	return int(minute), nil
}
func (a *Adl400Impl) ReadSecond(commUid string, addr byte) (int, error) {
	read, err := ADL400.H003C.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	value := read[0]
	second := value >> 8 // 高字节=小时（9）
	//minute := value & 0xFF // 低字节=日（27）
	return int(second), nil
}
func (a *Adl400Impl) ReadTime(commUid string, addr byte) (time.Time, error) {
	// 读取各个时间组件
	year, err := a.ReadYear(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read year: %v", err)
	}

	month, err := a.ReadMonth(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read month: %v", err)
	}

	day, err := a.ReadDay(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read day: %v", err)
	}

	hour, err := a.ReadHour(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read hour: %v", err)
	}

	minute, err := a.ReadMinute(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read minute: %v", err)
	}

	second, err := a.ReadSecond(commUid, addr)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to read second: %v", err)
	}
	// 构建时间对象
	loc, _ := time.LoadLocation("Local") // 使用本地时区
	t := time.Date(
		year+2000, // 假设年份是2位数，加上2000
		time.Month(month),
		day,
		hour,
		minute,
		second,
		0, // 纳秒
		loc,
	)
	return t, nil
}

func (a *Adl400Impl) ReadVoltage(commUid string, addr byte) (totalVoltage, aVoltage, bVoltage, cVoltage float64, err error) {
	aRead, err := ADL400.H0061.Read(commUid, addr)
	if err != nil {
		return
	}
	aVoltage = float64(aRead[0]) * 0.1
	bRead, err := ADL400.H0062.Read(commUid, addr)
	if err != nil {
		return
	}
	bVoltage = float64(bRead[0]) * 0.1
	cRead, err := ADL400.H0063.Read(commUid, addr)
	if err != nil {
		return
	}
	cVoltage = float64(cRead[0]) * 0.1
	return totalVoltage, aVoltage, bVoltage, cVoltage, err
}
func (a *Adl400Impl) ReadElectricCurrent(commUid string, addr byte) (totalElectricCurrent, aElectricCurrent, bElectricCurrent, cElectricCurrent float64, err error) {
	aRead, err := ADL400.H0064.Read(commUid, addr)
	if err != nil {
		return
	}
	aElectricCurrent = float64(aRead[0]) * 0.01
	bRead, err := ADL400.H0065.Read(commUid, addr)
	if err != nil {
		return
	}
	bElectricCurrent = float64(bRead[0]) * 0.01

	cRead, err := ADL400.H0066.Read(commUid, addr)
	if err != nil {
		return
	}
	cElectricCurrent = float64(cRead[0]) * 0.01

	return totalElectricCurrent, aElectricCurrent, bElectricCurrent, cElectricCurrent, err
}
func (a *Adl400Impl) ReadPower(commUid string, addr byte) (totalPower, aPower, bPower, cPower float64, err error) {
	aRead, err := ADL400.H0067.Read(commUid, addr)
	if err != nil {
		return
	}
	aPower = float64(aRead[0]) * 0.001
	bRead, err := ADL400.H0068.Read(commUid, addr)
	if err != nil {
		return
	}
	bPower = float64(bRead[0]) * 0.001

	cRead, err := ADL400.H0069.Read(commUid, addr)
	if err != nil {
		return
	}
	cPower = float64(cRead[0]) * 0.001
	tRead, err := ADL400.H006A.Read(commUid, addr)
	if err != nil {
		return 0, 0, 0, 0, err
	}
	totalPower = float64(tRead[0]) * 0.001
	return totalPower, aPower, bPower, cPower, err
}
func (a *Adl400Impl) ReadTotalPower(commUid string, addr byte) (totalPower float64, err error) {
	tRead, err := ADL400.H006A.Read(commUid, addr)
	if err != nil {
		return 0, err
	}
	totalPower = float64(tRead[0]) * 0.001
	return totalPower, err
}
func (a *Adl400Impl) ReadEnergy(commUid string, addr byte) (totalEnergy, aEnergy, bEnergy, cEnergy float64, err error) {
	read, err := ADL400.H000A.Read(commUid, addr)
	if err != nil {
		return
	}
	high := uint32(read[0])     // 高16位
	low := uint32(read[1])      // 低16位
	value := (high << 16) | low // 组合为32位整数
	totalEnergy = float64(value) * 0.01

	aRead, err := ADL400.H0087.Read(commUid, addr)
	if err != nil {
		return
	}
	ahigh := uint32(aRead[0])      // 高16位
	alow := uint32(aRead[1])       // 低16位
	avalue := (ahigh << 16) | alow // 组合为32位整数
	aEnergy = float64(avalue) * 0.01

	bRead, err := ADL400.H0089.Read(commUid, addr)
	if err != nil {
		return
	}
	bhigh := uint32(bRead[0])      // 高16位
	blow := uint32(bRead[1])       // 低16位
	bvalue := (bhigh << 16) | blow // 组合为32位整数
	bEnergy = float64(bvalue) * 0.01

	cRead, err := ADL400.H008B.Read(commUid, addr)
	if err != nil {
		return
	}
	chigh := uint32(cRead[0])      // 高16位
	clow := uint32(cRead[1])       // 低16位
	cvalue := (chigh << 16) | clow // 组合为32位整数
	cEnergy = float64(cvalue) * 0.01

	return totalEnergy, aEnergy, bEnergy, cEnergy, err
}

func (a *Adl400Impl) ReadPowerFactor(commUid string, addr byte) (totalPf, aPf, bPf, cPf float64, err error) {
	aRead, err := ADL400.H0073.Read(commUid, addr)
	if err != nil {
		return
	}
	aPf = float64(aRead[0]) * 0.001
	bRead, err := ADL400.H0074.Read(commUid, addr)
	if err != nil {
		return
	}
	bPf = float64(bRead[0]) * 0.001

	cRead, err := ADL400.H0075.Read(commUid, addr)
	if err != nil {
		return
	}
	cPf = float64(cRead[0]) * 0.001
	tRead, err := ADL400.H0076.Read(commUid, addr)
	if err != nil {
		return 0, 0, 0, 0, err
	}
	totalPf = float64(tRead[0]) * 0.001
	return totalPf, aPf, bPf, cPf, err
}
func (a *Adl400Impl) ReadMsgAddr(commUid string, addr byte) (msgAddr byte, err error) {
	read, err := ADL400.H003F.Read(commUid, addr)
	if err != nil {
		return 0, err
	}

	// 调试日志：打印原始数据
	g.Log().Infof("ReadMsgAddr raw data: len=%d, data=% X", len(read), read)

	// 根据实际数据长度处理不同情况
	switch len(read) {
	case 1: // 单个 uint16 值 (2字节)
		// 示例日志: [5C03] -> 0x5C03
		value := read[0]           // 假设返回的是 uint16 类型
		msgAddr = byte(value >> 8) // 取高字节 (0x5C)
		g.Log().Infof("Extracted from uint16: 0x%X -> msgAddr=0x%X (%d)", value, msgAddr, msgAddr)
		/*
			case 2: // 两个字节 [high, low]
				// 示例: [5C 03] -> msgAddr=0x5C
				msgAddr = read[0]
				g.Log().Infof("Extracted from bytes: [% X] -> msgAddr=0x%X (%d)", read, msgAddr, msgAddr)

			default:
				return 0, fmt.Errorf("unexpected data length: %d bytes", len(read))*/
	}

	return msgAddr, nil
}

func (a *Adl400Impl) ReadMainAddr(commUid string, addr byte) (mainAddr byte, err error) {
	/*	read, err := ADL400.H0099_009E.Read(commUid, addr)
		if err != nil {
			return "", err
		}

		// 调试日志
		g.Log().Infof("ReadMainAddr raw data: len=%d, data=% X", len(read), read)

		// 根据实际数据长度处理
		var bcdData []byte
		switch v := read.(type) {
		case []uint16: // 返回的是 uint16 数组
			// 示例: [0000 0000 0050] -> BCD "000000000050"
			for _, reg := range v {
				bcdData = append(bcdData, byte(reg>>8), byte(reg))
			}

		case []byte: // 直接返回字节数组
			bcdData = v

		default:
			return "", fmt.Errorf("unexpected data type: %T", read)
		}

		// 验证数据长度
		if len(bcdData) != 12 {
			return "", fmt.Errorf("invalid BCD data length: expected 12 bytes, got %d", len(bcdData))
		}

		// 转换BCD码为字符串
		var builder strings.Builder
		for _, b := range bcdData {
			high := b >> 4
			low := b & 0x0F

			if high > 9 || low > 9 {
				return "", fmt.Errorf("invalid BCD digit: %X", b)
			}

			builder.WriteByte('0' + high)
			builder.WriteByte('0' + low)
		}

		mainAddr = builder.String()
		g.Log().Infof("Converted mainAddr: %s", mainAddr)*/
	return
}

func (a *Adl400Impl) ReadDailyFreezingTime(commUid string, addr byte) (dailyFreezingTime string, err error) {
	read, err := ADL400.H0121.Read(commUid, addr)
	if err != nil {
		return "", err
	}
	value := read[0]
	minute := value >> 8 // 高字节=小时（9）
	hour := value & 0xFF // 低字节=日（27）
	// 校验有效时间范围
	if hour < 0 || hour > 23 || minute < 0 || minute > 59 {
		return fmt.Sprintf("%03d:%02d", hour, minute), nil
	}
	return fmt.Sprintf("%02d:%02d", hour, minute), nil

}

func (a *Adl400Impl) ReadMonthlyFreezingTime(commUid string, addr byte) (dayStr, hourStr string, err error) {
	read, err := ADL400.H0122.Read(commUid, addr)
	if err != nil {
		return "", "", err
	}
	value := read[0]
	day := value >> 8    // 高字节=小时（9）
	hour := value & 0xFF // 低字节=日（27）

	return fmt.Sprintf("%02d", day), fmt.Sprintf("%02d", hour), err
}
