package services

import (
	"ai_scheduler/internal/biz"
	"ai_scheduler/internal/config"
	"context"

	"github.com/gofiber/fiber/v2/log"
)

type CronService struct {
	config         *config.Config
	dingTalkBotBiz *biz.DingTalkBotBiz
	qywxAppBiz     *biz.QywxAppBiz
	groupConfigBiz *biz.GroupConfigBiz
}

func NewCronService(
	config *config.Config,
	dingTalkBotBiz *biz.DingTalkBotBiz,
	qywxAppBiz *biz.QywxAppBiz,
	groupConfigBiz *biz.GroupConfigBiz,
) *CronService {
	return &CronService{
		config:         config,
		dingTalkBotBiz: dingTalkBotBiz,
		qywxAppBiz:     qywxAppBiz,
		groupConfigBiz: groupConfigBiz,
	}
}

func (d *CronService) CronReportSendDingTalk(ctx context.Context) error {
	groupId := d.config.Dingtalk.BotGroupID["bbxt"]
	groupInfo, err := d.dingTalkBotBiz.GetGroupInfo(ctx, groupId)
	if err != nil {
		return err
	}
	if groupInfo.GroupID == 0 {
		return nil
	}
	groupConfig, err := d.groupConfigBiz.GetGroupConfig(ctx, groupInfo.ConfigID)
	if err != nil {
		return err
	}
	if groupConfig.ConfigID == 0 {
		return nil
	}
	reports, err := d.groupConfigBiz.GetReportLists(ctx, groupConfig)
	if err != nil {
		return err
	}

	// for _, report := range reports {
	// 	err = d.dingTalkBotBiz.SendReport(ctx, &groupInfo, report)
	// 	if err != nil {
	// 		log.Error(err)
	// 		continue
	// 	}
	// }

	err = d.dingTalkBotBiz.SendReports(ctx, &groupInfo, reports)
	if err != nil {
		log.Error(err)
		return err
	}
	return nil
}

func (d *CronService) CronReportSendQywx(ctx context.Context) error {
	groupId := d.config.Qywx.BotGroupID["bbxt"]
	groupInfo, err := d.qywxAppBiz.GetGroupInfo(ctx, groupId)
	if err != nil {
		return err
	}
	if groupInfo.GroupID == 0 {
		return nil
	}
	groupConfig, err := d.groupConfigBiz.GetGroupConfig(ctx, groupInfo.ConfigID)
	if err != nil {
		return err
	}
	if groupConfig.ConfigID == 0 {
		return nil
	}
	reports, err := d.groupConfigBiz.GetReportLists(ctx, groupConfig)
	if err != nil {
		return err
	}

	for _, report := range reports {
		// err = d.qywxAppBiz.SendReport(ctx, &groupInfo, report)
		err = d.qywxAppBiz.SendReportHYT(ctx, &groupInfo, report)
		if err != nil {
			log.Error(err)
			continue
		}
	}
	return nil
}
