package p import ( "fmt" "log" "math/rand" "app.yhyue.com/moapp/jybase/mysql" "strings" "sync" "time" "github.com/donnie4w/go-logger/logger" ) type WxTplMsgCustom struct { FirstData string AdvertCode string } // type WxTplMsgCustoms struct { All *sync.Map Mysql *mysql.Mysql TplId string SceneCode []string } /* 新建结构体 * @Param mysql 数据库实例 * @Param tplId 模板消息id * @Param sceneCode 场景代码 * @Return error */ func NewWxTplMsgCustoms(m *mysql.Mysql, tplId string, sceneCode ...string) *WxTplMsgCustoms { return &WxTplMsgCustoms{ All: &sync.Map{}, Mysql: m, TplId: tplId, SceneCode: sceneCode, } } //初始化自定义模板消息,如果有异常,程序终止 func (w *WxTplMsgCustoms) ForceVerify() { w.init(true) } //重新加载自定义模板消息 func (w *WxTplMsgCustoms) Reload() { w.init(false) } //初始化自定义模板消息 func (w *WxTplMsgCustoms) init(isVerify bool) { param := []interface{}{w.TplId} wh := []string{} for _, v := range w.SceneCode { param = append(param, v) wh = append(wh, "?") } list := w.Mysql.SelectBySql(`select a.sceneCode,c.firstdata,c.advertCode from scene a inner join template_message b on (a.templateId=b.id and b.templateId=? and a.sceneCode in (`+strings.Join(wh, ",")+`)) inner join template_config c on (a.id=c.sceneId and c.state=1 and c.isTest=1)`, param...) all := map[string][]*WxTplMsgCustom{} if list != nil { for _, v := range *list { sceneCode, _ := v["sceneCode"].(string) sceneCode = strings.TrimSpace(sceneCode) firstdata, _ := v["firstdata"].(string) firstdata = strings.TrimSpace(firstdata) advertCode, _ := v["advertCode"].(string) advertCode = strings.TrimSpace(advertCode) if sceneCode == "" || firstdata == "" { continue } all[sceneCode] = append(all[sceneCode], &WxTplMsgCustom{ FirstData: firstdata, AdvertCode: advertCode, }) } } for k, v := range all { if len(v) > 0 { w.All.Store(k, v) } } w.All.Range(func(key, value interface{}) bool { v, _ := value.([]*WxTplMsgCustom) for _, vv := range v { logger.Info("微信自定义模板消息 id", w.TplId, "场景代码", key, "广告位代码", vv.AdvertCode, "firstData", vv.FirstData) } return true }) for _, v := range w.SceneCode { if len(all[v]) == 0 { msg := fmt.Sprintf("微信自定义模板消息 id %s 场景代码 %s 配置异常", w.TplId, v) if isVerify { log.Fatalln(msg) } else { logger.Error(msg) } } } } /* 随机获取自定义模板消息 * @Param sceneCode 场景代码 */ func (w *WxTplMsgCustoms) Get(sceneCode string) *WxTplMsgCustom { value, ok := w.All.Load(sceneCode) if !ok { return nil } values, _ := value.([]*WxTplMsgCustom) if len(values) == 0 { return nil } r := rand.New(rand.NewSource(time.Now().UnixNano())) return values[r.Intn(len(values))] }