package psap_ticket_monitor

import (
	"encoding/json"
	"fmt"
	"net/http"

	ueCallBackTicket "be.ems/features/ue/mf_callback_ticket"
	"be.ems/lib/log"
	"be.ems/src/framework/cron"
	"be.ems/src/framework/logger"
	neService "be.ems/src/modules/network_element/service"
)

var NewProcessor = &PsapTicketMonitor{
	callbackTicketService: ueCallBackTicket.NewCallbackTicketService(),
	count:                 0,
}

// PsapTicketMonitor 工单处理超时监控
type PsapTicketMonitor struct {
	callbackTicketService *ueCallBackTicket.CallbackTicketService // 回调工单服务
	count                 int                                     // 执行次数
}

func (s *PsapTicketMonitor) Execute(data any) (any, error) {
	s.count++ // 执行次数加一
	options := data.(cron.JobData)
	sysJob := options.SysJob
	logger.Infof("执行工单监控任务 %v 任务ID %s", options.Repeat, sysJob.JobID)

	// 返回结果，用于记录执行结果
	result := map[string]any{
		"count": s.count,
	}

	// 处理超时的NEW状态工单 (30分钟)
	newTicketsUpdated, err := s.handleTimeoutTickets(
		ueCallBackTicket.TicketStatusNew.Enum(),
		30*60*1000000, // 30分钟(微秒)
	)
	if err != nil {
		logger.Errorf("处理NEW状态超时工单失败: %v", err)
	}
	result["newTicketsUpdated"] = newTicketsUpdated

	// 处理超时的IN_PROGRESS状态工单 (60分钟)
	inProgressTicketsUpdated, err := s.handleTimeoutTickets(
		ueCallBackTicket.TicketStatusInProgress.Enum(),
		60*60*1000000, // 60分钟(微秒)
	)
	if err != nil {
		logger.Errorf("处理IN_PROGRESS状态超时工单失败: %v", err)
	}
	result["inProgressTicketsUpdated"] = inProgressTicketsUpdated

	// 处理超时的NO_ANSWER_1状态工单 (4小时)
	noAnswer1TicketsUpdated, err := s.handleTimeoutTickets(
		ueCallBackTicket.TicketStatusNoAnswer1.Enum(),
		4*60*60*1000000, // 4小时(微秒)
	)
	if err != nil {
		logger.Errorf("处理NO_ANSWER_1状态超时工单失败: %v", err)
	}
	result["noAnswer1TicketsUpdated"] = noAnswer1TicketsUpdated

	// 处理超时的NO_ANSWER_2状态工单 (8小时)
	noAnswer2TicketsUpdated, err := s.handleTimeoutTickets(
		ueCallBackTicket.TicketStatusNoAnswer2.Enum(),
		8*60*60*1000000, // 8小时(微秒)
	)
	if err != nil {
		logger.Errorf("处理NO_ANSWER_2状态超时工单失败: %v", err)
	}
	result["noAnswer2TicketsUpdated"] = noAnswer2TicketsUpdated

	// 汇总结果
	totalUpdated := newTicketsUpdated + inProgressTicketsUpdated + noAnswer1TicketsUpdated + noAnswer2TicketsUpdated
	result["totalUpdated"] = totalUpdated

	logger.Infof("工单监控任务完成，共处理 %d 个超时工单", totalUpdated)
	return result, nil
}

// handleTimeoutTickets 处理指定状态的超时工单
func (s *PsapTicketMonitor) handleTimeoutTickets(status string, timeoutMicros int64) (int, error) {
	// 查询超时的工单
	tickets, err := s.callbackTicketService.FindTimeoutTickets(status, timeoutMicros)
	if err != nil {
		return 0, err
	}

	if len(tickets) == 0 {
		return 0, nil // 没有超时工单
	}

	// 更新超时工单状态
	var updatedCount int
	for _, ticket := range tickets {
		// 获取网元信息
		neInfo := neService.NewNeInfo.SelectNeInfoByRmuid(ticket.RmUid)
		// 构造网元MF的API地址
		url := fmt.Sprintf("http://%s:%d/ne/config/data?neType=%s&neId=%s&paramName=agents",
			neInfo.IP, neInfo.Port, neInfo.NeType, neInfo.NeId)
		// 发送HTTP请求获取座席列表
		resp, err := http.Get(url)
		if err != nil {
			log.Error("Failed to get MF agents", err)
			continue
		}
		defer resp.Body.Close()

		// 解析座席列表响应
		var agentResp struct {
			Code int                          `json:"code"`
			Data []ueCallBackTicket.AgentInfo `json:"data"`
			Msg  string                       `json:"msg"`
		}

		if err := json.NewDecoder(resp.Body).Decode(&agentResp); err != nil {
			log.Error("Failed to decode MF agents response", err)
			continue
		}

		if err := s.callbackTicketService.UpdateTicketToTimeout(&ticket, status, agentResp.Data); err != nil {
			log.Errorf("更新工单 %d 状态失败: %v", ticket.TicketId, err)
			continue
		}
		updatedCount++
		log.Infof("工单 %d 已更新为超时状态 (原状态: %s)", ticket.TicketId, status)
	}

	return updatedCount, nil
}
