DeviceClassList.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package Device
  2. import (
  3. "ColdVerify_local/conf"
  4. "ColdVerify_local/lib"
  5. "ColdVerify_local/logs"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/astaxie/beego/cache"
  9. _ "github.com/astaxie/beego/cache/redis"
  10. "github.com/beego/beego/v2/adapter/orm"
  11. orm2 "github.com/beego/beego/v2/client/orm"
  12. _ "github.com/go-sql-driver/mysql"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. // 模板
  18. type DeviceClassList struct {
  19. Id int `orm:"column(ID);size(11);auto;pk"`
  20. T_class int `orm:"size(200);null"` // 分类
  21. T_id string `orm:"size(20);null"` // 设备id
  22. T_sn string `orm:"size(256);null"` // 设备序列号 KF开头,环境监测主机。 YD开头,温途监测主机
  23. T_terminal int `orm:"size(2);default(1)"` // 1-测点 2-终端
  24. T_failure_time string `orm:"size(256);null"` // 失效时间
  25. T_pdf string `orm:"size(256);null"` // pdf链接
  26. T_Certificate_sn string `orm:"size(256);null"` // 证书编号
  27. T_remark string `orm:"size(1024);null"` // 备注
  28. T_State int `orm:"size(2);default(1)"` // 0 删除 1 正常
  29. CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
  30. UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"` //auto_now 每次 model 保存时都会对时间自动更新
  31. }
  32. func (t *DeviceClassList) TableName() string {
  33. return "device_class_list" // 数据库名称 // ************** 替换 FormulaList **************
  34. }
  35. var redisCache_DeviceClassList cache.Cache
  36. func init() {
  37. //注册模型
  38. orm.RegisterModel(new(DeviceClassList))
  39. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  40. "redis_"+"DeviceClassList", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  41. logs.Println(config)
  42. var err error
  43. redisCache_DeviceClassList, err = cache.NewCache("redis", config)
  44. if err != nil || redisCache_DeviceClassList == nil {
  45. errMsg := "failed to init redis"
  46. logs.Println(errMsg, err)
  47. }
  48. }
  49. // ---------------- Redis -------------------
  50. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  51. func Redis_DeviceClassList_Set(key string, r DeviceClassList) (err error) {
  52. //json序列化
  53. str, err := json.Marshal(r)
  54. if err != nil {
  55. logs.Error(lib.FuncName(), err)
  56. return
  57. }
  58. err = redisCache_DeviceClassList.Put(key, str, 24*time.Hour)
  59. if err != nil {
  60. logs.Println("set key:", key, ",value:", str, err)
  61. }
  62. return
  63. }
  64. // if r,is :=Redis_Get(T_sn);is{
  65. // return r,nil
  66. // }
  67. func Redis_DeviceClassList_Get(key string) (r DeviceClassList, is bool) {
  68. if redisCache_DeviceClassList.IsExist(key) {
  69. logs.Println("找到key:", key)
  70. v := redisCache_DeviceClassList.Get(key)
  71. json.Unmarshal(v.([]byte), &r)
  72. return r, true
  73. }
  74. logs.Println("没有 找到key:", key)
  75. return DeviceClassList{}, false
  76. }
  77. func Redis_DeviceClassList_DelK(key string) (err error) {
  78. err = redisCache_DeviceClassList.Delete(key)
  79. return
  80. }
  81. // ---------------- 特殊方法 -------------------
  82. // 获取 ById
  83. func Read_DeviceClassList_ById(id int) (r DeviceClassList, is bool) {
  84. o := orm.NewOrm()
  85. r = DeviceClassList{Id: id}
  86. err := o.Read(&r) // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
  87. if err != nil {
  88. logs.Error(lib.FuncName(), err)
  89. return r, false
  90. }
  91. return r, true
  92. }
  93. // 获取 By
  94. func Read_DeviceClassList(T_sn string) (r DeviceClassList, is bool) {
  95. if r, is = Redis_DeviceClassList_Get(T_sn); is == true {
  96. return r, true
  97. }
  98. o := orm.NewOrm()
  99. qs := o.QueryTable(new(DeviceClassList))
  100. err := qs.Filter("T_sn", T_sn).One(&r)
  101. if err != nil {
  102. logs.Println(lib.FuncName(), err)
  103. return r, false
  104. }
  105. Redis_DeviceClassList_Set(T_sn, r)
  106. return r, true
  107. }
  108. // 添加
  109. func Read_DeviceClassList_T_class_T_sn(T_class int, T_sn string) (r DeviceClassList, is bool) {
  110. o := orm.NewOrm()
  111. qs := o.QueryTable(new(DeviceClassList))
  112. err := qs.Filter("T_sn", T_sn).Filter("T_class", T_class).One(&r)
  113. if err != nil {
  114. logs.Println(lib.FuncName(), err)
  115. return r, false
  116. }
  117. return r, true
  118. }
  119. func Read_DeviceClassList_T_class_T_id(T_class int, T_id string) (r DeviceClassList, is bool) {
  120. o := orm.NewOrm()
  121. qs := o.QueryTable(new(DeviceClassList))
  122. err := qs.Filter("T_id", T_id).Filter("T_class", T_class).Filter("T_State", 1).One(&r)
  123. if err != nil {
  124. logs.Println(lib.FuncName(), err)
  125. return r, false
  126. }
  127. return r, true
  128. }
  129. // 添加
  130. func Add_DeviceClassList(r DeviceClassList) (id int64, is bool) {
  131. o := orm.NewOrm()
  132. //r.T_State = 1
  133. //err := o.Read(&r, "T_class", "T_sn", "T_State") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
  134. //if err == nil {
  135. // if r.Id > 0 {
  136. // logs.Println("重复添加", r.T_class, r.T_sn)
  137. // return 0, false
  138. // }
  139. //}
  140. id, err := o.Insert(&r)
  141. if err != nil {
  142. logs.Error(lib.FuncName(), err)
  143. return 0, false
  144. }
  145. Redis_DeviceClassList_Set(r.T_sn, r)
  146. return id, true
  147. }
  148. // 删除
  149. func Delete_DeviceClassList(v DeviceClassList) bool {
  150. o := orm.NewOrm()
  151. if num, err := o.Delete(&v); err == nil {
  152. logs.Println("Number of records deleted in database:", num)
  153. } else {
  154. logs.Println(lib.FuncName(), err)
  155. return false
  156. }
  157. Redis_DeviceClassList_DelK(v.T_sn)
  158. return true
  159. }
  160. // 删除
  161. func Delete_DeviceClassList_(v DeviceClassList) bool {
  162. o := orm.NewOrm()
  163. v.T_State = 0
  164. if num, err := o.Update(&v, "T_State"); err == nil {
  165. logs.Println("Number of records updated in database:", num)
  166. } else {
  167. logs.Println(lib.FuncName(), err)
  168. return false
  169. }
  170. Redis_DeviceClassList_DelK(v.T_sn)
  171. return true
  172. }
  173. // 修改
  174. func Update_DeviceClassList(m DeviceClassList, cols ...string) bool {
  175. o := orm.NewOrm()
  176. if num, err := o.Update(&m, cols...); err == nil {
  177. logs.Println("Number of records updated in database:", num)
  178. Redis_DeviceClassList_Set(m.T_sn, m)
  179. return true
  180. } else {
  181. logs.Println(lib.FuncName(), err)
  182. }
  183. return false
  184. }
  185. // 获取列表
  186. func Read_DeviceClassList_List(T_class int, T_sn string, page int, page_z int) (r []DeviceClassList, cnt int64) {
  187. o := orm.NewOrm()
  188. // 也可以直接使用 Model 结构体作为表名
  189. qs := o.QueryTable(new(DeviceClassList))
  190. var offset int64
  191. if page <= 1 {
  192. offset = 0
  193. } else {
  194. offset = int64((page - 1) * page_z)
  195. }
  196. cond := orm.NewCondition()
  197. cond1 := cond.And("T_class", T_class).And("T_sn__icontains", T_sn).And("T_State", 1) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
  198. if page_z == 9999 {
  199. qs.SetCond((*orm2.Condition)(cond1)).OrderBy("T_id").All(&r)
  200. } else {
  201. qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_id").All(&r)
  202. }
  203. cnt, _ = qs.SetCond((*orm2.Condition)(cond1)).Count()
  204. return r, cnt
  205. }
  206. func Read_DeviceClassList_OrderList(T_class int, T_sn, T_id, T_remark string, page int, page_z int) (r []DeviceClassList, cnt int64) {
  207. o := orm.NewOrm()
  208. var maps_z []orm2.ParamsList
  209. pagez := page_z
  210. var offset int
  211. if page <= 1 {
  212. offset = 0
  213. } else {
  214. page -= 1
  215. offset = page * pagez
  216. }
  217. sqlWhere := "t_class = " + strconv.Itoa(T_class) + " AND t__state = 1"
  218. if len(T_sn) > 1 {
  219. sqlWhere += " AND t_sn like \"%" + T_sn + "%\""
  220. }
  221. if len(T_id) > 1 {
  222. sqlWhere += " AND T_id like \"%" + T_id + "%\""
  223. }
  224. if len(T_remark) > 0 {
  225. sqlWhere += " AND t_remark like \"%" + T_remark + "%\""
  226. }
  227. sql := "SELECT COUNT(ID) FROM device_class_list WHERE " + sqlWhere
  228. logs.Println(sql)
  229. _, err := o.Raw(sql).ValuesList(&maps_z)
  230. if err != nil {
  231. return r, 0
  232. }
  233. if len(maps_z) == 0 {
  234. return r, 0
  235. }
  236. //logs.Println("maps_z;",maps_z[0][0])
  237. sql = "SELECT * FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "
  238. if page_z != 9999 {
  239. sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
  240. }
  241. logs.Println(sql)
  242. _, err = o.Raw(sql).QueryRows(&r)
  243. if err != nil {
  244. logs.Println(lib.FuncName(), err)
  245. return r, 0
  246. }
  247. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  248. key, _ := strconv.Atoi(maps_z[0][0].(string))
  249. return r, int64(key)
  250. }
  251. // 获取列表
  252. func Read_DeviceClassList_List_id(T_class_Id int) (r []DeviceClassList) {
  253. o := orm.NewOrm()
  254. // 也可以直接使用 Model 结构体作为表名
  255. qs := o.QueryTable(new(DeviceClassList))
  256. qs.Filter("T_class", T_class_Id).Filter("T_State", 1).All(&r)
  257. return r
  258. }
  259. // 排除终端
  260. func Read_DeviceClassList_List_id_By_Terminal(T_class_Id int, T_Terminal bool) (r []DeviceClassList) {
  261. o := orm.NewOrm()
  262. // 也可以直接使用 Model 结构体作为表名
  263. sqlWhere := "t_class = " + strconv.Itoa(T_class_Id) + " AND t__state = 1"
  264. if T_Terminal == true {
  265. sqlWhere += " AND t_terminal = 2"
  266. } else {
  267. sqlWhere += " AND t_terminal <= 1"
  268. }
  269. sql := "SELECT * FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "
  270. logs.Println(sql)
  271. _, err := o.Raw(sql).QueryRows(&r)
  272. if err != nil {
  273. logs.Error(lib.FuncName(), err)
  274. }
  275. return r
  276. }
  277. // 获取列表
  278. func Read_DeviceClassList_List_id_T_remark(T_class_Id int, T_remark string) (r []DeviceClassList) {
  279. o := orm.NewOrm()
  280. T_remark_s := strings.Split(T_remark, "|")
  281. sqlWhere := "t_class = " + strconv.Itoa(T_class_Id) + " AND t__state = 1 AND t_terminal <= 1"
  282. var conditions []string
  283. for _, v := range T_remark_s {
  284. if v == "" {
  285. continue
  286. }
  287. conditions = append(conditions, fmt.Sprintf("t_remark LIKE '%%%s%%'", v))
  288. }
  289. if len(conditions) > 0 {
  290. sqlWhere += " AND (" + strings.Join(conditions, " OR ") + ")"
  291. }
  292. sql := "SELECT * FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "
  293. logs.Println(sql)
  294. _, err := o.Raw(sql).QueryRows(&r)
  295. if err != nil {
  296. logs.Error(lib.FuncName(), err)
  297. }
  298. return r
  299. }
  300. // 获取列表
  301. func Read_DeviceClassList_List_id_T_sn(T_class_Id int, T_sn string) (r []DeviceClassList) {
  302. o := orm.NewOrm()
  303. // 也可以直接使用 Model 结构体作为表名
  304. qs := o.QueryTable(new(DeviceClassList))
  305. qs.Filter("T_class", T_class_Id).Filter("T_sn", T_sn).All(&r)
  306. return r
  307. }
  308. // 删除重复设备列表
  309. func Del_DeviceClassList_Duplication(T_class int) error {
  310. o := orm.NewOrm()
  311. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  312. sql := "DELETE FROM device_class_list WHERE ID NOT IN (" +
  313. "SELECT * FROM (SELECT MIN(ID) FROM device_class_list WHERE t__state = 1 AND t_class = " + strconv.Itoa(T_class) +
  314. " GROUP BY t_class, t_id, t_sn) AS keep_ids) " +
  315. " AND t__state = 1 AND t_class = " + strconv.Itoa(T_class)
  316. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  317. logs.Debug(sql)
  318. res, err := o.Raw(sql).Exec()
  319. if err != nil {
  320. logs.Error(lib.FuncName(), err)
  321. return err
  322. }
  323. num, _ := res.RowsAffected()
  324. logs.Debug("删除重复设备列表: ", num)
  325. return nil
  326. }
  327. func DeduplicateById(devices []DeviceClassList) []DeviceClassList {
  328. unique := make(map[int]DeviceClassList)
  329. for _, device := range devices {
  330. if _, exists := unique[device.Id]; !exists {
  331. unique[device.Id] = device
  332. }
  333. }
  334. result := make([]DeviceClassList, 0, len(unique))
  335. for _, device := range unique {
  336. result = append(result, device)
  337. }
  338. return result
  339. }
  340. func ExcludeDevicesById(devices []DeviceClassList, excludeDevices []DeviceClassList) []DeviceClassList {
  341. filteredList := make([]DeviceClassList, 0)
  342. for _, device := range devices {
  343. exclude := false
  344. for _, excludeDevice := range excludeDevices {
  345. if device.T_id == excludeDevice.T_id {
  346. exclude = true
  347. break
  348. }
  349. }
  350. if !exclude {
  351. filteredList = append(filteredList, device)
  352. }
  353. }
  354. return filteredList
  355. }
  356. func JoinDeviceClassListSnToString(devices []DeviceClassList) string {
  357. var builder strings.Builder
  358. for _, device := range devices {
  359. builder.WriteString(device.T_sn)
  360. builder.WriteString("|")
  361. }
  362. return builder.String()
  363. }