package ami

// import (
// 	"fmt"
// 	"pms-api-go/pkg/configs"
// 	"pms-api-go/pkg/httpclient"
// 	"pms-api-go/pkg/lfshook"
// 	"strconv"
// 	"strings"
// 	"time"

// 	"gopkg.in/ini.v1"
// )

// var TimestampList = make(map[string]string)
// var StartTimeList = make(map[string]time.Time) // 事件中 Timestamp 转 StartTime 有问题，重新记录时间
// var CallTypeList = make(map[string]string)     // 临时记录 incoming 和 outgoing ，为incoming时： HangupRequest 中如果CallerIDNum为被叫号码，则未接听
// // var DialStatusList = make(map[string]string)     // 临时记录 DialStatus:ANSWER NOANSWER

// func callNotify(event map[string]string) {
// 	fmt.Println("=========================================== ")
// 	fmt.Println("event[] = ", event)
// 	fmt.Println("event = ", event["Event"])
// 	fmt.Println("AMIPushUrl = ", configs.PushConfigValue.AMIPushUrl)
// 	fmt.Println("Channel = ", event["Channel"])

// 	var callDest string
// 	if event["Channel"] != "" {
// 		callDest = strings.Split(strings.Split(event["Channel"], "/")[1], "-")[0]
// 		fmt.Println("callDest = ", callDest)
// 	}

// 	// var callId string
// 	var callId = "10000021" // 测试用，每次测试 +1
// 	// event["Exten"] = "123456789" // 测试用
// 	// fmt.Println("Exten = ", event["Exten"])

// 	// 读取vtiger配置文件
// 	confPath := "/etc/asterisk/pms_api.conf"
// 	cfg, err := ini.Load(confPath)
// 	if err != nil {
// 		lfshook.NewLogger().Error(err)
// 		return
// 	}
// 	ZOHO_URL := cfg.Section("general").Key("zohoUrl").String()
// 	if ZOHO_URL == "" {
// 		lfshook.NewLogger().Error("/etc/asterisk/pms_api.conf not set zohoUrl")
// 		return
// 	}

// 	// var getURL string
// 	fmt.Println("Context = ", event["Context"])
// 	// 呼叫发起事件
// 	// if event["Event"] == "DialBegin" && event["Context"] == "macro-stdexten" {
// 	// if event["Event"] == "DialBegin" && strings.Compare(event["Context"], "macro-stdexten") == 0 {
// 	if event["Event"] == "DialBegin" {

// 		/* ===================先放这里测试用 ============================================================
// 		// 记录开始时间
// 		TimestampList[event["Uniqueid"]] = event["Timestamp"]
// 		// StartTimeList[event["Uniqueid"]] = time.Now().Format("2006-01-02 15:04:09")
// 		StartTimeList[event["Uniqueid"]] = time.Now()
// 		/* ===================先放这里测试用 ============================================================
// 		fmt.Printf("Uniqueid=%s\n", event["Uniqueid"])
// 		fmt.Printf("Timestamp=%s\n", event["Timestamp"])

// 		TimestampTmp, err := strconv.Atoi(event["Timestamp"]) // 不要
// 		if err != nil {
// 			fmt.Printf("转换出错: %v\n", err)
// 			return
// 		}
// 		fmt.Printf("TimestampAtoi=%d\n", TimestampTmp)

// 		TimestampTmp002, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
// 		if err != nil {
// 			fmt.Printf("转换出错: %v\n", err)
// 			return
// 		}
// 		fmt.Printf("TimestampParseFloat=%f\n", TimestampTmp002)

// 		// * ===================================================================================== */

// 		// Incoming Call - Ringing
// 		if event["Context"] == "macro-stdexten" {
// 			// if strings.Compare(event["Context"], "macro-stdexten") == 0 {  // OK
// 			// https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ringing&id=10033&from=12300000001&to=123456789
// 			// getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["Exten"], callDest) // 取得from to 可能不准
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["DestConnectedLineNum"], event["DestCallerIDNum"])

// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)

// 			// Outgoing Call - Ringing
// 		} else if event["Context"] == "macro-trunkdial-failover" {
// 			// https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=ringing&id=10031&from=123456789&to=12300000001
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["DestConnectedLineNum"], event["DestCallerIDNum"])
// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)
// 		}

// 		// 呼叫已连接事件
// 	} else if event["Event"] == "BridgeEnter" {
// 		// Incoming Call - Answered
// 		if event["Context"] == "macro-stdexten" {
// 			// 记录开始时间
// 			// TimestampList[event["Uniqueid"]] = event["Timestamp"] // Uniqueid 有时通话也不合适  NG  // 都改为 Linkedid
// 			// StartTimeList[event["Uniqueid"]] = time.Now()         // Uniqueid 有时通话也不合适  NG  // 都改为 Linkedid
// 			TimestampList[event["Linkedid"]] = event["Timestamp"] // 呼入时设置 Uniqueid 不是 Linkedid
// 			StartTimeList[event["Linkedid"]] = time.Now()         // 呼入时设置 Uniqueid 不是 Linkedid

// 			// https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=answered&id=10023&from=12300000001&to=123456789
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"])
// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)

// 			// Outgoing Call - Answered
// 		} else if event["Context"] == "macro-trunkdial-failover" && event["Priority"] == "1" { // 注意这里选择 Priority:1 的，便于确认 CallerIDNum，ConnectedLineNum
// 			// 记录开始时间
// 			// TimestampList[event["Uniqueid"]] = event["Timestamp"] // error 需要把 Uniqueid 改为 Linkedid
// 			// StartTimeList[event["Uniqueid"]] = time.Now()         // error 需要把 Uniqueid 改为 Linkedid
// 			TimestampList[event["Linkedid"]] = event["Timestamp"]
// 			StartTimeList[event["Linkedid"]] = time.Now()

// 			// https: //www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=answered&id=10003&from=123456789&to=12300000001
// 			// getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"])
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDNum"])
// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)
// 		}

// 		// 呼叫挂断事件
// 	} else if event["Event"] == "HangupRequest" {
// 		/* ===================先放这里测试用 ============================================================
// 		// 记录结束时间
// 		// TimestampList[event["Uniqueid"]] = event["Timestamp"]
// 		// startTimeStamp := int64(TimestampList[event["Uniqueid"]])

// 		fmt.Println("startTimeStamp Str: ", TimestampList[event["Uniqueid"]])
// 		// keyTmp := event["Uniqueid"]
// 		// fmt.Println("keyTmp: ", keyTmp)
// 		// fmt.Println("startTimeStamp Str: ", TimestampList[keyTmp])

// 		startTimeStamp, err := strconv.ParseFloat(TimestampList[event["Uniqueid"]], 64) // OK
// 		if err != nil {
// 			fmt.Printf("startTimeStamp转换出错: %v\n", err)
// 			return
// 		}
// 		fmt.Printf("startTimeStamp=%f\n", startTimeStamp)

// 		endTimeStamp, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
// 		if err != nil {
// 			fmt.Printf("endTimeStamp转换出错: %v\n", err)
// 			return
// 		}
// 		fmt.Printf("endTimeStamp=%f\n", endTimeStamp)

// 		durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
// 		fmt.Println("durationTime=", durationTime)
// 		// 删除记录时间
// 		// delete(TimestampList, event["Uniqueid"])
// 		// * ===================================================================================== */
// 		// Incoming Call - Ended
// 		// if event["Context"] == "macro-stdexten" {  // Context:DialPlan1
// 		if event["Context"] != "macro-trunkdial-failover" {
// 			// 获取时间
// 			// durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
// 			// startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
// 			durationTime := getDuration(event["Linkedid"], event["Timestamp"])
// 			startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
// 			fmt.Println("startTime: ", startTime)

// 			// https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ended&id=100&from=12300000001&to=123456789&start_time=2024-12-04 10:32:10&duration=223
// 			// getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDName"], startTime, durationTime)

// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)

// 			// Outgoing Call - Ended
// 		} else if event["Context"] == "macro-trunkdial-failover" {
// 			// 获取时间
// 			// durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
// 			durationTime := getDuration(event["Linkedid"], event["Timestamp"])
// 			// /* ===================测试用 ============================================================
// 			// startTime, _ := time.Parse("2006-01-02 15:04:05", TimestampList[event["Uniqueid"]]) // error   1734328213.774410  =>  0001-01-01 00:00:00 +0000 UTC
// 			// startTime := StartTimeList[event["Uniqueid"]]
// 			// startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
// 			startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
// 			fmt.Println("startTime: ", startTime)
// 			// durationTime002 := getDuration002(startTime)
// 			// durationTime002 := time.Now().Sub(StartTimeList[event["Uniqueid"]]) // ok    durationTime002:  7.78408849s   // should use time.Since instead of time.Now().Sub (S1012)
// 			// durationTime002 := time.Since(StartTimeList[event["Uniqueid"]]) // ok    durationTime002:  11.611233458s
// 			// fmt.Println("durationTime002: ", durationTime002)
// 			// * ===================================================================================== */

// 			// 删除记录时间
// 			delete(StartTimeList, event["Linkedid"])

// 			// https://www.zohoapis.com/phonebridge/v3/callnotify?type=dailed&state=ended&id=10030&from=123456789&to=12300000001&start_time=2024-12-04 11:32:15&duration=325
// 			getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
// 			// getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDNum"], startTime, durationTime)
// 			fmt.Println("getURL = ", getURL)
// 			go httpclient.ZohoGet(getURL)
// 		}
// 	}
// 	// fmt.Println("getURL = ", getURL)

// 	// 测试验证下上面有没有删除，以防TimestampList越来越大
// 	for k, v := range TimestampList {
// 		fmt.Printf("===Linkedid:%s   Timestamp:%s===\n", k, v)
// 	}

// 	// 按编号搜索API 暂时用的以下接口
// 	// group.GET("/vtiger/lookup", contactsInfo) // 按编号搜索

// }

// // 使用事件中event["Timestamp"]的值计算时间间隔
// // func getDuration(uniqueid string, timeStamp string) int {
// func getDuration(linkedid string, timeStamp string) int { // 都改为 Linkedid

// 	fmt.Println("startTimeStamp Str: ", TimestampList[linkedid])
// 	if TimestampList[linkedid] == "" || timeStamp == "" {
// 		fmt.Printf("linkedid 或 timeStamp 为空\n")
// 		return 9999
// 	}

// 	startTimeStamp, err := strconv.ParseFloat(TimestampList[linkedid], 64)
// 	if err != nil {
// 		fmt.Printf("startTimeStamp转换出错: %v\n", err)
// 		return 9999
// 	}
// 	fmt.Printf("startTimeStamp=%f\n", startTimeStamp)

// 	endTimeStamp, err := strconv.ParseFloat(timeStamp, 64)
// 	if err != nil {
// 		fmt.Printf("endTimeStamp转换出错: %v\n", err)
// 		return 9999
// 	}
// 	fmt.Printf("endTimeStamp=%f\n", endTimeStamp)

// 	durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
// 	// fmt.Println("durationTime=", durationTime)                   // durationTime= 35s
// 	// fmt.Printf("durationTime=%d\n", durationTime)                // durationTime=35000000000
// 	// fmt.Printf("durationTime=%d\n", durationTime.Seconds())      // durationTime=%!d(float64=35)
// 	// fmt.Printf("durationTime=%f\n", durationTime.Seconds())      // durationTime=35.000000
// 	fmt.Printf("durationTime=%d\n", int(durationTime.Seconds())) // durationTime=35

// 	// durationTime001 := time.Duration(endTimeStamp - startTimeStamp)
// 	// fmt.Println("durationTime001=", durationTime001) // durationTime001= 35ns

// 	// durationTime003 := time.Duration(endTimeStamp - startTimeStamp).Seconds()
// 	// fmt.Println("durationTime003=", durationTime003) // durationTime003= 3.5e-08

// 	// 删除记录时间
// 	delete(TimestampList, linkedid)

// 	// return durationTime
// 	return int(durationTime.Seconds())
// }

// // // 程序中取时间计算间隔多少秒
// // func getDuration002(startTime string) time.Duration {
// // 	// durationTime := endTime.Sub(startTime)
// // 	startTime002, err := time.Parse("2006-01-02 15:04:05", startTime)
// // 	if err != nil {
// // 		fmt.Println("Error parsing time:", err)
// // 		return 0
// // 	}
// // 	durationTime := time.Now().Sub(startTime002)
// // 	return durationTime

// // }
