package active

import (
	"encoding/xml"
	"fmt"
	"net/http"
	"os"
	"pbx-api-gin/pkg/utils"
	"time"
)

// var ActiveCab string
var CabNum string
var ActivedCab = "1"
var PADTimeout = 30
var Master = false
var MasterTag = 0

var TrainDevide = 0
var RadioFault = 0

var TrainInfoMap = make(map[string]map[int]string)

// 初始化所有列车号
var TrainNumGr = []string{"TS1", "TS2", "TS3", "TS4", "TS5", "TS6", "TS7", "TS8", "TS9", "TS10", "TS11", "TS12", "TS13"}
var TrainNum = "" //STC 设置该变量，可对应取车厢号

// 初始化所有车厢号
var data = [][]string{
	{"D433", "P433", "M433", "K433", "C434", "M434", "P434", "D434"},
	{"D435", "P435", "M435", "K435", "C436", "M436", "P436", "D436"},
	{"D437", "P437", "M437", "K437", "C438", "M438", "P438", "D438"},
	{"D439", "P439", "M439", "K439", "C440", "M440", "P440", "D440"},
	{"D441", "P441", "M441", "K441", "C442", "M442", "P442", "D442"},
	{"D443", "P443", "M443", "K443", "C444", "M444", "P444", "D444"},
	{"D445", "P445", "M445", "K445", "C446", "M446", "P446", "D446"},
	{"D447", "P447", "M447", "K447", "C448", "M448", "P448", "D448"},
	{"D449", "P449", "M449", "K449", "C450", "M450", "P450", "D450"},
	{"D451", "P451", "M451", "K451", "C452", "M452", "P452", "D452"},
	{"D453", "P653", "M453", "K453", "C454", "M454", "P454", "D454"},
	{"D455", "P455", "M455", "K455", "C456", "M456", "P456", "D456"},
	{"D457", "P457", "M457", "K457", "C458", "M458", "P458", "D458"},
}

// Pacu 表示单个 pacu 节点
type Pacu struct {
	ID     string `xml:"id"`
	Status string `xml:"status"`
	Volume string `xml:"volume"`
	Mute   bool   `xml:"mute"`
}

// Icp 表示单个 icp 节点
type Icp struct {
	ID     string `xml:"id"`
	Volume string `xml:"volume"`
}

type Device struct {
	PacuInfo [8]Pacu `xml:"-"` // 不自动序列化，由自定义方法处理
	ICPInfo  [2]Icp  `xml:"-"`
}

var DeviceEndpoint Device

// var SetTimer = false
var QueueTimer *time.Timer = nil

// 挂断所有报警器
func NotifyPaiu(Exten, Action string) {
	url := ""
	switch Action {
	case "answer":
		url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=answer", Exten[2:])
	case "hold":
		url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hold", Exten[2:])
	case "hangup":
		url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hangup", Exten[2:])
	}

	utils.LoggerDebug.Printf("Notify PAD URL:%+v ", url)
	resp, err := http.Get(url)
	if err != nil {
		//lfshook.NewLogger().Logger.Infof("======Notify PAIU Alarm====:%+v ", err)
		return
	}
	defer resp.Body.Close()
	/*
	   body, err := io.ReadAll(resp.Body)

	   	if err != nil {
	   		// 读取数据错误
	   		lfshook.NewLogger().Warn("ioutil ReadAll failed :", err.Error())
	   		return
	   	}

	   fmt.Printf("状态码: %d\n", resp.StatusCode)
	   fmt.Printf("响应内容: %s\n", body)
	*/
}

// MarshalXML 实现自定义 XML 输出：按顺序写入所有 pacu 和 icp 节点
func (d Device) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	// 写入根标签 <device>
	if err := e.EncodeToken(xml.StartElement{Name: xml.Name{Local: "device"}}); err != nil {
		return err
	}

	// 写入所有 <pacu> 节点
	for _, p := range DeviceEndpoint.PacuInfo {
		if err := e.Encode(p); err != nil {
			return err
		}
	}

	// 写入所有 <icp> 节点
	for _, i := range DeviceEndpoint.ICPInfo {
		if err := e.Encode(i); err != nil {
			return err
		}
	}

	// 写入根结束标签 </device>
	return e.EncodeToken(xml.EndElement{Name: xml.Name{Local: "device"}})
}

func GenerateXML(pt string) error {
	// 创建文件（会覆盖同名文件）
	file, err := os.Create(pt)
	if err != nil {
		//fmt.Printf("创建文件失败: %v\n", err)
		return err
	}
	defer file.Close() // 确保关闭

	// 使用 xml.Encoder 写入（更规范，支持缩进、处理特殊字符等）
	encoder := xml.NewEncoder(file)
	encoder.Indent("", "  ") // 启用缩进，等效于 MarshalIndent
	if err := encoder.Encode(DeviceEndpoint); err != nil {
		//fmt.Printf("XML 编码写入失败: %v\n", err)
		return err
	}
	return err
}

func InitTrainInfoMap() {
	utils.LoggerDebug.Printf("Init train info map ..... ")

	for i, train := range TrainNumGr {
		TrainInfoMap[train] = make(map[int]string)
		for j, car := range data[i] {
			TrainInfoMap[train][j+1] = car //位置从1开始
		}
	}
}
