push.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. package model
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/date"
  5. "app.yhyue.com/moapp/jybase/encrypt"
  6. "app.yhyue.com/moapp/jybase/esv1"
  7. "app.yhyue.com/moapp/jybase/mongodb"
  8. "app.yhyue.com/moapp/jybase/mysql"
  9. "app.yhyue.com/moapp/jybase/redis"
  10. "encoding/json"
  11. "fmt"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. "go.mongodb.org/mongo-driver/bson/primitive"
  14. IC "jyBXSubscribe/rpc/init"
  15. ms "jyBXSubscribe/rpc/model/service"
  16. "jyBXSubscribe/rpc/type/bxsubscribe"
  17. "log"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. //
  24. const (
  25. pageSize = 50
  26. AllSubPushCacheSize = 250
  27. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext"],"from":0,"size":%d}`
  28. mongodb_fields = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":1, "buyerclass":1,"budget":1,"bidamount":1,"s_winner":1,"bidopentime":1,"buyer":1,"projectname":1}`
  29. SubFreeFlag = "fType"
  30. SubVipFlag = "vType"
  31. MemberFlag = "mType"
  32. EntnicheFlag = "eType"
  33. oneDay = 24 * 60 * 60
  34. )
  35. var aboutDbMsg map[string]*AboutDbMsg = map[string]*AboutDbMsg{
  36. SubFreeFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  37. SubVipFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  38. MemberFlag: &AboutDbMsg{"pushmember", "memberpush"},
  39. EntnicheFlag: &AboutDbMsg{"pushentniche", "entnichepush"},
  40. }
  41. type AboutDbMsg struct {
  42. MysqlTable string
  43. RedisKeyFlag string
  44. }
  45. type SubPush struct {
  46. Date string
  47. Datas []*bxsubscribe.SubscribeInfo
  48. Count int64
  49. }
  50. type PushCa struct {
  51. Date int64
  52. InfoId string
  53. Visit int
  54. Index int64
  55. Keys []string
  56. Type int
  57. Isvip int
  58. FileExists bool
  59. }
  60. //查询参数
  61. type SubPushQueryParam struct {
  62. Mgo_bidding mongodb.MongodbSim //
  63. Bidding string //
  64. Bidding_back string //
  65. PushMysql *mysql.Mysql //
  66. UserId string //用户id
  67. PageNum int //页面
  68. PageSize int //每页数量
  69. SelectTime string //时间
  70. Area string //区域
  71. City string //城市
  72. Buyerclass string //采购单位行业
  73. Subtype string //信息类型 二级分类
  74. Subscopeclass string //信息行业
  75. Key string //订阅词
  76. Export bool //导出
  77. EntId string //企业id
  78. Price string //价格
  79. FileExists string //是否有附件;默认全部;1:有附件;-1:无附件
  80. EntUserId string //商机管理用户id
  81. DeptId string //商机管理用户部门id
  82. }
  83. func (spqp *SubPushQueryParam) IsEmpty() bool {
  84. return spqp.SelectTime == "" && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == ""
  85. }
  86. type subscribePush struct {
  87. ModuleFlag string
  88. }
  89. func NewSubscribePush(module ...string) *subscribePush {
  90. m := ""
  91. if len(module) > 0 {
  92. m = module[0]
  93. }
  94. return &subscribePush{m}
  95. }
  96. //从pushcache_2_a中取
  97. func (s *subscribePush) GetTodayCache(userId string) (*SubPush, error) {
  98. pc_a, err := redis.GetNewBytes("pushcache_2_b", s.todayKey(userId))
  99. if err != nil {
  100. return nil, err
  101. }
  102. if pc_a == nil {
  103. return nil, nil
  104. }
  105. var p *SubPush
  106. if err := json.Unmarshal(*pc_a, &p); err != nil {
  107. return nil, err
  108. }
  109. return p, nil
  110. }
  111. //往pushcache_2_a中放
  112. func (s *subscribePush) PutTodayCache(userId string, pc_a *SubPush) {
  113. redis.Put("pushcache_2_b", s.todayKey(userId), pc_a, oneDay)
  114. }
  115. //获取redis key
  116. func (s *subscribePush) todayKey(userId string) string {
  117. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  118. }
  119. func (s *subscribePush) allKey(userId string) string {
  120. return fmt.Sprintf("all_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  121. }
  122. //历史推送记录中单条信息格式化
  123. func (s *subscribePush) InfoFormat(p *PushCa, info *map[string]interface{}) *bxsubscribe.SubscribeInfo {
  124. area := common.ObjToString((*info)["area"])
  125. if area == "A" {
  126. area = "全国"
  127. }
  128. industry := common.ObjToString((*info)["s_subscopeclass"])
  129. scs := strings.Split(industry, ",")
  130. if len(scs) > 0 {
  131. industry = scs[0]
  132. if industry != "" {
  133. iss := strings.Split(industry, "_")
  134. if len(iss) > 0 {
  135. industry = iss[0]
  136. }
  137. }
  138. }
  139. infotype := common.ObjToString((*info)["subtype"])
  140. if infotype == "" {
  141. infotype = common.ObjToString((*info)["toptype"])
  142. }
  143. if infotype == "" {
  144. infotype = common.ObjToString((*info)["type"])
  145. if infotype == "tender" {
  146. infotype = "招标"
  147. } else if infotype == "bid" {
  148. infotype = "中标"
  149. }
  150. }
  151. _id := p.InfoId
  152. if _id == "" {
  153. _id = common.ObjToString((*info)["_id"])
  154. }
  155. return &bxsubscribe.SubscribeInfo{
  156. XId: encrypt.EncodeArticleId2ByCheck(_id),
  157. Title: common.ObjToString((*info)["title"]),
  158. Area: area,
  159. BuyerClass: common.ObjToString((*info)["buyerclass"]),
  160. Subtype: infotype,
  161. Industry: industry,
  162. PublishTime: common.Int64All((*info)["publishtime"]),
  163. CaIndex: p.Index,
  164. CaDate: p.Date,
  165. CaIsvisit: int64(p.Visit),
  166. CaIsvip: int64(p.Isvip),
  167. CaType: int64(p.Type),
  168. MatchKeys: p.Keys,
  169. Budget: common.ObjToString((*info)["budget"]),
  170. BidAmount: common.ObjToString((*info)["bidamount"]),
  171. Buyer: common.ObjToString((*info)["buyer"]),
  172. ProjectName: common.ObjToString((*info)["projectname"]),
  173. Winner: common.ObjToString((*info)["s_winner"]),
  174. BidOpenTime: common.ObjToString((*info)["bidopentime"]),
  175. CaFileExists: p.FileExists,
  176. }
  177. }
  178. func (s *subscribePush) Datas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  179. logx.Info(spqp.UserId, s.ModuleFlag, "subscribePush query param:", "SelectTime:", spqp.SelectTime, "Area:", spqp.Area, "City:", spqp.City, "Subtype:", spqp.Subtype, "Subscopeclass:", spqp.Subscopeclass, "Buyerclass:", spqp.Buyerclass, "Key:", spqp.Key, "PageNum:", spqp.PageNum, "Price:", spqp.Price, "FileExists:", spqp.FileExists)
  180. if spqp.UserId == "" {
  181. return
  182. }
  183. if spqp.PageNum < 1 {
  184. spqp.PageNum = 1
  185. }
  186. if spqp.PageSize < 1 || spqp.PageSize > pageSize {
  187. if !spqp.Export {
  188. spqp.PageSize = pageSize
  189. } else { //数据导出查询20000条限制
  190. if spqp.PageSize < 1 || spqp.PageSize > 20000 {
  191. spqp.PageSize = 20000
  192. }
  193. }
  194. }
  195. starttime, endtime := int64(0), int64(0)
  196. logx.Info(4444)
  197. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  198. st := strings.Split(spqp.SelectTime, "_")[0]
  199. et := strings.Split(spqp.SelectTime, "_")[1]
  200. if st != "" && et != "" {
  201. starttime, _ = strconv.ParseInt(st, 0, 64)
  202. endtime, _ = strconv.ParseInt(et, 0, 64)
  203. if endtime > 0 {
  204. etTime := time.Unix(endtime, 0)
  205. endtime = time.Date(etTime.Year(), etTime.Month(), etTime.Day(), 23, 59, 59, 0, time.Local).Unix()
  206. }
  207. }
  208. }
  209. logx.Info(2222)
  210. nowFormat := date.NowFormat(date.Date_Short_Layout)
  211. start := (spqp.PageNum - 1) * spqp.PageSize
  212. end := start + spqp.PageSize
  213. //时间是今天,没有别的过滤条件--首先读取当前推送缓存数据 其次查询数据库
  214. if nowFormat == date.FormatDateByInt64(&starttime, date.Date_Short_Layout) && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == "" {
  215. logx.Info("a1:", s.todayKey(spqp.UserId))
  216. subPush, err := s.GetTodayCache(spqp.UserId)
  217. if err != nil {
  218. logx.Info(spqp.UserId, "GetTodayCache Error", err)
  219. }
  220. if err != nil || subPush == nil || subPush.Date != nowFormat || len(subPush.Datas) == 0 {
  221. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, false)
  222. subPush = &SubPush{
  223. Date: nowFormat,
  224. Datas: list,
  225. Count: countSearch,
  226. }
  227. s.PutTodayCache(spqp.UserId, subPush)
  228. }
  229. length := len(subPush.Datas)
  230. if end > length {
  231. end = length
  232. }
  233. if start < length {
  234. result = subPush.Datas[start:end]
  235. }
  236. total = int64(length)
  237. } else if spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize <= 250 { //全部,没有过滤条件 之前缓存5页*50条=250
  238. logx.Info("a2:", s.allKey(spqp.UserId))
  239. allCache, err := s.GetAllCache(spqp.UserId)
  240. if err != nil {
  241. logx.Info(spqp.UserId, "GetAllCache Error", err)
  242. }
  243. if err != nil || allCache == nil || allCache.Date != nowFormat || len(allCache.Datas) == 0 {
  244. spqp.PageNum = 1
  245. logx.Info(1111)
  246. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, AllSubPushCacheSize, true)
  247. allCache = &SubPush{
  248. Date: nowFormat,
  249. Datas: list,
  250. Count: countSearch,
  251. }
  252. s.PutAllCache(spqp.UserId, allCache)
  253. }
  254. length := len(allCache.Datas)
  255. if end > length {
  256. end = length
  257. }
  258. if start < length {
  259. result = allCache.Datas[start:end]
  260. }
  261. total = allCache.Count
  262. } else {
  263. logx.Info("a4")
  264. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true)
  265. }
  266. logx.Info("-------------------------------------------------", len(result))
  267. if result == nil {
  268. result = []*bxsubscribe.SubscribeInfo{}
  269. }
  270. hasNextPage = len(result) >= spqp.PageSize
  271. return
  272. }
  273. //
  274. func (s *subscribePush) getDatasFromMysql(spqp *SubPushQueryParam, starttime, endtime int64, size int, isLimit bool) (result []*bxsubscribe.SubscribeInfo, count int64) {
  275. querys := []string{fmt.Sprintf("userid='%s'", common.If(s.ModuleFlag == "eType", spqp.EntUserId, spqp.UserId))}
  276. //时间
  277. if starttime > 0 && endtime > 0 {
  278. querys = append(querys, fmt.Sprintf("date>=%d and date<=%d", starttime, endtime))
  279. } else if starttime > 0 && endtime == 0 {
  280. querys = append(querys, fmt.Sprintf("date>=%d", starttime))
  281. } else if starttime == 0 && endtime > 0 {
  282. querys = append(querys, fmt.Sprintf("date<=%d", endtime))
  283. }
  284. if spqp.Area != "" || spqp.City != "" {
  285. var sqlAreaCity = ""
  286. //城市
  287. city := []string{}
  288. for _, v := range strings.Split(spqp.City, ",") {
  289. if IC.PushMapping.City[v] > 0 {
  290. city = append(city, fmt.Sprint(IC.PushMapping.City[v]))
  291. } else {
  292. city = append(city, "-1")
  293. }
  294. }
  295. if len(city) == 1 {
  296. city = append(city, "9999")
  297. }
  298. if len(city) > 0 {
  299. sqlAreaCity = fmt.Sprintf("city in (%s)", strings.Join(city, ","))
  300. }
  301. //区域
  302. var sqlArea = ""
  303. area := []string{}
  304. for _, v := range strings.Split(spqp.Area, ",") {
  305. if IC.PushMapping.Area[v] > 0 {
  306. area = append(area, fmt.Sprint(IC.PushMapping.Area[v]))
  307. } else {
  308. area = append(area, "-1")
  309. }
  310. }
  311. if len(area) == 1 {
  312. area = append(area, "9999")
  313. }
  314. if len(area) > 0 {
  315. sqlArea = fmt.Sprintf("area in (%s)", strings.Join(area, ","))
  316. }
  317. if sqlAreaCity != "" && sqlArea != "" {
  318. sqlAreaCity = "( " + sqlAreaCity + " or " + sqlArea + " )"
  319. } else if sqlAreaCity == "" && sqlArea != "" {
  320. sqlAreaCity = sqlArea
  321. }
  322. if sqlAreaCity != "" {
  323. querys = append(querys, sqlAreaCity)
  324. }
  325. }
  326. //采购单位行业
  327. if spqp.Buyerclass != "" {
  328. buyerclass := []string{}
  329. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  330. buyerclass = append(buyerclass, fmt.Sprint(IC.PushMapping.Buyerclass[v]))
  331. }
  332. if len(buyerclass) == 1 {
  333. buyerclass = append(buyerclass, "9999")
  334. }
  335. if len(buyerclass) > 0 {
  336. querys = append(querys, fmt.Sprintf("buyerclass in (%s)", strings.Join(buyerclass, ",")))
  337. }
  338. }
  339. //信息类型
  340. if spqp.Subtype != "" {
  341. subtype := []string{}
  342. for _, v := range strings.Split(spqp.Subtype, ",") {
  343. subtype = append(subtype, fmt.Sprint(IC.PushMapping.Subtype[v]))
  344. }
  345. if len(subtype) == 1 {
  346. subtype = append(subtype, "9999")
  347. }
  348. if len(subtype) > 0 {
  349. querys = append(querys, fmt.Sprintf("subtype in (%s)", strings.Join(subtype, ",")))
  350. }
  351. }
  352. //信息行业
  353. if spqp.Subscopeclass != "" {
  354. find_in_set := []string{}
  355. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  356. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%d',subscopeclass)", IC.PushMapping.Subscopeclass[v]))
  357. }
  358. if len(find_in_set) == 1 {
  359. querys = append(querys, find_in_set[0])
  360. } else if len(find_in_set) > 1 {
  361. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  362. }
  363. }
  364. //关键词
  365. if spqp.Key != "" {
  366. find_in_set := []string{}
  367. for _, v := range strings.Split(spqp.Key, ",") {
  368. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(replace(matchkeys,'+',','),' ',','))", v))
  369. }
  370. if len(find_in_set) == 1 {
  371. querys = append(querys, find_in_set[0])
  372. } else if len(find_in_set) > 1 {
  373. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  374. }
  375. }
  376. //价格- 预算和中标金额
  377. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  378. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  379. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  380. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  381. if minPriceStr != "" && maxPriceStr != "" {
  382. querys = append(querys, fmt.Sprintf("((bidamount>=%d and bidamount<=%d) or (budget>=%d and budget<=%d and bidamount is null))", minPrice, maxPrice, minPrice, maxPrice))
  383. } else if minPriceStr != "" {
  384. querys = append(querys, fmt.Sprintf("(bidamount>=%d or (budget>=%d and bidamount is null))", minPrice, minPrice))
  385. } else if maxPriceStr != "" {
  386. querys = append(querys, fmt.Sprintf("( bidamount<=%d or (budget<=%d and bidamount is null))", maxPrice, maxPrice))
  387. }
  388. }
  389. //附件
  390. if spqp.FileExists != "" {
  391. if spqp.FileExists == "1" {
  392. querys = append(querys, fmt.Sprintf("attachment_count is not null"))
  393. } else if spqp.FileExists == "-1" {
  394. querys = append(querys, fmt.Sprintf("attachment_count is null"))
  395. }
  396. }
  397. searchSql := fmt.Sprintf(" from %s where %s order by id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, strings.Join(querys, " and "))
  398. fmt.Println("searchSql", searchSql)
  399. //查询总数
  400. count = spqp.PushMysql.CountBySql(fmt.Sprintf("select count(id)" + searchSql))
  401. logx.Info("count:", count, "---", s.ModuleFlag)
  402. findSql := "select id,date,infoid,isvisit,matchkeys,type"
  403. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  404. findSql += ",isvip"
  405. }
  406. findSql += searchSql
  407. if isLimit {
  408. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  409. }
  410. logx.Info(spqp.UserId, "subscribePush query sql:", findSql)
  411. list := spqp.PushMysql.SelectBySql(findSql)
  412. if list != nil && len(*list) > 0 {
  413. pushCas := s.GetJyPushs(*list)
  414. result = s.GetInfoByIds(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, pushCas)
  415. } else {
  416. result = []*bxsubscribe.SubscribeInfo{}
  417. }
  418. return
  419. }
  420. //根据id取内容
  421. func (s *subscribePush) GetInfoByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  422. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  423. if len(pushCas) == 0 {
  424. return array
  425. }
  426. m := map[string]bool{}
  427. ids := []string{}
  428. for _, v := range pushCas {
  429. if m[v.InfoId] {
  430. continue
  431. }
  432. m[v.InfoId] = true
  433. ids = append(ids, v.InfoId)
  434. }
  435. infos := map[string]map[string]interface{}{}
  436. //redis
  437. es_ids := []string{}
  438. for _, v := range ids {
  439. //剑鱼程序未找到赋值 位置;猜测在推送程序中
  440. info_i := redis.Get("pushcache_1", fmt.Sprintf("info_%s", v))
  441. if info_i != nil {
  442. info_m, _ := info_i.(map[string]interface{})
  443. info_m["_id"] = v
  444. infos[v] = info_m
  445. } else {
  446. es_ids = append(es_ids, v)
  447. }
  448. }
  449. //elasticsearch
  450. if len(es_ids) > 0 {
  451. list := elastic.Get("bidding", "bidding", fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  452. if list != nil {
  453. for _, v := range *list {
  454. _id := common.ObjToString(v["_id"])
  455. infos[_id] = v
  456. }
  457. }
  458. }
  459. //mongodb bidding
  460. mgo_ids := []primitive.ObjectID{}
  461. for _, v := range es_ids {
  462. if infos[v] == nil {
  463. _id, _ := primitive.ObjectIDFromHex(v)
  464. mgo_ids = append(mgo_ids, _id)
  465. }
  466. }
  467. if len(mgo_ids) > 0 {
  468. list, ok := Mgo_bidding.Find(bidding, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  469. if ok && *list != nil {
  470. for _, v := range *list {
  471. _id := mongodb.BsonIdToSId(v["_id"])
  472. v["_id"] = _id
  473. infos[_id] = v
  474. }
  475. }
  476. }
  477. //mongodb bidding_back
  478. mgo_back_ids := []primitive.ObjectID{}
  479. for _, v := range mgo_ids {
  480. if infos[mongodb.BsonIdToSId(v)] == nil {
  481. mgo_back_ids = append(mgo_back_ids, v)
  482. }
  483. }
  484. if len(mgo_back_ids) > 0 {
  485. list, ok := Mgo_bidding.Find(bidding_back, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  486. if ok && *list != nil {
  487. for _, v := range *list {
  488. _id := mongodb.BsonIdToSId(v["_id"])
  489. v["_id"] = _id
  490. infos[_id] = v
  491. }
  492. }
  493. }
  494. //
  495. for k, v := range pushCas {
  496. info := infos[v.InfoId]
  497. if info == nil {
  498. info = map[string]interface{}{}
  499. }
  500. array[k] = s.InfoFormat(v, &info)
  501. }
  502. return array
  503. }
  504. //获取历史推送
  505. func (s *subscribePush) GetJyPushs(datas []map[string]interface{}) (pushCas []*PushCa) {
  506. pushCas = []*PushCa{}
  507. for _, v := range datas {
  508. keys := []string{}
  509. if matchkeys := common.ObjToString(v["matchkeys"]); matchkeys != "" {
  510. keys = strings.Split(matchkeys, " ")
  511. }
  512. pushCas = append(pushCas, &PushCa{
  513. Date: common.Int64All(v["date"]),
  514. InfoId: common.ObjToString(v["infoid"]),
  515. Visit: common.IntAll(v["isvisit"]),
  516. Index: common.Int64All(v["id"]),
  517. Keys: keys,
  518. Type: common.IntAll(v["type"]),
  519. Isvip: common.IntAll(v["isvip"]),
  520. FileExists: common.IntAll(v["attachment_count"]) > 0,
  521. })
  522. }
  523. return
  524. }
  525. //查看全部列表缓存
  526. func (s *subscribePush) PutAllCache(userId string, datas *SubPush) {
  527. redis.Put("pushcache_2_a", s.allKey(userId), datas, oneDay)
  528. }
  529. func (s *subscribePush) GetAllCache(userId string) (*SubPush, error) {
  530. return s.GetCache("pushcache_2_a", s.allKey(userId))
  531. }
  532. func (s *subscribePush) GetCache(code, key string) (*SubPush, error) {
  533. pc_a, err := redis.GetNewBytes(code, key)
  534. if err != nil {
  535. return nil, err
  536. }
  537. if pc_a == nil {
  538. return nil, nil
  539. }
  540. var p *SubPush
  541. if err := json.Unmarshal(*pc_a, &p); err != nil {
  542. return nil, err
  543. }
  544. return p, nil
  545. }
  546. //是否收藏
  547. func (s *subscribePush) MakeCollection(userId string, list []*bxsubscribe.SubscribeInfo) {
  548. if list == nil || len(list) == 0 {
  549. return
  550. }
  551. param := []interface{}{userId}
  552. wh := []string{}
  553. for _, v := range list {
  554. array := encrypt.DecodeArticleId2ByCheck(v.XId)
  555. if len(array) == 1 && array[0] != "" {
  556. param = append(param, array[0])
  557. wh = append(wh, "?")
  558. }
  559. }
  560. if len(wh) > 0 {
  561. result := IC.MainMysql.SelectBySql(`select bid from bdcollection where userid=? and bid in (`+strings.Join(wh, ",")+`)`, param...)
  562. bid_map := map[string]bool{}
  563. if result != nil {
  564. for _, v := range *result {
  565. bid_map[encrypt.EncodeArticleId2ByCheck(common.ObjToString(v["bid"]))] = true
  566. }
  567. }
  568. for _, v := range list {
  569. if bid_map[v.XId] {
  570. v.Collection = 1
  571. }
  572. }
  573. }
  574. }
  575. //仅移动端首页使用,历史推送7天信息
  576. func (s *subscribePush) sevenDayKey(userId string) string {
  577. return fmt.Sprintf("7day_subpush_%s", userId)
  578. }
  579. func (s *subscribePush) PutSevenDayCache(userId string, datas []*bxsubscribe.SubscribeInfo) {
  580. redis.Put("pushcache_2_a", s.sevenDayKey(userId), SubPush{Datas: datas}, 7*24*60*60)
  581. }
  582. //从pushcache_2_a中取
  583. func (s *subscribePush) GetSevenDayCache(userId string) ([]*bxsubscribe.SubscribeInfo, error) {
  584. allPush, _ := s.GetCache("pushcache_2_a", s.sevenDayKey(userId))
  585. if allPush != nil && allPush.Datas != nil && len(allPush.Datas) > 0 {
  586. return allPush.Datas, nil
  587. }
  588. return nil, nil
  589. }
  590. //历史推送记录中单条信息格式化
  591. func InfoFormats(info map[string]interface{}, tmp map[string]interface{}) map[string]interface{} {
  592. area := common.ObjToString(info["area"])
  593. if area == "A" {
  594. area = "全国"
  595. }
  596. industry := common.ObjToString(info["s_subscopeclass"])
  597. scs := strings.Split(industry, ",")
  598. if len(scs) > 0 {
  599. industry = scs[0]
  600. if industry != "" {
  601. iss := strings.Split(industry, "_")
  602. if len(iss) > 0 {
  603. industry = iss[0]
  604. }
  605. }
  606. }
  607. infotype := common.ObjToString(info["subtype"])
  608. if infotype == "" {
  609. infotype = common.ObjToString(info["toptype"])
  610. }
  611. if infotype == "" {
  612. infotype = common.ObjToString(info["type"])
  613. if infotype == "tender" {
  614. infotype = "招标"
  615. } else if infotype == "bid" {
  616. infotype = "中标"
  617. }
  618. }
  619. info["type"] = infotype
  620. return info
  621. }
  622. //UpdateUserPushUnread 更新app未读标识为已读
  623. func UpdateUserPushUnread(userid string, vt string) {
  624. if vt == MemberFlag {
  625. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
  626. } else if vt == EntnicheFlag {
  627. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
  628. } else {
  629. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
  630. }
  631. }
  632. //
  633. //获取用户信息
  634. func (s *subscribePush) UserInfo(userId string) (*map[string]interface{}, int64) {
  635. user, ok := IC.Mgo.FindById("user", userId, `{"s_m_openid":1,"a_m_openid":1,"s_phone":1,"a_mergeorder":1,"o_jy":1,"l_firstpushtime":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"i_member_status":1,"o_member_jy":1}`)
  636. if !ok || user == nil {
  637. return nil, 0
  638. }
  639. return user, common.Int64All((*user)["l_firstpushtime"])
  640. }
  641. //是否有订阅词
  642. func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
  643. var industry_ = []string{}
  644. if u != nil {
  645. if t == SubFreeFlag {
  646. o_jy, _ := (*u)["o_jy"].(map[string]interface{})
  647. a_key, _ := o_jy["a_key"].([]interface{})
  648. return len(a_key) > 0, industry_
  649. } else {
  650. var obj map[string]interface{}
  651. if t == SubVipFlag {
  652. obj, _ = (*u)["o_vipjy"].(map[string]interface{})
  653. } else if t == MemberFlag {
  654. obj, _ = (*u)["o_member_jy"].(map[string]interface{})
  655. } else if t == EntnicheFlag {
  656. if len(data) > 0 {
  657. return true, data
  658. } else {
  659. return false, data
  660. }
  661. }
  662. if obj != nil {
  663. if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
  664. industry_ = common.ObjArrToStringArr(buyerclassObj)
  665. }
  666. itmes, _ := obj["a_items"].([]interface{})
  667. for _, v := range itmes {
  668. item, _ := v.(map[string]interface{})
  669. keys, _ := item["a_key"].([]interface{})
  670. if len(keys) > 0 {
  671. return true, industry_
  672. }
  673. }
  674. }
  675. }
  676. }
  677. return false, industry_
  678. }
  679. const (
  680. INDEX = "bidding"
  681. TYPE = "bidding"
  682. bidField = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","filetext","spidercode","site"`
  683. bidTime = `{"range":{"publishtime":{"gt":%d}}}`
  684. bidSort = `{"publishtime":"desc"}`
  685. findfields = `"title"`
  686. )
  687. //首次访问推送页面 默认生成推送数据
  688. //默认匹配es 7天内数据
  689. func (s *subscribePush) DefaultDatas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  690. if spqp.UserId == "" {
  691. return false, 0, nil
  692. }
  693. t1 := time.Now()
  694. log.Println("userId:", spqp.UserId)
  695. //用户信息
  696. bsp := s.getUserInfo(spqp)
  697. logx.Info("获取用户信息耗时:", time.Since(t1))
  698. t2 := time.Now()
  699. if len(bsp.Keyword) > 0 {
  700. logx.Info(time.Since(t1), "--bsp:", bsp)
  701. //获取查询语句
  702. qstr := s.getDefaultDatasSQL(bsp)
  703. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, bsp.Size, 0, false)
  704. logx.Info(time.Since(t1), "count:", len(*list))
  705. if list != nil && len(*list) > 0 {
  706. total = int64(len(*list))
  707. //超过50条先处理50条 返回前50条
  708. listOne := *list
  709. if len(*list) > pageSize {
  710. listOne = (*list)[:pageSize]
  711. }
  712. result = s.listManager(spqp, listOne, bsp.Keyword, (len(listOne)+pageSize)/pageSize)
  713. if len(*list) > pageSize {
  714. hasNextPage = true
  715. listOther := (*list)[pageSize:]
  716. go s.listManager(spqp, listOther, bsp.Keyword, (len(listOther)+pageSize)/pageSize)
  717. }
  718. }
  719. }
  720. logx.Info("请求耗时:", time.Since(t2))
  721. return
  722. }
  723. //
  724. func (s *subscribePush) listManager(spqp *SubPushQueryParam, list []map[string]interface{}, keyword []ViewKeyWord, ccount int) (resultList []*bxsubscribe.SubscribeInfo) {
  725. t2 := time.Now()
  726. now := time.Now()
  727. var (
  728. wg = &sync.WaitGroup{}
  729. wc = make(chan bool, ccount)
  730. )
  731. for _, v := range list {
  732. wg.Add(1)
  733. wc <- true
  734. go func(v map[string]interface{}) {
  735. defer func() {
  736. wg.Done()
  737. <-wc
  738. }()
  739. redisKey := fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"]))
  740. title := strings.Replace(common.ObjToString(v["title"]), "\n", "", -1)
  741. var myInsert = make(map[string]interface{})
  742. myInsert["userid"] = spqp.UserId
  743. myInsert["infoid"] = common.ObjToString(v["_id"])
  744. myInsert["date"] = now.Unix()
  745. matchkeys := getKeys(title, keyword)
  746. myInsert["matchkeys"] = strings.Join(matchkeys, " ")
  747. if v["area"] != nil {
  748. myInsert["area"] = common.If(common.ObjToString(v["area"]) == "A", 0, common.If(IC.PushMapping.Area[common.ObjToString(v["area"])] > 0, IC.PushMapping.Area[common.ObjToString(v["area"])], 0).(int)).(int)
  749. }
  750. if v["city"] != nil {
  751. myInsert["city"] = common.If(IC.PushMapping.City[common.ObjToString(v["city"])] > 0, IC.PushMapping.City[common.ObjToString(v["city"])], 0).(int)
  752. }
  753. if v["subtype"] != nil {
  754. myInsert["subtype"] = common.If(IC.PushMapping.Subtype[common.ObjToString(v["subtype"])] > 0, IC.PushMapping.Subtype[common.ObjToString(v["subtype"])], 0).(int)
  755. }
  756. if v["toptype"] != nil {
  757. myInsert["toptype"] = common.If(IC.PushMapping.Toptype[common.ObjToString(v["toptype"])] > 0, IC.PushMapping.Toptype[common.ObjToString(v["toptype"])], 0).(int)
  758. }
  759. if v["buyerclass"] != nil {
  760. myInsert["buyerclass"] = common.If(IC.PushMapping.Buyerclass[common.ObjToString(v["buyerclass"])] > 0, IC.PushMapping.Buyerclass[common.ObjToString(v["buyerclass"])], 0).(int)
  761. }
  762. if v["isValidFile"] != nil {
  763. isValidFile, _ := v["isValidFile"].(bool)
  764. myInsert["attachment_count"] = common.If(isValidFile, 1, 0).(int) //附件 :检索库 只有附件字段,无法识别附件数量 暂定为1;为识别有附件
  765. }
  766. if v["bidamount"] != nil {
  767. myInsert["bidamount"] = common.Int64All(v["bidamount"])
  768. }
  769. if v["budget"] != nil {
  770. myInsert["budget"] = common.Int64All(v["budget"])
  771. }
  772. if s_subscopeclass := common.ObjToString(v["s_subscopeclass"]); s_subscopeclass != "" {
  773. subscopeclass := []string{}
  774. for _, v := range strings.Split(s_subscopeclass, ",") {
  775. if subscopeclass_mapping, ok := IC.PushMapping.Subscopeclass[v]; ok {
  776. subscopeclass = append(subscopeclass, fmt.Sprint(subscopeclass_mapping))
  777. }
  778. }
  779. if len(subscopeclass) > 0 {
  780. myInsert["subscopeclass"] = strings.Join(subscopeclass, ",")
  781. }
  782. }
  783. //商机管理用户
  784. if s.ModuleFlag == "s" {
  785. myInsert["userid"] = spqp.EntUserId
  786. myInsert["entid"] = spqp.EntId
  787. myInsert["deptid"] = spqp.DeptId
  788. }
  789. //保存推送表
  790. id := spqp.PushMysql.Insert(aboutDbMsg[s.ModuleFlag].MysqlTable, myInsert)
  791. if id > 0 {
  792. redis.Put("pushcache_2_a", redisKey, 1, 86400)
  793. resultList = append(resultList, s.InfoFormat(&PushCa{
  794. InfoId: common.ObjToString(v["_id"]),
  795. Date: now.Unix(),
  796. Index: id,
  797. Keys: matchkeys,
  798. FileExists: v["filetext"] != nil,
  799. }, &v))
  800. }
  801. }(v)
  802. }
  803. wg.Wait()
  804. log.Println("数据处理耗时:", time.Since(t2))
  805. return
  806. }
  807. //获取匹配得关键词
  808. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  809. if len(keywords) > 0 {
  810. L:
  811. for _, v := range keywords {
  812. for _, vk := range v.Keyword {
  813. if strings.Contains(title, vk) {
  814. str = append(str, v.Keyword...)
  815. break L
  816. }
  817. }
  818. for _, va := range v.Appended {
  819. if strings.Contains(title, va) {
  820. str = append(str, v.Appended...)
  821. break L
  822. }
  823. }
  824. }
  825. }
  826. return
  827. }
  828. //获取查询语句
  829. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  830. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  831. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  832. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  833. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  834. bools := []string{}
  835. musts := []string{}
  836. //发布时间最新7天
  837. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
  838. //省份
  839. areaCity := []string{}
  840. if len(bsp.Area) > 0 {
  841. areaquery := `{"terms":{"area":[`
  842. for k, v := range bsp.Area {
  843. if k > 0 {
  844. areaquery += `,`
  845. }
  846. areaquery += `"` + v + `"`
  847. }
  848. areaquery += `]}}`
  849. areaCity = append(areaCity, areaquery)
  850. }
  851. //城市
  852. if len(bsp.City) > 0 {
  853. areaquery := `{"terms":{"city":[`
  854. for k, v := range bsp.City {
  855. if k > 0 {
  856. areaquery += `,`
  857. }
  858. areaquery += `"` + v + `"`
  859. }
  860. areaquery += `]}}`
  861. areaCity = append(areaCity, areaquery)
  862. }
  863. if len(areaCity) > 0 {
  864. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  865. }
  866. if len(bsp.Subtype) > 0 {
  867. subquery := `{"terms":{"subtype":[`
  868. for k, v := range bsp.Subtype {
  869. if k > 0 {
  870. subquery += `,`
  871. }
  872. subquery += `"` + v + `"`
  873. }
  874. subquery += `]}}`
  875. musts = append(musts, subquery)
  876. }
  877. if len(bsp.Buyerclass) > 0 {
  878. Buyerclass := `{"terms":{"buyerclass":[`
  879. for k, v := range bsp.Buyerclass {
  880. if k > 0 {
  881. Buyerclass += `,`
  882. }
  883. Buyerclass += `"` + v + `"`
  884. }
  885. Buyerclass += `]}}`
  886. musts = append(musts, Buyerclass)
  887. }
  888. boolsNum := 0 //should
  889. if len(bsp.Keyword) > 0 {
  890. boolsNum = 1
  891. if bsp.SelectType == "" || bsp.SelectType == "2" {
  892. bsp.SelectType = "detail\", \"title"
  893. } else {
  894. bsp.SelectType = "title"
  895. }
  896. multi_match = fmt.Sprintf(multi_match, "%s", "\""+bsp.SelectType+"\"")
  897. for _, v := range bsp.Keyword {
  898. shoulds := []string{}
  899. must_not := []string{}
  900. //附加词
  901. for _, vv := range v.Keyword {
  902. vv = strings.TrimSpace(vv)
  903. if vv == "" {
  904. continue
  905. }
  906. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  907. }
  908. for _, vv := range v.Appended {
  909. vv = strings.TrimSpace(vv)
  910. if vv == "" {
  911. continue
  912. }
  913. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  914. }
  915. //排除词
  916. for _, vv := range v.Exclude {
  917. vv = strings.TrimSpace(vv)
  918. if vv == "" {
  919. continue
  920. }
  921. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  922. }
  923. //添加
  924. if len(shoulds) > 0 {
  925. notStr := ""
  926. if len(must_not) > 0 {
  927. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  928. }
  929. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  930. }
  931. }
  932. }
  933. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  934. logx.Info("----", qstr)
  935. return qstr
  936. }
  937. /*已选条件--关键词*/
  938. type ViewKeyWord struct {
  939. Keyword []string `json:"key"` //关键词
  940. Appended []string `json:"appendkey"` //附加词
  941. Exclude []string `json:"notkey"` //排除词
  942. MatchWay int `json:"matchway"` //匹配模式
  943. }
  944. /*已选条件*/
  945. type ViewCondition struct {
  946. Area []string //地区-省份
  947. City []string //地区-城市
  948. Buyerclass []string //采购行业
  949. Keyword []ViewKeyWord //关键词
  950. SelectType string //筛选(正文 or 标题)
  951. Subtype []string //信息类型
  952. Size int //数量
  953. }
  954. //获取用户信息
  955. func (s *subscribePush) getUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  956. var isPayBool = false
  957. var tmpInfo = struct {
  958. Items []interface{}
  959. BuyerClass []interface{}
  960. SubType []interface{}
  961. Area map[string]interface{}
  962. SelectType string
  963. }{}
  964. switch s.ModuleFlag {
  965. case "mType":
  966. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1}`)
  967. if !ok || userMap == nil || len(*userMap) == 0 {
  968. return &ViewCondition{}
  969. }
  970. //大会员
  971. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  972. isPayBool = true
  973. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  974. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  975. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  976. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  977. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  978. }
  979. case "vType":
  980. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
  981. if !ok || userMap == nil || len(*userMap) == 0 {
  982. return &ViewCondition{}
  983. }
  984. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  985. isPayBool = true
  986. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  987. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  988. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  989. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  990. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  991. }
  992. case "eType":
  993. //商机管理
  994. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  995. entId, _ := strconv.Atoi(spqp.EntId)
  996. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  997. if entInfo != nil && len(entInfo) > 0 {
  998. spqp.DeptId = strconv.Itoa(deptId)
  999. isPayBool = true
  1000. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1001. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1002. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1003. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1004. }
  1005. default:
  1006. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1}`)
  1007. if !ok || userMap == nil || len(*userMap) == 0 {
  1008. return &ViewCondition{}
  1009. }
  1010. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1011. if o_jy["a_key"] != nil {
  1012. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1013. //信息类型
  1014. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1015. //省份
  1016. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1017. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1018. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1019. }
  1020. }
  1021. }
  1022. vc = &ViewCondition{
  1023. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1024. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1025. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1026. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1027. SelectType: "1",
  1028. }
  1029. //付费用户
  1030. if isPayBool {
  1031. vc.Size = IC.C.DefaulCount.Pay
  1032. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1033. } else {
  1034. vc.Size = IC.C.DefaulCount.Free
  1035. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1036. }
  1037. return
  1038. }
  1039. //关键词 附加词 排除词
  1040. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1041. if a_items == nil {
  1042. return
  1043. }
  1044. for _, v := range a_items {
  1045. vm, _ := v.(map[string]interface{})
  1046. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1047. continue
  1048. }
  1049. kwsArr := vm["a_key"]
  1050. for i, k := range kwsArr.([]interface{}) {
  1051. if item != "" && index >= 0 && i != index {
  1052. continue
  1053. }
  1054. kw := ViewKeyWord{}
  1055. b, e := json.Marshal(k)
  1056. if e != nil {
  1057. log.Println(e.Error())
  1058. }
  1059. json.Unmarshal(b, &kw)
  1060. if kw.MatchWay == 1 {
  1061. for _, kk := range kw.Keyword {
  1062. arr = append(arr, ViewKeyWord{
  1063. Keyword: []string{kk},
  1064. Exclude: kw.Exclude,
  1065. })
  1066. }
  1067. for _, kk := range kw.Appended {
  1068. arr = append(arr, ViewKeyWord{
  1069. Keyword: []string{kk},
  1070. Exclude: kw.Exclude,
  1071. })
  1072. }
  1073. } else {
  1074. arr = append(arr, kw)
  1075. }
  1076. }
  1077. }
  1078. return
  1079. }
  1080. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1081. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1082. if a_items == nil {
  1083. return
  1084. }
  1085. for _, v := range a_items {
  1086. vmr, _ := v.([]interface{})
  1087. vm, _ := vmr[0].(map[string]interface{})
  1088. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1089. continue
  1090. }
  1091. kwsArr := vmr
  1092. for i, k := range kwsArr {
  1093. if item != "" && index >= 0 && i != index {
  1094. continue
  1095. }
  1096. kw := ViewKeyWord{}
  1097. b, e := json.Marshal(k)
  1098. if e != nil {
  1099. log.Println(e.Error())
  1100. }
  1101. json.Unmarshal(b, &kw)
  1102. if kw.MatchWay == 1 {
  1103. for _, kk := range kw.Keyword {
  1104. arr = append(arr, ViewKeyWord{
  1105. Keyword: []string{kk},
  1106. Exclude: kw.Exclude,
  1107. })
  1108. }
  1109. for _, kk := range kw.Appended {
  1110. arr = append(arr, ViewKeyWord{
  1111. Keyword: []string{kk},
  1112. Exclude: kw.Exclude,
  1113. })
  1114. }
  1115. } else {
  1116. arr = append(arr, kw)
  1117. }
  1118. }
  1119. }
  1120. return
  1121. }
  1122. //地区格式化
  1123. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1124. if area == nil {
  1125. return
  1126. }
  1127. var eareArr []string
  1128. var cityArr []string
  1129. for k, v := range area {
  1130. if len(v.([]interface{})) > 0 {
  1131. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1132. } else {
  1133. eareArr = append(eareArr, k)
  1134. }
  1135. }
  1136. if i == 1 {
  1137. arr = eareArr
  1138. } else {
  1139. arr = cityArr
  1140. }
  1141. return
  1142. }