package qywx

import (
	"ai_scheduler/internal/data/impl"
	"ai_scheduler/internal/pkg/l_request"
	"ai_scheduler/internal/pkg/util"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

type Group struct {
	groupImpl *impl.BotGroupQywxImpl
	auth      *Auth
}

func NewGroup(groupImpl *impl.BotGroupQywxImpl, auth *Auth) *Group {
	return &Group{
		groupImpl: groupImpl,
		auth:      auth,
	}
}

// Create 方法用于创建群聊
// 参数:
//   - ctx: context.Context，上下文，用于控制请求的超时和取消
//   - req: GroupCreateReq，创建群聊的请求参数结构体
//   - corpid: string，企业的CorpID
//   - corpsecret: string，应用的Secret
//
// 返回值:
//   - GroupCreateResp: 创建群聊的响应结果
//   - error: 错误信息，如果请求失败则返回错误
func (g *Group) Create(ctx context.Context, req GroupCreateReq, corpid string, corpsecret string) (GroupCreateResp, error) {

	var res GroupCreateResp

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/create", &res, corpid, corpsecret)

	if err != nil {
		return res, err
	}

	return res, nil
}

// SendMarkDown 方法用于发送Markdown格式的消息到群聊
// 参数:
//   - ctx: 上下文信息，用于控制请求的超时和取消
//   - req: 群聊发送Markdown消息的请求参数结构体
//   - corpid: 企业微信corp ID
//   - corpsecret: 企业微信应用的secret
//
// 返回值:
//   - error: 操作过程中发生的错误，如果成功则为nil
func (g *Group) SendMarkDown(ctx context.Context, req GroupSendMarkDownReq, corpid string, corpsecret string) error {

	req.Msgtype = "markdown_v2"

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/send", nil, corpid, corpsecret)

	if err != nil {
		return err
	}

	return nil
}

func (g *Group) SendNews(ctx context.Context, req GroupSendNewsReq, corpid string, corpsecret string) error {

	req.Msgtype = "news"

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/send", nil, corpid, corpsecret)

	if err != nil {
		return err
	}

	return nil
}

func (g *Group) SendImg(ctx context.Context, req GroupSendImgReq, corpid string, corpsecret string) error {

	req.Msgtype = "image"

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/send", nil, corpid, corpsecret)

	if err != nil {
		return err
	}

	return nil
}

func (g *Group) SendMpNews(ctx context.Context, req GroupSendMpNewsReq, corpid string, corpsecret string) error {

	req.Msgtype = "mpnews"

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/send", nil, corpid, corpsecret)

	if err != nil {
		return err
	}

	return nil
}

func (g *Group) SendText(ctx context.Context, req GroupSendTextReq, corpid string, corpsecret string) error {

	req.Msgtype = "text"

	param, _ := util.StructToMap(req)

	_, err := g.request(ctx, param, "https://qyapi.weixin.qq.com/cgi-bin/appchat/send", nil, corpid, corpsecret)

	if err != nil {
		return err
	}

	return nil
}

func (g *Group) request(ctx context.Context, param map[string]interface{}, url string, resData interface{}, corpid string, corpsecret string) ([]byte, error) {
	auth, err := g.auth.GetAccessToken(ctx, corpid, corpsecret)
	if err != nil {
		return nil, err
	}
	req := l_request.Request{
		Method: http.MethodPost,
		Url:    url + "?access_token=" + auth.AccessToken,
		Json:   param,
	}
	res, err := req.Send()
	if err != nil {
		return nil, err
	}
	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("request failed, status code: %d,reason: %s", res.StatusCode, res.Reason)
	}
	var code commonResp
	if err = json.Unmarshal(res.Content, &code); err != nil {
		return nil, fmt.Errorf("返回结构异常：%s", string(res.Content))
	}
	if code.Errcode != 0 {
		return nil, fmt.Errorf("返回状态异常：%s", string(code.Errmsg))
	}
	if resData != nil {
		if err = json.Unmarshal(res.Content, resData); err != nil {
			return nil, fmt.Errorf("返回数据异常：%s", string(res.Content))
		}
	}

	return res.Content, nil
}
