package batch_msg

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/batchmsg"

	"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 GetBatchMsgByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetBatchMsgByIdLogic) GetBatchMsgById(req *types.IDReq) (*types.BatchMsgInfoResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	data, err := l.svcCtx.DB.BatchMsg.Query().Where(
		batchmsg.ID(req.Id),
		batchmsg.OrganizationID(organizationId),
	).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errorx.NewInvalidArgumentError("群发消息不存在")
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	labels, groupLables := make([]uint64, 0), make([]uint64, 0)
	tagMap := make(map[string][]uint64)
	err = json.Unmarshal([]byte(data.Tagids), &tagMap)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	labels = tagMap["contact_tag"]
	groupLables = tagMap["group_tag"]

	return &types.BatchMsgInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.BatchMsgInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:       &data.Status,
			BatchNo:      &data.BatchNo,
			TaskName:     &data.TaskName,
			Fromwxid:     &data.Fromwxid,
			Msg:          &data.Msg,
			Tag:          &data.Tag,
			Total:        &data.Total,
			Success:      &data.Success,
			Fail:         &data.Fail,
			Type:         &data.Type,
			Ctype:        &data.Ctype,
			StartTime:    pointy.GetUnixMilliPointer(data.StartTime.UnixMilli()),
			StopTime:     pointy.GetUnixMilliPointer(data.StopTime.UnixMilli()),
			SendTime:     pointy.GetUnixMilliPointer(data.SendTime.UnixMilli()),
			StartTimeStr: pointy.GetPointer(data.StartTime.Format("2006-01-02 15:04:05")),
			Labels:       labels,
			GroupLabels:  groupLables,
		},
	}, nil
}
