package logic

import (
	"context"
	"encoding/json"
	"fmt"
	it "jyBXSubscribe/api/init"
	"jyBXSubscribe/api/internal/svc"
	"jyBXSubscribe/api/internal/types"
	. "jyBXSubscribe/entity"
	"jyBXSubscribe/rpc/bxsubscribe"
	"time"

	"app.yhyue.com/moapp/jybase/common"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

//
func (l *SubscribeUpdateLogic) SubscribeUpdate(req *types.SubscribeUpdateReq) (resp *types.CommonResp, err error) {
	resp = &types.CommonResp{}
	if req.UserId == "" {
		return
	} else if KeyWordsRepeat(req.Items) {
		resp.Data = map[string]interface{}{
			"status": -1,
		}
		resp.Err_code, resp.Err_msg = -1, "关键词设置异常"
		return
	}
	su := &SubscribeUpdate{
		Area:            req.Area,
		Buyerclass:      req.Buyerclass,
		Items:           req.Items,
		Infotype:        req.Infotype,
		Matchway:        req.Matchway,
		Projectmatch:    req.Projectmatch,
		Ratemode:        req.Ratemode,
		Apppush:         req.Apppush,
		Mailpush:        req.Mailpush,
		Mail:            req.Mail,
		Otherbuyerclass: req.Otherbuyerclass,
	}
	b, _ := json.Marshal(su)
	rp, err := l.svcCtx.Suscribe.UpdateSubScribeInfo(l.ctx, &bxsubscribe.UpdateSubScribeInfoReq{
		UserId:       req.UserId,
		PositionType: req.PositionType,
		SubSet:       b,
	})
	if err != nil {
		resp.Err_code, resp.Err_msg = -1, "修改失败"
		l.Error(fmt.Sprintf("%+v", req), resp.Err_msg)
	} else {
		it.MgoLog.Save("ovipjy_log", map[string]interface{}{
			"userid":     req.UserId,
			"o_vipjy":    req,
			"createtime": time.Now().Unix(),
			"type":       "o_vipjy",
		})
		resp.Data = map[string]interface{}{
			"status": rp.Status,
		}
	}
	return
}

//判断关键词是否异常,
func KeyWordsRepeat(aitems []map[string]interface{}) bool {
	m := map[string]bool{} //去重的数组
	// 录入的关键词
	i := 0
	for _, items := range aitems {
		for kk, vv := range items {
			if kk == "a_key" {
				for _, n := range common.ObjArrToMapArr(vv.([]interface{})) {
					db_not := []string{}
					db_key := []string{}
					db_append := []string{}
					matchway := 0
					if n["key"] != nil {
						db_key = common.ObjArrToStringArr(n["key"].([]interface{}))
					}
					if n["notkey"] != nil {
						db_not = common.ObjArrToStringArr(n["notkey"].([]interface{}))
					}
					if n["appendkey"] != nil {
						db_append = common.ObjArrToStringArr(n["appendkey"].([]interface{}))
					}
					if n["matchway"] != nil {
						matchway = common.IntAll(n["matchway"])
					}
					key := fmt.Sprintf("%v%v%v%s", db_key, db_append, db_not, matchway)
					if m[key] {
						return true //有重复 不可以提交
					}
					i++
					m[key] = true
				}
			}
		}
	}
	if i > 300 {
		//关键词大于300异常
		return true
	}
	return false
}
