package logic

import (
	"context"
	"database/sql"
	"fmt"
	IC "jyBXSubscribe/rpc/init"
	"jyBXSubscribe/rpc/model"
	"strings"
	"time"

	"app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/encrypt"
	P "app.yhyue.com/moapp/jybase/mapping"
	"app.yhyue.com/moapp/jybase/redis"

	"jyBXSubscribe/rpc/internal/svc"
	"jyBXSubscribe/rpc/type/bxsubscribe"

	"app.yhyue.com/moapp/jybase/date"

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

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

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

// 标讯信息分发
func (l *BidDistributorLogic) BidDistributor(in *bxsubscribe.BidDistributorReq) (*bxsubscribe.StatusResp, error) {
	userEnt := model.EntInfo(common.IntAll(in.EntId), common.IntAll(in.EntUserId))
	if !(userEnt.Role_admin_system || userEnt.Role_admin_department) {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "无权限"}, nil
	}
	//根据信息查询区域列表
	var staffs []string
	staffs = strings.Split(in.Staffs, ",")
	var pushCas []*model.PushCa

	if len(in.InfoIds) == 0 || in.Staffs == "" {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "缺少参数"}, nil
	}

	for _, v := range in.InfoIds {
		pushCas = append(pushCas, &model.PushCa{InfoId: v})
	}
	infoList := model.NewSubscribePush().GetInfoByIds(IC.MgoBidding, IC.DB.Mongo.Bidding.Collection, IC.DB.Mongo.Bidding.CollectionBack, pushCas, false)

	//分发数据库修改
	ok := IC.BaseServiceMysql.ExecTx("分发数据库修改", func(tx *sql.Tx) bool {
		insertRow := []string{"entid", "deptid", "userid", "infoid", "area", "city", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count", "source", "date"}
		row := []string{"userid", "entid", "infoid", "createtime"}
		dateNew := time.Now().Unix()
		insertValue := []interface{}{}
		values := []interface{}{}
		for _, m := range staffs {
			for _, v := range infoList {
				area := common.If((*v).Area == "", nil, P.BidCodeMapping.Area[(*v).Area])
				buyerclass := common.If((*v).BuyerClass == "", nil, P.BidCodeMapping.Buyerclass[(*v).BuyerClass])
				city := common.If((*v).City == "", nil, P.BidCodeMapping.Area[(*v).City])
				toptype := common.If((*v).Toptype == "", nil, P.BidCodeMapping.Toptype[(*v).Toptype])
				subtype := common.If((*v).Subtype == "", nil, P.BidCodeMapping.Subtype[(*v).Subtype])
				scopeclass := common.If((*v).Industry == "", nil, P.BidCodeMapping.Subscopeclass[(*v).Industry])
				budget := common.If((*v).Budget > 0, (*v).Budget, nil)
				bidamount := common.If((*v).BidAmount > 0, (*v).BidAmount, nil)
				attachment_count := common.If((*v).IsValidFile, 1, nil)
				infoidArr := encrypt.DecodeArticleId2ByCheck((*v).XId)
				infoid := ""
				if len(infoidArr) > 0 {
					infoid = infoidArr[0]
				}
				if infoid == "" {
					continue
				}
				insertValue = append(insertValue, in.EntId, 0, m, infoid, area, city, buyerclass, toptype, subtype, scopeclass, budget, bidamount, attachment_count, 3, dateNew)
				values = append(values, m, in.EntId, infoid, date.NowFormat(date.Date_Full_Layout))
			}
		}
		IC.BaseServiceMysql.InsertBatchByTx(tx, "push.pushentniche", insertRow, insertValue)
		IC.BaseServiceMysql.InsertBatchByTx(tx, "base_service.ent_bid_distribute", row, values)
		return true
	})
	//清除推送列表缓存
	for _, staff := range staffs {
		//today
		redis.Del("pushcache_2_b", fmt.Sprintf("entnichepush_%s", staff))
		//all
		redis.Del("pushcache_2_a", fmt.Sprintf("all_entnichepush_%s", staff))
		redis.Del("pushcache_2_a", fmt.Sprintf("all_entnichepush_vip_%s", staff))
		redis.Del("pushcache_2_a", fmt.Sprintf("all_entnichepush_member_%s", staff))
	}
	if !ok {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "数据分发异常"}, nil
	}
	return &bxsubscribe.StatusResp{Status: 1}, nil
}
