device.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package model
  4. import (
  5. "fmt"
  6. "github.com/jinzhu/gorm"
  7. "github.com/tidwall/gjson"
  8. "time"
  9. )
  10. const (
  11. DeviceTypeVedio = 9
  12. DeviceTypeDust = 5
  13. DeviceTypeTower = 1
  14. DeviceTypeHighFramework = 7
  15. DeviceTypeUnloading = 6
  16. DeviceTypeUpDown = 4
  17. DeviceTypeWireless = 8
  18. DeviceTypeVehicle = 2
  19. DeviceTypeStaff = 3
  20. )
  21. type TDevice struct {
  22. Id int64 `gorm:"column:id" json:"id" form:"id"`
  23. ProjectId int64 `gorm:"column:project_id" json:"project_id" form:"project_id"`
  24. ProviderId int64 `gorm:"column:provider_id" json:"provider_id" form:"provider_id"`
  25. Name string `gorm:"column:name" json:"name" form:"name"`
  26. Sn string `gorm:"column:sn" json:"sn" form:"sn"`
  27. Addr string `gorm:"column:addr" json:"addr" form:"addr"`
  28. DeviceCode int32 `gorm:"column:device_code" json:"device_code" form:"device_code"`
  29. Lon float64 `gorm:"column:lon" json:"lon" form:"lon"`
  30. Lat float64 `gorm:"column:lat" json:"lat" form:"lat"`
  31. XCoord float64 `gorm:"column:x_coord" json:"x_coord" form:"x_coord"`
  32. YCoord float64 `gorm:"column:y_coord" json:"y_coord" form:"y_coord"`
  33. Status int64 `gorm:"column:status" json:"status" form:"status"`
  34. CreatedAt time.Time `gorm:"column:created_at" json:"created_at" form:"created_at"`
  35. UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at" form:"updated_at"`
  36. VerifyStatus int64 `gorm:"column:verify_status" json:"verify_status" form:"verify_status"`
  37. Key string `gorm:"column:key" json:"key" form:"key"`
  38. ProjectApproveTime time.Time `json:"project_approve_time"`
  39. }
  40. func (TDevice) TableName() string {
  41. return "t_device"
  42. }
  43. func (p *TDevice) Insert(db *gorm.DB) error {
  44. return db.Create(p).Error
  45. }
  46. func (p *TDevice) Statistic(db *gorm.DB, projectId int64, deviceType int32, result interface{}) error {
  47. sql := fmt.Sprintf("select device_code as device_type, sum(status=0) as offline, sum(status=1) as online from t_device where project_id=%d group by type", projectId)
  48. if deviceType > 0 {
  49. sql = fmt.Sprintf("select device_code as device_type, sum(status=0) as offline, sum(status=1) as online from t_device where project_id=%d and type = %d group by type", projectId, deviceType)
  50. }
  51. err := db.Raw(sql).Scan(result).Error
  52. return err
  53. }
  54. func (p *TDevice) Del(db *gorm.DB, where map[string]interface{}) error {
  55. cond, val, err := whereBuild(where)
  56. if err != nil {
  57. return err
  58. }
  59. return db.Table(p.TableName()).Where(cond, val...).Delete(p).Error
  60. }
  61. func (p *TDevice) Find(db *gorm.DB, where map[string]interface{}) error {
  62. cond, val, err := whereBuild(where)
  63. if err != nil {
  64. return err
  65. }
  66. return db.Table(p.TableName()).Where(cond, val...).First(p).Error
  67. }
  68. func (p *TDevice) Update(db *gorm.DB, where map[string]interface{}, values map[string]interface{}) error {
  69. cond, val, err := whereBuild(where)
  70. if err != nil {
  71. return err
  72. }
  73. return db.Table(p.TableName()).Where(cond, val...).Updates(values).Error
  74. }
  75. func (p *TDevice) FindSort(db *gorm.DB, where map[string]interface{}, sort string) error {
  76. cond, val, err := whereBuild(where)
  77. if err != nil {
  78. return err
  79. }
  80. ps := []TDevice{}
  81. err = db.Table(p.TableName()).Where(cond, val...).Order(sort).Limit(1).Find(&ps).Error
  82. if err != nil {
  83. return err
  84. }
  85. if len(ps) > 0 {
  86. *p = ps[0]
  87. }
  88. return nil
  89. }
  90. func (p *TDevice) Save(db *gorm.DB) error {
  91. return db.Save(p).Error
  92. }
  93. func (p *TDevice) Count(db *gorm.DB, where map[string]interface{}) (int64, error) {
  94. if len(where) > 0 {
  95. cond, val, err := whereBuild(where)
  96. if err != nil {
  97. return 0, err
  98. }
  99. ret := int64(0)
  100. err = db.Table(p.TableName()).Where(cond, val...).Count(&ret).Error
  101. return ret, err
  102. }
  103. ret := int64(0)
  104. err := db.Table(p.TableName()).Count(&ret).Error
  105. return ret, err
  106. }
  107. func (p *TDevice) List(db *gorm.DB, where map[string]interface{}, page int) (list []TDevice, err error) {
  108. if len(where) > 0 {
  109. cond, val, err := whereBuild(where)
  110. if err != nil {
  111. return list, err
  112. }
  113. result := db.Table(p.TableName()).Where(cond, val...).Limit(PageSize).Offset(page).Find(&list)
  114. return list, result.Error
  115. }
  116. result := db.Table(p.TableName()).Limit(10).Offset(page).Find(&list)
  117. return list, result.Error
  118. }
  119. func (p *TDevice) All(db *gorm.DB) (list []TDevice, err error) {
  120. result := db.Table(p.TableName()).Find(&list)
  121. return list, result.Error
  122. }
  123. type DeviceItem struct {
  124. Id int64
  125. Sn string
  126. TypeCode int32
  127. TypeName string
  128. ProjectName string
  129. ProjectId int64
  130. SafetyRecordNo string
  131. CreatedTime time.Time
  132. Status int32
  133. State int32
  134. ProjectApproveTime time.Time
  135. Key string
  136. ProviderName string
  137. SocialCode string
  138. Name string
  139. Ip string
  140. Port int
  141. MediaTransport string
  142. ChannelCount int
  143. Lon float64
  144. Lat float64
  145. }
  146. const (
  147. DeviceTypeVideo = 9
  148. )
  149. func listRawSqlForVedio(req ListRawRequest)(string, string, []interface{}) {
  150. sql := fmt.Sprintf("select t1.id as id, t1.key, t1.name as name, t1.sn as sn, t1.device_code as type_code, t1.project_id as project_id, t1.project_approve_time, t4.MediaTransport as media_transport, t4.IP as ip, t4.Port as port, t4.channel_count, "+
  151. "t1.created_at as created_time, t4.Alive as state, t1.verify_status as status, t2.safety_record_no, t2.name as project_name, t3.name as provider_name, t3.social_code from t_device as t1 left join t_project as t2 on t1.project_id=t2.id left join t_provider as t3 on t1.provider_id=t3.id left join VSSDevTbl as t4 on t4.DevPubID=t1.sn")
  152. countSql := fmt.Sprintf("select count(1) as count from t_device as t1 left join t_project as t2 on t1.project_id=t2.id ")
  153. args := []interface{}{}
  154. whereArray := []string{}
  155. if req.ProviderId > 0 {
  156. whereArray = append(whereArray, fmt.Sprintf("t1.provider_id=%d", req.ProviderId))
  157. }
  158. whereArray = append(whereArray, fmt.Sprintf("t1.device_code = %d", DeviceTypeVideo))
  159. if req.Filter != "" {
  160. whereArray = append(whereArray, fmt.Sprintf("(t1.sn like '%%%s%%' or t2.safety_record_no like '%%%s%%' or t2.name like '%%%s%%')", req.Filter, req.Filter, req.Filter))
  161. }
  162. if req.ProjectId > 0 {
  163. whereArray = append(whereArray, fmt.Sprintf("t1.project_id = %d", req.ProjectId))
  164. }
  165. if req.CanDel {
  166. req.IsAll = true
  167. req.StatusFilter = []int32{1}
  168. whereArray = append(whereArray, fmt.Sprintf("(select count(1) from t_project_job where device_id=t1.id and type = 1 and (status = 0 or status = 1)) = 0"))
  169. }
  170. if len(req.StatusFilter) > 0 {
  171. args = append(args, req.StatusFilter)
  172. whereArray = append(whereArray, fmt.Sprintf("t1.verify_status in(?)"))
  173. }
  174. where := ""
  175. for _, v := range whereArray {
  176. if where == "" {
  177. where = fmt.Sprintf(" where %s", v)
  178. continue
  179. }
  180. where = fmt.Sprintf("%s and %s", where, v)
  181. }
  182. offset := (req.Page - 1) *int32(PageSize)
  183. if req.IsAll {
  184. sql = fmt.Sprintf("%s %s order by t1.created_at desc", sql, where)
  185. countSql = fmt.Sprintf("%s %s", countSql, where)
  186. } else {
  187. sql = fmt.Sprintf("%s %s order by t1.created_at desc limit %d offset %d", sql, where, PageSize, offset)
  188. countSql = fmt.Sprintf("%s %s", countSql, where)
  189. }
  190. return sql, countSql, args
  191. }
  192. func listRawSql(req ListRawRequest)(string, string, []interface{}) {
  193. if req.IsVedio {
  194. return listRawSqlForVedio(req)
  195. }
  196. sql := fmt.Sprintf("select t1.id as id, t1.key, t1.name, t1.sn as sn, t1.device_code as type_code, t1.project_id as project_id, t1.project_approve_time, "+
  197. "t1.created_at as created_time, t1.status as state, t1.verify_status as status, t2.safety_record_no, t2.name as project_name, t2.lon, t2.lat, t3.name as provider_name, t3.social_code from t_device as t1 left join t_project as t2 on t1.project_id=t2.id left join t_provider as t3 on t1.provider_id=t3.id")
  198. countSql := fmt.Sprintf("select count(1) as count from t_device as t1 left join t_project as t2 on t1.project_id=t2.id ")
  199. args := []interface{}{}
  200. whereArray := []string{}
  201. if req.ProviderId > 0 {
  202. whereArray = append(whereArray, fmt.Sprintf("t1.provider_id=%d", req.ProviderId))
  203. }
  204. if req.TypeCode > 0 {
  205. whereArray = append(whereArray, fmt.Sprintf("t1.device_code = %d", req.TypeCode))
  206. }
  207. if !req.CanDel {
  208. whereArray = append(whereArray, fmt.Sprintf("t1.device_code <> %d", DeviceTypeVideo))
  209. }
  210. if req.Filter != "" {
  211. whereArray = append(whereArray, fmt.Sprintf("(t1.sn like '%%%s%%' or t2.safety_record_no like '%%%s%%' or t2.name like '%%%s%%')", req.Filter, req.Filter, req.Filter))
  212. }
  213. if req.ProjectId > 0 {
  214. whereArray = append(whereArray, fmt.Sprintf("t1.project_id = %d", req.ProjectId))
  215. }
  216. if req.CanDel {
  217. req.IsAll = true
  218. req.StatusFilter = []int32{1}
  219. whereArray = append(whereArray, fmt.Sprintf("(select count(1) from t_project_job where device_id=t1.id and type = 1 and (status = 0 or status = 1)) = 0"))
  220. }
  221. if len(req.StatusFilter) > 0 {
  222. args = append(args, req.StatusFilter)
  223. whereArray = append(whereArray, fmt.Sprintf("t1.verify_status in(?)"))
  224. }
  225. where := ""
  226. for _, v := range whereArray {
  227. if where == "" {
  228. where = fmt.Sprintf(" where %s", v)
  229. continue
  230. }
  231. where = fmt.Sprintf("%s and %s", where, v)
  232. }
  233. offset := (req.Page - 1) *int32(PageSize)
  234. if req.IsAll {
  235. sql = fmt.Sprintf("%s %s order by t1.created_at desc", sql, where)
  236. countSql = fmt.Sprintf("%s %s", countSql, where)
  237. } else {
  238. sql = fmt.Sprintf("%s %s order by t1.created_at desc limit %d offset %d", sql, where, PageSize, offset)
  239. countSql = fmt.Sprintf("%s %s", countSql, where)
  240. }
  241. return sql, countSql, args
  242. }
  243. type ListRawRequest struct {
  244. ProviderId int64
  245. Filter string
  246. StatusFilter []int32
  247. IsAll bool
  248. CanDel bool
  249. Page int32
  250. TypeCode int32
  251. ProjectId int64
  252. IsVedio bool
  253. }
  254. func (p *TDevice) ListRaw(db *gorm.DB, req ListRawRequest) ([]DeviceItem, int64, error) {
  255. type ResultCount struct {
  256. Count int64
  257. }
  258. array := []ResultCount{}
  259. ret := []DeviceItem{}
  260. var err error
  261. sql, countSql, args := listRawSql(req)
  262. err = db.Raw(countSql, args...).Scan(&array).Error
  263. if err != nil {
  264. return nil, 0, err
  265. }
  266. if len(array) == 0 {
  267. return nil, 0, nil
  268. }
  269. if array[0].Count == 0 {
  270. return nil, 0, nil
  271. }
  272. err = db.Raw(sql, args...).Scan(&ret).Error
  273. if err != nil {
  274. return nil, array[0].Count, err
  275. }
  276. return ret, array[0].Count, nil
  277. }
  278. type DeviceDelJobItem struct {
  279. Id int64
  280. Sn string
  281. TypeCode int32
  282. TypeName string
  283. ProjectName string
  284. ProviderName string
  285. SocialCode string
  286. SafetyRecordNo string
  287. CreatedTime time.Time
  288. Status int32
  289. ApproveTime time.Time
  290. Origin string
  291. Reason string
  292. Feedback string
  293. Name string
  294. }
  295. func listDelJobSql(req ListRawRequest)(string, string, []interface{}) {
  296. sql := "select t1.origin, t1.reason, t1.feedback, t1.id, t1.status, t1.updated_at as approve_time, t1.created_at as created_time, t2.name as provider_name, t2.social_code, t3.safety_record_no, t3.name as project_name " +
  297. "from t_project_job as t1 left join t_provider as t2 on t1.provider_id=t2.id left join t_project as t3 on t3.id=t1.project_id "
  298. countSql := "select count(1) as count " +
  299. "from t_project_job as t1 left join t_provider as t2 on t1.provider_id=t2.id left join t_project as t3 on t3.id=t1.project_id "
  300. args := []interface{}{}
  301. whereArray := []string{"t1.type = 1"}
  302. if req.ProviderId > 0 {
  303. whereArray = append(whereArray, fmt.Sprintf("t1.provider_id=%d", req.ProviderId))
  304. }
  305. if req.Filter != "" {
  306. whereArray = append(whereArray, fmt.Sprintf("(t1.content like '%%%s%%' or t2.social_code like '%%%s%%' or t2.name like '%%%s%%')", req.Filter, req.Filter, req.Filter))
  307. }
  308. if len(req.StatusFilter) > 0 {
  309. args = append(args, req.StatusFilter)
  310. whereArray = append(whereArray, fmt.Sprintf("t1.status in(?)"))
  311. }
  312. if req.ProjectId > 0 {
  313. whereArray = append(whereArray, fmt.Sprintf("t1.project_id = %d", req.ProjectId))
  314. }
  315. where := ""
  316. for _, v := range whereArray {
  317. if where == "" {
  318. where = fmt.Sprintf(" where %s", v)
  319. continue
  320. }
  321. where = fmt.Sprintf("%s and %s", where, v)
  322. }
  323. offset := (req.Page - 1) *int32(PageSize)
  324. if req.IsAll {
  325. sql = fmt.Sprintf("%s %s order by t1.created_at desc", sql, where)
  326. countSql = fmt.Sprintf("%s %s", countSql, where)
  327. } else {
  328. sql = fmt.Sprintf("%s %s order by t1.created_at desc limit %d offset %d", sql, where, PageSize, offset)
  329. countSql = fmt.Sprintf("%s %s", countSql, where)
  330. }
  331. return sql, countSql, args
  332. }
  333. func (p *TDevice) ListDelJob(db *gorm.DB, req ListRawRequest) ([]DeviceDelJobItem, int64, error) {
  334. type ResultCount struct {
  335. Count int64
  336. }
  337. array := []ResultCount{}
  338. ret := []DeviceDelJobItem{}
  339. var err error
  340. sql, countSql, args := listDelJobSql(req)
  341. err = db.Raw(countSql, args...).Scan(&array).Error
  342. if err != nil {
  343. return nil, 0, err
  344. }
  345. if len(array) == 0 {
  346. return nil, 0, nil
  347. }
  348. if array[0].Count == 0 {
  349. return nil, 0, nil
  350. }
  351. err = db.Raw(sql, args...).Scan(&ret).Error
  352. if err != nil {
  353. return nil, array[0].Count, err
  354. }
  355. for i, v := range ret {
  356. ret[i].Sn = gjson.GetBytes([]byte(v.Origin), "sn").String()
  357. ret[i].TypeCode = int32(gjson.GetBytes([]byte(v.Origin), "device_code").Int())
  358. ret[i].Name = gjson.GetBytes([]byte(v.Origin), "name").String()
  359. }
  360. return ret, array[0].Count, nil
  361. }
  362. type DeviceStatisticData struct {
  363. Total int64
  364. Online int64
  365. Offline int64
  366. Increase int64
  367. }
  368. func GetIncreaseStart(month bool) string {
  369. now := time.Now()
  370. var ret time.Time
  371. if month {
  372. ret = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
  373. return ret.Format("2006-01-02 15:04:05")
  374. }
  375. switch {
  376. case int(now.Month()) < 4 :
  377. ret = time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
  378. case int(now.Month()) < 7 :
  379. ret = time.Date(now.Year(), 4, 1, 0, 0, 0, 0, now.Location())
  380. case int(now.Month()) < 10 :
  381. ret = time.Date(now.Year(), 7, 1, 0, 0, 0, 0, now.Location())
  382. default:
  383. ret = time.Date(now.Year(), 10, 1, 0, 0, 0, 0, now.Location())
  384. }
  385. return ret.Format("2006-01-02 15:04:05")
  386. }
  387. func DeviceStatistic(db *gorm.DB) (DeviceStatisticData, error) {
  388. type Result struct {
  389. Count int64
  390. Online int64
  391. Increase int64
  392. }
  393. //
  394. ret := DeviceStatisticData{}
  395. start := GetIncreaseStart(false)
  396. sql := fmt.Sprintf("select count(1) as count, sum(status=1) as online, sum(created_at >= '%s') as increase from t_device where verify_status=1 and device_code <> 9", start)
  397. array := []Result{}
  398. err := db.Raw(sql).Scan(&array).Error
  399. if err != nil {
  400. return ret, err
  401. }
  402. if len(array) > 0 {
  403. ret.Total = array[0].Count
  404. ret.Online = array[0].Online
  405. ret.Increase = array[0].Increase
  406. }
  407. //
  408. sql = fmt.Sprintf("select count(1) as count, sum(t1.Alive=1) as online, sum(t3.created_at >= '%s') as increase from VSSChannelTbl as t1 left join VSSDevTbl as t2 on t1.DevPubID=t2.DevPubID left join t_device as t3 on t3.sn=t1.DevPubID where t3.device_code=9 and t3.verify_status=1")
  409. array = []Result{}
  410. err = db.Raw(sql).Scan(&array).Error
  411. if err != nil {
  412. return ret, err
  413. }
  414. if len(array) > 0 {
  415. ret.Total += array[0].Count
  416. ret.Online += array[0].Online
  417. ret.Increase += array[0].Increase
  418. }
  419. ret.Offline = ret.Total - ret.Online
  420. return ret, nil
  421. }
  422. type DeviceStatisticsItem struct {
  423. TypeCode int32
  424. Total int64
  425. Online int64
  426. }
  427. func (p *TDevice) DeviceTypeStatistic(db *gorm.DB) ([]DeviceStatisticsItem, error) {
  428. sql := fmt.Sprintf("select device_code as type_code, sum(1) as total, sum(status=1) as online from t_device where verify_status=1 and device_code <> 9 group by device_code")
  429. array := []DeviceStatisticsItem{}
  430. err := db.Raw(sql).Scan(&array).Error
  431. if err != nil {
  432. return nil, err
  433. }
  434. vedioArray := []DeviceStatisticsItem{}
  435. sql = fmt.Sprintf("select t3.device_code as type_code, sum(1) as total, sum(t1.Alive=1) as online from VSSChannelTbl as t1 left join VSSDevTbl as t2 on t1.DevPubID=t2.DevPubID left join t_device as t3 on t3.sn=t1.DevPubID where t3.device_code=9 and t3.verify_status=1 group by t3.device_code")
  436. err = db.Raw(sql).Scan(&vedioArray).Error
  437. if err != nil {
  438. return nil, err
  439. }
  440. if len(vedioArray) > 0 {
  441. return append(array, vedioArray...), nil
  442. }
  443. return array, nil
  444. }