package dingtalk

import (
	errorcode "ai_scheduler/internal/data/error"
	"encoding/json"
	"time"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	notable "github.com/alibabacloud-go/dingtalk/notable_1_0"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

type NotableClient struct {
	cli          *notable.Client
	oauth2Client *Oauth2Client
}

func NewNotableClient(oauth2Client *Oauth2Client) (*NotableClient, error) {
	cfg := &openapi.Config{
		Protocol: tea.String("https"),
		RegionId: tea.String("central"),
	}
	c, err := notable.NewClient(cfg)
	if err != nil {
		return nil, err
	}
	return &NotableClient{cli: c, oauth2Client: oauth2Client}, nil
}

type UpdateRecordReq struct {
	BaseId         string
	SheetId        string
	RecordId       string
	OperatorId     string
	CreatorUnionId string
}

type UpdateRecordsserResp struct {
	Body interface{}
}

func (c *NotableClient) UpdateRecord(appKey AppKey, req *UpdateRecordReq) (bool, error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return false, err
	}

	resp, err := c.cli.UpdateRecordsWithOptions(
		tea.String(req.BaseId),
		tea.String(req.SheetId),
		&notable.UpdateRecordsRequest{
			OperatorId: tea.String(req.OperatorId),
			Records: []*notable.UpdateRecordsRequestRecords{
				{
					Fields: map[string]any{
						"提交人": []map[string]any{
							{
								"unionId": req.CreatorUnionId,
							},
						},
					},
					Id: tea.String(req.RecordId),
				},
			},
		},
		&notable.UpdateRecordsHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return false, err
	}

	if resp.Body == nil {
		return false, errorcode.ParamErrf("empty response body")
	}

	return true, nil
}

type InsertRecordReq struct {
	BaseId         string
	SheetIdOrName  string
	OperatorId     string
	CreatorUnionId string
	Content        string
	AttachmentUrl  string
}

func (c *NotableClient) InsertRecord(accessToken string, req *InsertRecordReq) (string, error) {
	// 默认使用“数据表”
	if req.SheetIdOrName == "" {
		req.SheetIdOrName = "数据表"
	}

	headers := &notable.InsertRecordsHeaders{}
	headers.XAcsDingtalkAccessToken = tea.String(accessToken)
	resp, err := c.cli.InsertRecordsWithOptions(
		tea.String(req.BaseId),
		tea.String(req.SheetIdOrName),
		&notable.InsertRecordsRequest{
			OperatorId: tea.String(req.OperatorId),
			Records: []*notable.InsertRecordsRequestRecords{
				{
					Fields: map[string]any{
						"创建日期": time.Now().Format(time.DateTime),
						"需求内容": req.Content,
						"提交人": []map[string]any{
							{
								"unionId": req.CreatorUnionId,
							},
						},
						"附件": map[string]any{
							"link": req.AttachmentUrl,
						},
					},
				},
			},
		}, headers, &util.RuntimeOptions{})
	if err != nil {
		return "", err
	}

	if resp.Body == nil || resp.Body.Value == nil || len(resp.Body.Value) == 0 {
		return "", errorcode.ParamErrf("empty response body")
	}

	return *resp.Body.Value[0].Id, nil
}

func (c *NotableClient) GetHTTPStatus(err error) int {
	if sdkErr, ok := err.(*tea.SDKError); ok {
		if sdkErr.StatusCode != nil {
			return *sdkErr.StatusCode
		}
		if sdkErr.Data != nil {
			var m struct {
				StatusCode int `json:"statusCode"`
			}
			if json.Unmarshal([]byte(*sdkErr.Data), &m) == nil {
				return m.StatusCode
			}
		}
	}
	return 0 // 0 = 非 HTTP 错误
}
