package biz

import (
	"ai_scheduler/internal/biz/handle/qywx"
	"ai_scheduler/internal/data/constants"
	errors "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/data/impl"
	"ai_scheduler/internal/data/model"
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/l_request"
	"ai_scheduler/internal/tools/bbxt"
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	"ai_scheduler/internal/config"

	"xorm.io/builder"
)

// AiRouterBiz 智能路由服务
type QywxAppBiz struct {
	conf             *config.Config
	botGroupQywxImpl *impl.BotGroupQywxImpl
	qywxGroupHandle  *qywx.Group
	qywxOtherHandle  *qywx.Other
}

// NewDingTalkBotBiz
func NewQywxAppBiz(
	conf *config.Config,
	botGroupQywxImpl *impl.BotGroupQywxImpl,
	qywxGroupHandle *qywx.Group,
	qywxOtherHandle *qywx.Other,
) *QywxAppBiz {
	return &QywxAppBiz{
		conf:             conf,
		botGroupQywxImpl: botGroupQywxImpl,
		qywxGroupHandle:  qywxGroupHandle,
		qywxOtherHandle:  qywxOtherHandle,
	}
}

func (q *QywxAppBiz) InitGroup(ctx context.Context) (string, error) {
	chatId := pkg.RandomString(q.conf.Qywx.ChatIdLen)
	GroupInfo := &model.AiBotGroupQywx{
		Title:     "bot_group_" + time.Now().Format(time.DateOnly),
		ChatID:    chatId,
		ConfigID:  q.conf.Qywx.DefaultConfigId,
		AppSecret: q.conf.Qywx.AppSecret,
	}
	_, err := q.botGroupQywxImpl.Add(GroupInfo)
	if err != nil {
		return "", err
	}
	resp, err := q.qywxGroupHandle.Create(
		ctx,
		qywx.GroupCreateReq{
			Name:     GroupInfo.Title,
			Chatid:   GroupInfo.ChatID,
			Userlist: strings.Split(q.conf.Qywx.InitAccount, ","),
		},
		q.conf.Qywx.CorpId,
		GroupInfo.AppSecret,
	)
	if err != nil {
		return "", err
	}
	return resp.Chatid, nil
}

func (q *QywxAppBiz) GetGroupInfo(ctx context.Context, groupId int) (group model.AiBotGroupQywx, err error) {

	cond := builder.NewCond()
	cond = cond.And(builder.Eq{"group_id": groupId})
	cond = cond.And(builder.Eq{"status": constants.Enable})
	err = q.botGroupQywxImpl.GetOneBySearchToStrut(&cond, &group)

	return
}

func (q *QywxAppBiz) SendReport(ctx context.Context, groupInfo *model.AiBotGroupQywx, report *bbxt.ReportRes) (err error) {
	//confitent := fmt.Sprintf("%s\n%s", report.Title, fmt.Sprintf("![图片](%s)", report.Url))

	upload, err := q.qywxOtherHandle.UploadMediaWithUrl(ctx, report.Url, "image", q.conf.Qywx.CorpId, groupInfo.AppSecret)
	if err != nil {
		return
	}

	err = q.qywxGroupHandle.SendText(ctx, qywx.GroupSendTextReq{
		Chatid: groupInfo.ChatID,
		Text: qywx.Text{
			Content: report.ReportName + "\n" + report.Title,
		},
	}, q.conf.Qywx.CorpId, groupInfo.AppSecret)
	if err != nil {
		return
	}
	err = q.qywxGroupHandle.SendImg(ctx, qywx.GroupSendImgReq{
		Chatid: groupInfo.ChatID,
		Image: qywx.Image{
			MediaId: upload.MediaId,
		},
	}, q.conf.Qywx.CorpId, groupInfo.AppSecret)
	if err != nil {
		return
	}
	return
}

// SendReportV2 发送到货易通指定的群聊
func (q *QywxAppBiz) SendReportHYT(ctx context.Context, groupInfo *model.AiBotGroupQywx, report *bbxt.ReportRes) (err error) {

	if report == nil {
		return fmt.Errorf("report is nil")
	}
	// 文本消息
	err = q.sendReportHYT(groupInfo, &bbxt.ReportRes{
		Title: report.Title,
	})
	if err != nil {
		return err
	}

	time.Sleep(1 * time.Second) // 等待1秒，避免被频控

	// 图片消息
	err = q.sendReportHYT(groupInfo, &bbxt.ReportRes{
		ReportName: report.ReportName,
		Url:        report.Url,
	})
	if err != nil {
		return err
	}

	time.Sleep(1 * time.Second) // 等待1秒，避免被频控

	return nil
}

func (q *QywxAppBiz) sendReportHYT(groupInfo *model.AiBotGroupQywx, report *bbxt.ReportRes) (err error) {
	req := l_request.Request{
		Method: "POST",
		Url:    "https://hyt.86698.cn/admin_upload/api/v1/sendWxCommon",
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
		Json: map[string]interface{}{
			"room_id":   groupInfo.ChatID,  //	群ID
			"oss_url":   report.Url,        // 图片URL
			"file_type": 2,                 //	文件类型，2:图片
			"file_name": report.ReportName, //	 文件名称
			"content":   report.Title,      //  输入文本，此处有值就走文本发送，没有就走文件发送
		},
	}

	resp, err := req.Send()
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return errors.SysErrf("发送到货易通群聊失败，状态码：%d", resp.StatusCode)
	}

	// 记录相应结果日志
	log.Printf("发送到货易通群聊成功，状态码：%d, 响应体：%s", resp.StatusCode, resp.Text)

	return nil
}
