package whatsapp

import (
	"context"
	"github.com/alibabacloud-go/cams-20200606/v2/client"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/hook/aliyun"

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

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

func (l *GetWhatsappListLogic) GetWhatsappList(req *types.WhatsappListReq) (*types.WhatsappListResp, error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.Whatsapp

	if isAdmin && req.OrganizationId != nil {
		predicates = append(predicates, whatsapp.OrganizationID(*req.OrganizationId))
	}
	if !isAdmin {
		predicates = append(predicates, whatsapp.OrganizationID(organizationId))
	}
	if req.Phone != nil {
		predicates = append(predicates, whatsapp.Phone(*req.Phone))
	}
	if req.PhoneName != nil {
		predicates = append(predicates, whatsapp.PhoneName(*req.PhoneName))
	}
	
	ids := make([]string, 0)
	if req.WaId != nil && *req.WaId != "" {
		ids = append(ids, *req.WaId)
		predicates = append(predicates, whatsapp.WaID(*req.WaId))
	} else {
		wclist, err := l.svcCtx.DB.WhatsappChannel.Query().All(l.ctx)
		if err != nil {
			return nil, errorx.NewInvalidArgumentError(err.Error())
		}

		for _, v := range wclist {
			ids = append(ids, v.WaID)
		}
	}

	data, err := l.svcCtx.DB.Whatsapp.Query().Where(predicates...).WithAgent().Page(l.ctx, req.Page, req.PageSize)

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

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

	phoneNumbers := make([]*client.QueryChatappPhoneNumbersResponseBodyPhoneNumbers, 0)
	for _, vid := range ids {
		_, err = aliyun.ChatappSyncPhoneNumber(vid)
		if err != nil {
			l.Logger.Errorf("sync chatapp phoneNumber err=%v\n", err)
		}
		result, err := aliyun.QueryCamsChatappPhoneNumbers(vid)
		l.Logger.Infof("result=%v err=%v vid=%v\n", result, err, vid)

		phoneNumbers = append(phoneNumbers, result.Body.PhoneNumbers...)
	}

	for _, v := range data.List {
		organizationName := ""
		if v.OrganizationID > 0 {
			departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: v.OrganizationID})
			if err != nil {
				l.Error("获取部门信息失败", err)
			}
			if departmentInfo != nil {
				organizationName = *departmentInfo.Name
			}
		}

		agent := types.AgentInfo{}
		//l.Logger.Infof("v.agent=%v v=%v\n", v.Edges.Agent, v)
		if v.Edges.Agent != nil {
			agent = types.AgentInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: &v.AgentID,
				},
				Name:       &v.Edges.Agent.Name,
				Role:       &v.Edges.Agent.Role,
				Status:     &v.Edges.Agent.Status,
				Background: &v.Edges.Agent.Background,
				Examples:   &v.Edges.Agent.Examples,
			}
		}

		var phoneStatus, quality, verifyStatus, frequency string
		currentPhone := v.Cc + v.Phone
		for _, v := range phoneNumbers {
			if *v.PhoneNumber == currentPhone {
				phoneStatus = *v.Status
				verifyStatus = *v.CodeVerificationStatus
				quality = *v.QualityRating
				frequency = *v.MessagingLimitTier
				break
			}
		}

		resp.Data.Data = append(resp.Data.Data,
			types.WhatsappInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				WaId:             &v.WaID,
				WaName:           &v.WaName,
				Callback:         &v.Callback,
				Account:          &v.Account,
				Phone:            &v.Phone,
				Cc:               &v.Cc,
				PhoneName:        &v.PhoneName,
				PhoneStatus:      &phoneStatus,
				Quality:          &quality,
				VerifyStatus:     &verifyStatus,
				Frequency:        &frequency,
				OrganizationId:   &v.OrganizationID,
				OrganizationName: &organizationName,
				AgentId:          &v.AgentID,
				AgentInfo:        &agent,
				ApiBase:          &v.APIBase,
				ApiKey:           &v.APIKey,
			})
	}

	return resp, nil
}
