package sop_task

import (
	"context"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqljson"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/errorx"
	"net/http"
	"wechat-api/ent/soptask"
	"wechat-api/ent/wx"
	"wechat-api/hook"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiSopTaskListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApiSopTaskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiSopTaskListLogic {
	return &GetApiSopTaskListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetApiSopTaskListLogic) GetApiSopTaskList(req *types.SopApiListReq, r *http.Request) (*types.SopTaskListResp, error) {
	tokenStr := r.Header.Get("Authorization")
	_, err := hook.CheckDesktopAuth(tokenStr, l.svcCtx.DB)
	if err != nil {
		return nil, errorx.NewCodeInvalidArgumentError("check auth failed")
	}

	data, err := l.svcCtx.DB.SopTask.Query().Where(soptask.StatusEQ(uint8(3))).Where(func(s *sql.Selector) {
		s.Where(sqljson.ValueContains("token", tokenStr))
	}).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
	}

	resp := &types.SopTaskListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		wxInfos, _ := l.svcCtx.DB.Wx.Query().Where(wx.WxidIn(v.BotWxidList...)).All(l.ctx)
		var botWxidList []string
		for _, b := range wxInfos {
			botWxidList = append(botWxidList, b.Nickname)
		}
		resp.Data.Data = append(resp.Data.Data, types.SopTaskInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &v.ID,
				CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			},
			Status:        &v.Status,
			Name:          &v.Name,
			BotWxidList:   botWxidList,
			Type:          &v.Type,
			PlanStartTime: pointy.GetUnixMilliPointer(v.PlanStartTime.UnixMilli()),
			PlanEndTime:   pointy.GetUnixMilliPointer(v.PlanEndTime.UnixMilli()),
			CreatorId:     &v.CreatorID,
			Token:         v.Token,
		})
	}

	return resp, nil
}
