package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	. "app.yhyue.com/moapp/jybase/mongodb"
	"app.yhyue.com/moapp/jybase/redis"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson"
	IC "jyBXSubscribe/rpc/init"
	"jyBXSubscribe/rpc/internal/svc"
	"jyBXSubscribe/rpc/type/bxsubscribe"
	"jyBXSubscribe/rpc/util"
	"log"
)

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

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

// 用户推送信息查看
func (l *UserInfoLogic) UserInfo(in *bxsubscribe.GetUserInfoReq) (*bxsubscribe.GetUserInfoResq, error) {
	// todo: add your logic here and delete this line
	userInfo := &map[string]interface{}{}
	s_email := ""
	s_m_openid := ""
	s_unionid := ""
	userInfo, _ = IC.Mgo.FindById(util.USER, in.UserId, `{"o_pushset":1,"s_m_openid":1,"s_unionid":1}`)
	if userInfo != nil && len(*userInfo) > 0 {
		pushSet := common.ObjToMap((*userInfo)["o_pushset"])
		s_email = common.InterfaceToStr((*pushSet)["s_email"])
		s_m_openid = common.InterfaceToStr((*userInfo)["s_m_openid"])
		s_unionid = common.InterfaceToStr((*userInfo)["s_unionid"])
	}
	if in.PositionType == 1 {
		userInfo, _ = IC.Mgo.FindOne(util.ENTUSER, map[string]interface{}{"i_entid": in.EntId, "i_userid": in.EntUserId})
		if userInfo != nil && len(*userInfo) > 0 {
			pushSet := common.ObjToMap((*userInfo)["o_pushset"])
			s_email = common.InterfaceToStr((*pushSet)["s_email"])
		}
	}
	isSubscribe := false
	isBind := false
	isMerge := false
	if s_m_openid != "" {
		//微信是否关注处理
		subscribeList := &[]map[string]interface{}{}
		subscribeList, _ = IC.Mgo.Find(util.SUBSCRIBE, map[string]interface{}{"s_m_openid": s_m_openid}, `{"l_date":-1}`, `{"s_event":1"}`, true, -1, -1)
		if subscribeList != nil && len(*subscribeList) > 0 {
			s_event := common.InterfaceToStr((*subscribeList)[0]["s_event"])
			if s_event == "subscribe" {
				isSubscribe = true
			}
		}
	}
	//
	//查询用户是否绑定
	if s_unionid != "" {
		isBind = true
	}
	//查询用户是否需要合并
	isMerge = MergeQuery(in.UserId)
	//用户二维码生成处理
	data := map[string]string{
		"userId": in.UserId,
		"source": util.ServiceMap[in.ServiceType],
	}
	bindKey := "Bind_" + in.ServiceType + common.InterfaceToStr(in.BaseUserId)
	redis.Put("other", bindKey, data, -1)
	state := 1
	if isBind {
		if isMerge {
			state = 2
		} else {
			if isSubscribe {
				state = 3
			} else {
				state = 4
			}
		}
	}
	return &bxsubscribe.GetUserInfoResq{
		Data: &bxsubscribe.GetUserInfo{
			Mail:   s_email,
			State:  common.Int64All(state),
			ImgUrl: fmt.Sprintf("/publicapply/getERCode/%s", bindKey), //二维码地址
			AppUrl: fmt.Sprintf(IC.C.AppUrl, "push_set", "pc-pushsettings"),
			ShowWx: isSubscribe,
		},
	}, nil
}

func MergeQuery(userId string) bool {
	var wId, pId string
	tud, _ := IC.Mgo.FindById("user", userId, `{"s_m_phone":1,"s_phone":1,"s_unionid":1,"s_m_openid":1,"s_nickname":1}`)
	s_m_phone, s_phone := common.ObjToString((*tud)["s_m_phone"]), common.ObjToString((*tud)["s_phone"])
	if tud == nil || len(*tud) == 0 {
		log.Println("查询用户身份异常:", userId)
		return false
	}
	//查询是否有对应微信需要合并
	if unionid := common.ObjToString((*tud)["s_unionid"]); unionid != "" && len(unionid) > 11 {
		mud, _ := IC.Mgo.FindOneByField("user", bson.M{"i_appid": 2, "s_unionid": unionid, "_id": bson.M{"$ne": StringTOBsonId(userId)}}, `{"_id":1,"s_nickname":1,"s_phone":1}`)
		if mud != nil && len(*mud) > 0 {
			if common.ObjToString((*tud)["s_phone"]) == "" {
				wId = userId
				pId = BsonIdToSId((*mud)["_id"])
			} else {
				pId = userId
				wId = BsonIdToSId((*mud)["_id"])
			}
			return pId != wId
		}
	}
	//查询是否有对应手机号需要合并
	if s_phone == s_m_phone { //已合并
		return false
	}
	if s_m_phone != "" { //当前用户为微信用户;查询对应的手机号用户
		mud, _ := IC.Mgo.FindOneByField("user", bson.M{"i_appid": 2, "s_phone": s_m_phone, "_id": bson.M{"$ne": StringTOBsonId(userId)}}, `{"_id":1}`)
		if mud != nil && len(*mud) > 0 {
			wId = BsonIdToSId((*tud)["_id"])
			pId = BsonIdToSId((*mud)["_id"])
			return pId != wId
		}
	} else if s_phone != "" { //当前用户为手机号用户;查询对应的微信用户
		mud, _ := IC.Mgo.FindOneByField("user", bson.M{"i_appid": 2, "s_m_phone": s_phone, "_id": bson.M{"$ne": StringTOBsonId(userId)}}, `{"_id":1,"s_nickname":1}`)
		if mud != nil && len(*mud) > 0 {
			wId = BsonIdToSId((*mud)["_id"])
			pId = BsonIdToSId((*tud)["_id"])
			return pId != wId
		}
	}
	return false
}
