package contact

import (
	"context"
	"time"
	"wechat-api/ent"
	"wechat-api/ent/contactfieldtemplate"
	"wechat-api/ent/label"
	"wechat-api/ent/labelrelationship"
	"wechat-api/ent/wx"

	"wechat-api/ent/contact"
	"wechat-api/ent/predicate"
	"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 GetContactListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func convertLabelToLabelInfo(label *ent.Label) types.LabelInfo {
	return types.LabelInfo{
		BaseIDInfo: types.BaseIDInfo{
			Id:        &label.ID,
			CreatedAt: pointy.GetPointer(label.CreatedAt.UnixMilli()),
			UpdatedAt: pointy.GetPointer(label.UpdatedAt.UnixMilli()),
		},
		Status:     &label.Status,
		Type:       &label.Type,
		Name:       &label.Name,
		From:       &label.From,
		Mode:       &label.Mode,
		Conditions: &label.Conditions,
	}
}

func (l *GetContactListLogic) GetContactList(req *types.ContactListReq) (*types.ContactListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var predicates []predicate.Contact
	if req.WxWxid == nil || (req.WxWxid != nil && !isAdmin) {
		predicates = append(predicates, contact.OrganizationIDEQ(organizationId))
	}
	if req.Status != nil {
		predicates = append(predicates, contact.StatusEQ(*req.Status))
	}

	layout := "2006-01-02 15:04:05"
	var startTime, endTime *time.Time

	if req.SearchDate != nil && len(req.SearchDate) == 2 {
		startStr := *req.SearchDate[0] + " 00:00:00"
		if t, err := time.Parse(layout, startStr); err == nil {
			//t = t.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
			startTime = &t
		} else {
			l.Logger.Errorf("invalid startDate: %v", err)
		}
		endStr := *req.SearchDate[1] + " 23:59:59"
		if t, err := time.Parse(layout, endStr); err == nil {
			//t = t.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
			endTime = &t
		} else {
			l.Logger.Errorf("invalid endDate: %v", err)
		}
	}

	var relPreds []predicate.LabelRelationship

	if startTime != nil {
		relPreds = append(relPreds, labelrelationship.CreatedAtGTE(*startTime))
	}
	if endTime != nil {
		relPreds = append(relPreds, labelrelationship.CreatedAtLTE(*endTime))
	}

	if len(req.LabelIDs) > 0 {
		relPreds = append(relPreds,
			labelrelationship.HasLabelsWith(label.IDIn(req.LabelIDs...)),
		)
	}
	if len(relPreds) > 0 {
		predicates = append(predicates, contact.HasContactRelationshipsWith(relPreds...))
	}

	if req.Ctype != nil {
		predicates = append(predicates, contact.Ctype(*req.Ctype))
	} else {
		predicates = append(predicates, contact.Ctype(1)) // 默认 Ctype = 1
	}

	if req.WxWxid != nil {
		predicates = append(predicates, contact.WxWxidContains(*req.WxWxid))
	}
	if req.Wxid != nil {
		predicates = append(predicates, contact.WxidContains(*req.Wxid))
	}
	if req.Account != nil {
		predicates = append(predicates, contact.AccountContains(*req.Account))
	}
	if req.Nickname != nil {
		predicates = append(predicates, contact.NicknameContains(*req.Nickname))
	}
	if req.Type != nil {
		predicates = append(predicates, contact.TypeEQ(*req.Type))
	} else {
		predicates = append(predicates, contact.Or(contact.TypeEQ(1), contact.TypeEQ(2)))
	}

	data, err := l.svcCtx.DB.Contact.Query().Where(predicates...).WithContactRelationships(func(query *ent.LabelRelationshipQuery) {
		query.WithLabels()
	}).WithContactFields(func(query *ent.ContactFieldQuery) {
		query.WithFieldContact()
	}).Page(l.ctx, req.Page, req.PageSize)

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

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

	wxWxids := []string{}
	wxWxidsSet := make(map[string]*ent.Wx)
	blockListSet := make(map[string]struct{})
	groupBlockListSet := make(map[string]struct{})
	for _, v := range data.List {
		wxWxids = append(wxWxids, v.WxWxid)
	}
	wxs, err := l.svcCtx.DB.Wx.Query().Where(wx.WxidIn(wxWxids...)).All(l.ctx)
	for _, w := range wxs {
		wxWxidsSet[w.Wxid] = w
		for _, b := range w.BlockList {
			blockListSet[w.Wxid+"_"+b] = struct{}{}
		}
		for _, g := range w.GroupBlockList {
			groupBlockListSet[w.Wxid+"_"+g] = struct{}{}
		}
	}

	field_template, _ := l.svcCtx.DB.ContactFieldTemplate.Query().
		Where(
			contactfieldtemplate.OrganizationID(organizationId), // Additional filter by organizationId
		).
		Only(l.ctx)

	for _, v := range data.List {
		// 自定义字段
		custom_field := make([]types.ContactFieldTemplate, 0)
		if field_template != nil && len(field_template.Template) > 0 {
			field_set := make(map[string][]string)
			fields := v.Edges.ContactFields
			for _, field := range fields {
				field_set[field.FormID] = field.Value
			}
			for _, template := range field_template.Template {
				template.Value = field_set[*template.Id]

				custom_field = append(custom_field, ConvertCustomToInternal(template))
			}
		}

		isInBlockList := false
		labelRelationships := make([]types.ContactLabelList, 0)
		if v.Edges.ContactRelationships != nil {
			for _, lr := range v.Edges.ContactRelationships {
				if lr.Edges.Labels == nil {
					continue
				}
				labelRelationships = append(labelRelationships, types.ContactLabelList{
					Label: &lr.Edges.Labels.Name,
					Value: &lr.LabelID,
				})
			}
		}
		var wxNickname string
		if wxWxidsSet[v.WxWxid] == nil {
			wxNickname = v.WxWxid
		} else {
			wxNickname = wxWxidsSet[v.WxWxid].Nickname
		}
		if v.Type == 1 {
			if _, exists := blockListSet[v.WxWxid+"_"+"ALL"]; exists {
				isInBlockList = true
			} else {
				_, isInBlockList = blockListSet[v.WxWxid+"_"+v.Wxid]
			}
		} else {
			if _, exists := groupBlockListSet[v.WxWxid+"_"+"ALL"]; exists {
				isInBlockList = true
			} else {
				_, isInBlockList = groupBlockListSet[v.WxWxid+"_"+v.Wxid]
			}
		}

		resp.Data.Data = append(resp.Data.Data,
			types.ContactInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:             &v.Status,
				WxWxid:             &v.WxWxid,
				WxWxidNickname:     &wxNickname,
				Type:               &v.Type,
				Wxid:               &v.Wxid,
				Account:            &v.Account,
				Nickname:           &v.Nickname,
				Markname:           &v.Markname,
				Headimg:            &v.Headimg,
				Sex:                &v.Sex,
				Starrole:           &v.Starrole,
				Dontseeit:          &v.Dontseeit,
				Dontseeme:          &v.Dontseeme,
				Lag:                &v.Lag,
				Gid:                &v.Gid,
				Gname:              &v.Gname,
				V3:                 &v.V3,
				LabelRelationships: labelRelationships,
				IsInBlockList:      &isInBlockList,
				Ctype:              &v.Ctype,
				Cname:              &v.Cname,
				Cage:               &v.Cage,
				Carea:              &v.Carea,
				Cc:                 &v.Cc,
				Phone:              &v.Phone,
				Cbirthday:          &v.Cbirthday,
				Cbirtharea:         &v.Cbirtharea,
				CidcardNo:          &v.CidcardNo,
				Ctitle:             &v.Ctitle,

				CustomFields: custom_field,
			})
	}

	return resp, nil
}
