package action

import (
	"crm-api/internal/app/ami"
	"crm-api/pkg/lfshook"
	"crm-api/pkg/utils"
	"errors"
	"strconv"
	"strings"
)

type CoreShowChannelResVO struct {
	CallerIDName      string `json:"callerIDName"`
	CallerIDNum       string `json:"callerIDNumber"`
	Channel           string `json:"channel"`
	ConnectedLineName string `json:"connectedLineName"`
	ConnectedLineNum  string `json:"connectedLineNumber"`
	Duration          string `json:"duration"`
	DurationSecond    int    `json:"durationSecond"`
}

// CoreShowChannels 获取通话通道
func CoreShowChannels() (result []CoreShowChannelResVO, err error) {
	// 通过 src 查询对应通道
	_, events, err := ami.AminInstance.Send(map[string]string{
		"Action": "CoreShowChannels",
	})
	if err != nil {
		lfshook.NewLogger().Errorf("core show channels error %+v", err)
		return nil, err
	}

	lfshook.NewLogger().Tracef("events %+v", events)
	result = make([]CoreShowChannelResVO, 0)
	for _, event := range events {
		if event.Data["Event"] == "CoreShowChannel" {
			channel := CoreShowChannelResVO{
				CallerIDName:      event.Data["CallerIDName"],
				CallerIDNum:       event.Data["CallerIDNum"],
				ConnectedLineName: event.Data["ConnectedLineName"],
				ConnectedLineNum:  event.Data["ConnectedLineNum"],
				Channel:           event.Data["Channel"],
				Duration:          event.Data["Duration"],
				DurationSecond:    utils.TimeStringToSecond(event.Data["Duration"]),
			}
			result = append(result, channel)
		}
	}
	lfshook.NewLogger().Tracef("channels %+v", result)
	return result, nil
}

type CoreShowCallsResVO struct {
	Active    int `json:"active"`
	Processed int `json:"processed"`
}

// CoreShowCalls 获取当前通话数量
// Response: Success
// Message: Command output follows
// Output: 66 active calls
// Output: 6090 calls processed
func CoreShowCalls() (result CoreShowCallsResVO, err error) {
	result = CoreShowCallsResVO{}
	data, _, err := ami.AminInstance.Send(map[string]string{
		"Action":  "Command",
		"Command": "core show calls",
	})
	if err != nil {
		lfshook.NewLogger().Errorf("core show calls error %+v", err)
		return result, err
	}
	// lfshook.NewLogger().Infof("data %+v", data)
	lines := strings.Split(data["Output"], "\n")
	for index, line := range lines {
		data := strings.Fields(line)
		if len(data) == 0 {
			continue
		}
		switch index {
		case 0:
			//:0 active calls
			result.Active, _ = strconv.Atoi(data[0])
		case 1:
			//:1 call processed
			result.Processed, _ = strconv.Atoi(data[0])
		}
	}
	return
}

// GetChannelByExten  通过 exten 查询对应通道
func GetChannelByExten(exten string) (channel string, err error) {
	lfshook.NewLogger().Infof("GetChannelByExten %s", exten)
	_, events, err := ami.AminInstance.Send(map[string]string{
		"Action": "CoreShowChannels",
	})
	if err != nil {
		lfshook.NewLogger().Errorf("core show channels error %+v", err)
		return "", err
	}

	for _, event := range events {
		lfshook.NewLogger().Infof("CoreShowChannels event Data %+v", event.Data)
		if event.Data["Event"] == "CoreShowChannel" && event.Data["ConnectedLineNum"] == exten && event.Data["CallerIDNum"] != exten {
			channel = event.Data["Channel"]
			lfshook.NewLogger().Infof("GetChannelByExten get channel %s", channel)
			break
		}
	}
	if channel == "" {
		lfshook.NewLogger().Errorf("not found channel %s", exten)
		return "", errors.New("not found channel")
	}

	return channel, nil
}
