package batch_msg

import (
	"context"
	"encoding/json"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/batchmsg"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetWhatcappBatchMsgLogic) GetWhatcappBatchMsg(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),
		batchmsg.Ctype(2),
	).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()),
			},
			Phone:        &data.Phone,
			Cc:           &data.Cc,
			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,
			TemplateName: &data.TemplateName,
			TemplateCode: &data.TemplateCode,
			Lang:         &data.Lang,
			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
}
