package dingtalk

import (
	"ai_scheduler/internal/data/constants"
	"ai_scheduler/internal/data/impl"
	"ai_scheduler/internal/data/model"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/l_request"
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"xorm.io/builder"
)

type Dept struct {
	dingDeptImpl *impl.BotDeptImpl
	auth         *Auth
}

func NewDept(dingDeptImpl *impl.BotDeptImpl, auth *Auth) *Dept {
	return &Dept{
		dingDeptImpl: dingDeptImpl,
		auth:         auth,
	}
}

func (d *Dept) GetDeptInfoByDeptIds(ctx context.Context, deptIds []int, authInfo *AuthInfo) (depts []*entitys.Dept, err error) {
	if len(deptIds) == 0 || authInfo == nil {
		return
	}
	var deptsInfo []model.AiBotDept
	cond := builder.NewCond()
	cond = cond.And(builder.Eq{"dingtalk_dept_id": deptIds})
	err = d.dingDeptImpl.GetRangeToMapStruct(&cond, &deptsInfo)
	if err != nil {
		return
	}
	var existDept = make([]int, len(deptsInfo), 0)
	for _, dept := range deptsInfo {
		depts = append(depts, &entitys.Dept{
			DeptId:   int(dept.DeptID),
			Name:     dept.Name,
			ToolList: dept.ToolList,
		})
		existDept = append(existDept, int(dept.DeptID))
	}
	diff := pkg.Difference(deptIds, existDept)
	if len(diff) > 0 {
		deptDo := make([]model.AiBotDept, 0)
		for _, deptId := range diff {
			deptInfo, _err := d.GetDeptInfoFromDingTalk(ctx, deptId, authInfo.AccessToken)
			if _err != nil {
				return nil, _err
			}
			depts = append(depts, &entitys.Dept{
				DeptId: deptInfo.DeptId,
				Name:   deptInfo.Name,
			})
			deptDo = append(deptDo, model.AiBotDept{
				DingtalkDeptID: int32(deptInfo.DeptId),
				Name:           deptInfo.Name,
			})
		}
		if len(deptDo) > 0 {
			_, err = d.dingDeptImpl.Add(deptDo)
			if err != nil {
				return nil, err
			}
		}
	}

	return
}

func (d *Dept) GetDeptInfoFromDingTalk(ctx context.Context, deptId int, token string) (depts DeptResResult, err error) {
	if deptId == 0 || len(token) == 0 {
		return
	}

	req := l_request.Request{
		Method: http.MethodPost,
		Url: constants.GetDingTalkRequestUrl(constants.RequestUrlGetDeptGet, map[string]string{
			"access_token": token,
		}),
		Json: map[string]interface{}{
			"dept_id": deptId,
		},
	}
	res, _err := req.Send()
	if _err != nil {
		err = _err
		return
	}
	var deptInfo DeptRes

	err = json.Unmarshal(res.Content, &deptInfo)
	if err != nil {
		return
	}
	if deptInfo.Errcode != 0 {
		fmt.Errorf("钉钉请求报错:%s", deptInfo.Errmsg)
	}
	return deptInfo.DeptResResult, err

}
