package m9zApi

import (
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"strings"
	g "tgk-touch/internal/global"
	m9z "tgk-touch/internal/library/m9z"
	"tgk-touch/utility"
	"time"

	"github.com/towgo/towgo/towgo"
)

// 写入设备编程模式
func setDeviceMode(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		Mode    uint8  `json:"mode"`
	}
	rpc.ReadParams(&p)
	var mode byte
	mode = 0x00
	switch p.Mode {
	case 0:
		mode = 0x00
		break
	case 1:
		mode = 0x01
		break
	case 2:
		mode = 0x02
		break
	}
	err := m9z.ModeWrite(p.CommUid, mode)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	g.Log().Debugf("setDeviceMode: mode = %+v", p)
	rpc.WriteResult("ok")
}

func setDeviceManualInfo(rpc towgo.JsonRpcConnection) {
	var p struct {
		m9z.ManualData
		CommUid string `json:"comm_uid"`
	}
	rpc.ReadParams(&p)

	err := m9z.ManualWrite(p.CommUid, &p.ManualData)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

// 设置设备时间
func setDeviceTime(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid    string `json:"comm_uid"`
		DeviceTime string `json:"device_time"`
	}
	rpc.ReadParams(&p)
	deviceLgnLatReadRep, err := m9z.LgnLatRead(p.CommUid)
	if err != nil {
		panic(err)
	}

	newTime, err := time.ParseInLocation("2006-01-02 15:04:05", p.DeviceTime, deviceLgnLatReadRep.Loc)
	if err != nil {
		panic(err)
	}
	err = m9z.DeviceTimeWrite(p.CommUid, newTime)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

func setLgnLatData(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.LgnLatData
		LocStr string `json:"loc_str"`
	}
	rpc.ReadParams(&p)
	ld := p.LgnLatData
	loc, err := parseTimezoneOffset(p.LocStr)
	if err != nil {
		panic(err)
	}
	ld.Loc = loc
	err = m9z.LgnLatWrite(p.CommUid, &ld)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

func parseTimezoneOffset(offsetStr string) (*time.Location, error) {
	// 提取偏移量（如 "+08:00"）
	offsetStr = strings.TrimPrefix(offsetStr, "UTC") // 移除前缀 "UTC"

	// 解析小时和分钟
	sign := 1
	if offsetStr[0] == '-' {
		sign = -1
		offsetStr = offsetStr[1:]
	} else if offsetStr[0] == '+' {
		offsetStr = offsetStr[1:]
	}

	parts := strings.Split(offsetStr, ":")
	hours, minutes := 0, 0
	if len(parts) >= 1 {
		fmt.Sscanf(parts[0], "%d", &hours)
	}
	if len(parts) >= 2 {
		fmt.Sscanf(parts[1], "%d", &minutes)
	}

	// 计算总秒数
	totalSeconds := (hours*60 + minutes) * 60 * sign
	return time.FixedZone(offsetStr, totalSeconds), nil
}

// 设置日出日落时间偏差
func setSunRiseSet(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.SunRiseSet
	}
	rpc.ReadParams(&p)
	err := m9z.SunRiseSetWrite(p.CommUid, &p.SunRiseSet)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

// 设置设备的配置
func setDeviceConfig(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.DeviceConfig
	}
	rpc.ReadParams(&p)
	err := m9z.DeviceConfigWrite(p.CommUid, &p.DeviceConfig)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

func setSave(rpc towgo.JsonRpcConnection) {
	cuid, _ := getDeviceId(rpc)
	err := m9z.Save(cuid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}
func setRestart(rpc towgo.JsonRpcConnection) {
	cuid, _ := getDeviceId(rpc)
	err := m9z.Restart(cuid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

func setDeviceLgnLatAndSunRsTime(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.SunRiseSet
		m9z.LgnLatData
		LocStr string `json:"loc_str"`
	}
	rpc.ReadParams(&p)
	ld := p.LgnLatData
	if p.LocStr == "" {
		p.LocStr = "UTC+08:00"
	}
	loc, err := parseTimezoneOffset(p.LocStr)
	if err != nil {
		panic(err)
	}
	ld.Loc = loc
	err = m9z.LgnLatWrite(p.CommUid, &ld)
	if err != nil {
		panic(err)
	}
	err = m9z.SunRiseSetWrite(p.CommUid, &p.SunRiseSet)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")

}

// 写入开始任务 (优化指令 CMD=0x13)
func setStartTaskWrite(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.TaskProgram
	}
	rpc.ReadParams(&p)
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}
	err := m9z.StartTaskWrite(p.CommUid, &p.TaskProgram)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

// 写入中间任务 (优化指令 CMD=0x14)
func setMiddleTaskWrite(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.TaskProgram
	}
	rpc.ReadParams(&p)
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}
	err := m9z.MiddleTaskWrite(p.CommUid, &p.TaskProgram)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

// 写入结束任务 (优化指令 CMD=0x15)
func setStopTaskWrite(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid string `json:"comm_uid"`
		m9z.TaskProgram
	}
	rpc.ReadParams(&p)
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}
	err := m9z.StopTaskWrite(p.CommUid, &p.TaskProgram)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

// 写入开始任务 (优化指令 CMD=0x15)
func setStartTask2(rpc towgo.JsonRpcConnection) {
	var p struct {
		ExecTime string `json:"execTime"`
		CommUid  string `json:"comm_uid"`
		Mode     uint8  `json:"mode"`
		m9z.ControlTask
	}
	rpc.ReadParams(&p)
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}
	parse, err := utility.ParseTime(p.ExecTime)
	if err != nil {
		panic(err)
	}
	p.ControlTask.ExecTime = parse
	program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode)
	if err != nil {
		panic(err)
	}
	err = m9z.StartTaskWrite(p.CommUid, program)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}
func setStopTask2(rpc towgo.JsonRpcConnection) {
	var p struct {
		ExecTime string `json:"execTime"`
		CommUid  string `json:"comm_uid"`
		Mode     uint8  `json:"mode"`
		m9z.ControlTask
	}
	rpc.ReadParams(&p)
	parse, err := utility.ParseTime(p.ExecTime)
	if err != nil {
		panic(err)
	}
	p.ControlTask.ExecTime = parse
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}

	program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode)
	if err != nil {
		panic(err)
	}

	err = m9z.StopTaskWrite(p.CommUid, program)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}

func setMiddleTask2(rpc towgo.JsonRpcConnection) {
	var p struct {
		CommUid         string `json:"comm_uid"`
		Mode            uint8  `json:"mode"`
		ControlTaskList []struct {
			m9z.ControlTask
			ExecTime string `json:"execTime"` // "2006-01-02 15:04:05" 格式时间
		} `json:"controlTaskList"`
	}
	rpc.ReadParams(&p)
	if p.CommUid == "" {
		panic(gerror.New("comm_uid is empty"))
	}
	middleTask := m9z.MiddleControlTask{}
	middleTask.ControlTaskList = make([]m9z.ControlTask, len(p.ControlTaskList))
	for i, controlTask := range p.ControlTaskList {
		parse, err := utility.ParseTime(controlTask.ExecTime)
		if err != nil {
			panic(gerror.NewCodef(gcode.CodeInvalidParameter, " %s parse control task time error, %s", controlTask.ExecTime, err))
		}
		controlTask.ControlTask.ExecTime = parse
		middleTask.ControlTaskList[i] = controlTask.ControlTask
	}
	program, err := m9z.MiddleControlTaskToTaskProgram(middleTask, p.Mode)
	if err != nil {
		panic(err)
	}
	err = m9z.MiddleTaskWrite(p.CommUid, program)
	if err != nil {
		panic(err)
	}
	err = m9z.Save(p.CommUid)
	if err != nil {
		panic(err)
	}
	rpc.WriteResult("ok")
}
