package sop_task

import (
	"context"
	"wechat-api/ent/predicate"
	"wechat-api/ent/soptask"
	"wechat-api/ent/wx"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetSopTaskListLogic) GetSopTaskList(req *types.SopTaskListReq) (*types.SopTaskListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.SopTask
	predicates = append(predicates, soptask.OrganizationIDEQ(organizationId))
	if req.Name != nil {
		predicates = append(predicates, soptask.NameContains(*req.Name))
	}
	if req.CreatorId != nil {
		predicates = append(predicates, soptask.CreatorIDContains(*req.CreatorId))
	}
	data, err := l.svcCtx.DB.SopTask.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

	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,
			})
	}

	return resp, nil
}
