package logic

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

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

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

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

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

// 信息分发
func (l *MsgDistributorLogic) MsgDistributor(in *bxsubscribe.MsgDistributorReq) (*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 regin, pushIds, staffs []string
	staffs = strings.Split(in.Staffs, ",")
	var pushCas []*model.PushCa
	for _, id := range strings.Split(in.MessageId, ",") {
		if id != "" {
			pushIds = append(pushIds, id)
		}
	}
	if len(pushIds) == 0 || in.Staffs == "" {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "缺少参数"}, nil
	}
	//获取分发信息的地区
	infoRes := IC.BaseServiceMysql.SelectBySql(fmt.Sprintf("SELECT infoid FROM push.pushentniche WHERE id in('%s')", strings.Join(pushIds, "','")))
	if infoRes == nil || len(*infoRes) == 0 {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "获取分发地区异常"}, nil
	}
	for _, m := range *infoRes {
		if infoId, _ := m["infoid"].(string); infoId != "" {
			pushCas = append(pushCas, &model.PushCa{InfoId: infoId})
		}
	}
	infoList := model.NewSubscribePush().GetInfoByIds(IC.MgoBidding, IC.DB.Mongo.Bidding.Collection, IC.DB.Mongo.Bidding.CollectionBack, pushCas, false)
	for _, info := range infoList {
		if info.Area != "" && info.Area != "全国" {
			regin = append(regin, info.Area)
		}
	}
	//区域人员校验
	userArr := model.Distributor(regin, common.IntAll(in.EntId), common.IntAll(in.EntUserId))
	for _, uid := range staffs {
		check := false
		for _, user := range userArr {
			if user.Id == common.IntAll(uid) {
				check = true
				break
			}
		}
		if !check {
			return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "选择人员异常"}, nil
		}
	}
	//查询分发信息内容
	msgRes := IC.BaseServiceMysql.SelectBySql(fmt.Sprintf("SELECT * FROM push.pushentniche WHERE id in ('%s') and entid =?  ", strings.Join(pushIds, "','")), in.EntId)
	if msgRes == nil || len(*msgRes) == 0 {
		return &bxsubscribe.StatusResp{ErrorCode: -1, ErrorMsg: "获取分发信息内容异常"}, nil
	}
	//分发数据库修改
	ok := IC.BaseServiceMysql.ExecTx("分发数据库修改", func(tx *sql.Tx) bool {
		insertRow := []string{"entid", "deptid", "infoid", "matchkeys", "type", "product", "matchways", "matchitems", "disid", "area", "city", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count", "source", "date", "userid", "isvisit", "visittime", "pid"}
		msgItems := []string{"entid", "deptid", "infoid", "matchkeys", "type", "product", "matchways", "matchitems", "disid", "area", "city", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count"}
		row := []string{"userid", "entid", "infoid", "createtime"}
		values := []interface{}{}
		dateNew := time.Now().Unix()
		for _, m := range *msgRes {
			var msgValues, insertValue []interface{}
			for _, key := range msgItems {
				msgValues = append(msgValues, m[key])
			}
			for _, uid := range staffs {
				insertValue = append(insertValue, msgValues...)
				insertValue = append(insertValue, []interface{}{3, dateNew, uid, nil, nil, m["id"]}...)
				values = append(values, uid, m["entid"], m["infoid"], date.NowFormat(date.Date_Full_Layout))
			}
			affected, _ := IC.BaseServiceMysql.InsertBatchByTx(tx, "push.pushentniche", insertRow, insertValue)
			if affected == 0 {
				return false
			}
		}
		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
}
