package Warning import ( "Cold_Api/conf" "Cold_Api/controllers/lib" db "Cold_Api/initialize" "Cold_Api/models/Account" "encoding/json" "fmt" "github.com/astaxie/beego/cache" _ "github.com/astaxie/beego/cache/redis" "github.com/beego/beego/v2/adapter/orm" orm2 "github.com/beego/beego/v2/client/orm" "github.com/beego/beego/v2/core/logs" _ "github.com/go-sql-driver/mysql" "github.com/gomodule/redigo/redis" "gorm.io/gorm" "sort" "strconv" "strings" "sync" "time" ) var ( CompanyCallthepolice = "companyCallthepolice" // 公司管理-设备报警 Callthepolice = "callthepolice" // 公司管理-设备报警 ) // 模板 type Warning struct { Id int64 `orm:"column(ID);size(11);auto;pk" gorm:"column:ID"` T_pid int `orm:"size(256);null" gorm:"column:t_pid"` // Account.Company 绑定公司 T_tp int `orm:"size(200);null" gorm:"column:t_tp"` // 报警类型 ->WarningList T_sn string `orm:"index;size(256);null" gorm:"column:t_sn"` // 设备序列号 T_D_name string `orm:"size(256);null" gorm:"column:t__d_name"` // 设备名称 T_id int `orm:"size(200);null" gorm:"column:t_id"` // 传感器 ID T_DS_name string `orm:"size(256);null" gorm:"column:t__d_s_name"` // 传感器名称 T_Remark string `orm:"type(text);null" gorm:"column:t__remark"` // 采集内容 T_Ut time.Time `orm:"type(timestamp);null;" gorm:"column:t__ut"` // 采集时间 T_fUt time.Time `orm:"type(timestamp);null;" gorm:"column:t_f_ut"` // 首次采集时间 T_Text string `orm:"type(text);null" gorm:"column:t__text"` // 处理备注 T_Log string `orm:"type(text);null" gorm:"column:t__log"` // 通知日志 T_Msid int64 `orm:"size(256);null" gorm:"column:t__msid"` // 消息ID T_State int `orm:"size(2);default(2)" gorm:"column:t__state"` // 0 删除 1 不处理 2 已处理 3 未处理 CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间 UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"` //auto_now 每次 model 保存时都会对时间自动更新 } // 多字段索引 func (u *Warning) TableIndex() [][]string { return [][]string{ []string{"T_pid", "T_tp", "T_State"}, } } /* 分表机制 |--------30天--------| |-----8月---||--------7月---------||--------6月---------||--------5月---------| 每天备份 到对应 月份 */ // 模板 type Warning_R struct { Id int64 T_pid int // Account.Company 绑定公司 T_tp int // 报警类型 ->WarningList T_tp_name string // 报警类型名称 T_sn string // 设备序列号 T_D_name string // 设备名称 T_id int // 传感器 ID T_DS_name string // 传感器名称 T_Remark string // 采集内容 T_Ut string // 采集时间 T_fUt string // 首次采集时间 T_Text string // 处理备注 T_Log []string // 处理日志 T_Msid int64 // 消息ID T_State int // 0 删除 1 未处理 2 已处理 T_history int // 0 40天 1 历史数据 CreateTime string // 创建时间 UpdateTime string // 更新时间 } type CompanyWarning_R struct { Id int64 T_pid int // Account.Company 绑定公司 T_pid_name string // Account.Company 公司名称 T_tp int // 报警类型 ->WarningList T_tp_name string // 报警类型名称 T_sn string // 设备序列号 T_D_name string // 设备名称 T_id int // 传感器 ID T_DS_name string // 传感器名称 T_Remark string // 采集内容 T_Ut string // 采集时间 T_fUt string // 首次采集时间 T_Text string // 处理备注 T_Log []string // 处理日志 T_Msid int64 // 消息ID T_State int // 0 删除 1 未处理 2 已处理 T_history int // 0 40天 1 历史数据 CreateTime string // 创建时间 UpdateTime string // 更新时间 } type Warning_Applet struct { Id int64 T_pid int // Account.Company 绑定公司 T_company_name string // 公司名称 T_tp int // 报警类型 ->WarningList T_tp_name string // 报警类型名称 T_sn string // 设备序列号 T_D_name string // 设备名称 T_id int // 传感器 ID T_DS_name string // 传感器名称 T_Remark string // 采集内容 T_Ut string // 采集时间 T_fUt string // 首次采集时间 T_Text string // 处理备注 T_Log []string // 处理日志 T_Msid int64 // 消息ID T_State int // 0 删除 1 未处理 2 已处理 CreateTime string // 创建时间 } type Warning_Count struct { Key string Count int64 TableCount map[string]int64 } func (t *Warning) TableName() string { return "warning" // 数据库名称 // ************** 替换 FormulaList ************** } var redis_Warning_Count cache.Cache func init() { //注册模型 orm.RegisterModel(new(Warning)) config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`, "redis_Warning_Count", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password) fmt.Println(config) var err error redis_Warning_Count, err = cache.NewCache("redis", config) if err != nil || redis_Warning_Count == nil { errMsg := "failed to init redis" logs.Error(errMsg, err) panic(errMsg) } } func Redis_WarningCount_Set(id int, key string, count int64, TableCount map[string]int64) (err error) { //json序列化 idKey := strconv.Itoa(id) TableCount["SaveTime"] = time.Now().Unix() warningCount, err := Redis_WarningCount_Get(idKey) warningCount = append(warningCount, Warning_Count{ Key: key, Count: count, TableCount: TableCount, }) str, err := json.Marshal(warningCount) if err != nil { logs.Error(lib.FuncName(), err) return } err = redis_Warning_Count.Put(idKey, str, 30*time.Minute) if err != nil { logs.Error("Redis_Admin_Set", "set key:", idKey, ",value:", str, err) } return } // if r,is :=Redis_Get(T_sn);is{ // return r,nil // } func Redis_WarningCount_Get(userId string) (count []Warning_Count, err error) { if redis_Warning_Count.IsExist(userId) { //println("找到key:",key) v := redis_Warning_Count.Get(userId) err = json.Unmarshal(v.([]byte), &count) if err != nil { logs.Error(lib.FuncName(), err) return count, err } return count, nil } return count, redis.ErrNil } func Redis_WarningCount_GetOne(id int, key string) (count int64, tableCount map[string]int64, err error) { countList := []Warning_Count{} tableCount = make(map[string]int64) idKey := strconv.Itoa(id) if !redis_Warning_Count.IsExist(idKey) { return count, tableCount, redis.ErrNil } //println("找到key:",key) v := redis_Warning_Count.Get(idKey) err = json.Unmarshal(v.([]byte), &countList) if err != nil { logs.Error(lib.FuncName(), err) return count, tableCount, err } for _, c := range countList { if c.Key == key { return c.Count, c.TableCount, nil } } return count, tableCount, redis.ErrNil } func Redis_WarningCount_DelK(id int) (err error) { idKey := strconv.Itoa(id) err = redis_Warning_Count.Delete(idKey) if err != nil { logs.Error(lib.FuncName(), err) } return } // ---------------- 特殊方法 ------------------- // T_history 0 40天 1 历史数据 func WarningToWarning_R(T_history int, t Warning) (r Warning_R) { r.Id = t.Id r.T_pid = t.T_pid r.T_tp = t.T_tp r.T_tp_name = Read_WarningType_Get(t.T_tp) r.T_sn = t.T_sn r.T_D_name = t.T_D_name r.T_id = t.T_id r.T_DS_name = t.T_DS_name r.T_Remark = t.T_Remark r.T_Ut = t.T_Ut.Format("2006-01-02 15:04:05") if !t.T_fUt.IsZero() { r.T_fUt = t.T_fUt.Format("2006-01-02 15:04:05") } r.T_Text = t.T_Text if len(t.T_Log) > 0 { r.T_Log = strings.Split(strings.TrimRight(t.T_Log, "\n"), "\n") } r.T_Msid = t.T_Msid r.T_State = t.T_State r.T_history = T_history r.CreateTime = t.CreateTime.Format("2006-01-02 15:04:05") r.UpdateTime = t.UpdateTime.Format("2006-01-02 15:04:05") return r } func WarningToCompanyWarning_R(T_history int, t Warning) (r CompanyWarning_R) { r.Id = t.Id r.T_pid = t.T_pid r.T_pid_name = Account.Read_Company_Get(t.T_pid) r.T_tp = t.T_tp r.T_tp_name = Read_WarningType_Get(t.T_tp) r.T_sn = t.T_sn r.T_D_name = t.T_D_name r.T_id = t.T_id r.T_DS_name = t.T_DS_name r.T_Remark = t.T_Remark r.T_Ut = t.T_Ut.Format("2006-01-02 15:04:05") if !t.T_fUt.IsZero() { r.T_fUt = t.T_fUt.Format("2006-01-02 15:04:05") } r.T_Text = t.T_Text if len(t.T_Log) > 0 { r.T_Log = strings.Split(strings.TrimRight(t.T_Log, "\n"), "\n") } r.T_Msid = t.T_Msid r.T_State = t.T_State r.T_history = T_history r.CreateTime = t.CreateTime.Format("2006-01-02 15:04:05") r.UpdateTime = t.UpdateTime.Format("2006-01-02 15:04:05") return r } func WarningToWarning_Applet(t Warning) (r Warning_Applet) { r.Id = t.Id r.T_pid = t.T_pid company, _ := Account.Read_Company_ById(t.T_pid) r.T_company_name = company.T_name r.T_tp = t.T_tp r.T_tp_name = Read_WarningType_Get(t.T_tp) r.T_sn = t.T_sn r.T_D_name = t.T_D_name r.T_id = t.T_id r.T_DS_name = t.T_DS_name r.T_Remark = t.T_Remark r.T_Ut = t.T_Ut.Format("2006-01-02 15:04:05") if !t.T_fUt.IsZero() { r.T_fUt = t.T_fUt.Format("2006-01-02 15:04:05") } r.T_Text = t.T_Text if len(t.T_Log) > 0 { r.T_Log = strings.Split(strings.TrimRight(t.T_Log, "\n"), "\n") } r.T_Msid = t.T_Msid r.T_State = t.T_State r.CreateTime = t.CreateTime.Format("2006-01-02 15:04:05") return r } // 获取 ById func Read_Warning_ById(id int64) (r Warning) { o := orm.NewOrm() r = Warning{Id: id} err := o.Read(&r) // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名 if err != nil { logs.Error(lib.FuncName(), err) } return r } // 获取 ById func Read_Warning_ById_Backups(id int, T_year string, T_month string) (r Warning, err error) { o := orm.NewOrm() var maps []Warning // Warning_2022_07 Wtab := "warning_" + T_year + "_" + T_month sql_WHERE := fmt.Sprintf(" t__state > 0 AND `ID`= %d", id) sql := "SELECT ID,t_pid,t_tp,t_sn,t__d_name,t_id,t__d_s_name,t__remark,t__ut,t__text,t__log,t__msid,t__state,create_time,update_time " + "FROM " + Wtab + " WHERE" + sql_WHERE fmt.Println(sql) num, err := o.Raw(sql).QueryRows(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } if num == 0 { return r, orm.ErrNoRows } return maps[0], nil } // 添加 func Add_Warning(m Warning) (id int64, err error) { o := orm.NewOrm() id, err = o.Insert(&m) if err != nil { logs.Error(lib.FuncName(), err) } return id, err } // 修改 func Update_Warning(r Warning, cols ...string) bool { o := orm.NewOrm() num, err := o.Update(&r, cols...) if err != nil { logs.Error(lib.FuncName(), err) return false } fmt.Println("Number of records updated in database:", num) return true } // 修改 func Update_Warning_Backups(r Warning, T_year string, T_month string) bool { o := orm.NewOrm() Wtab := "warning_" + T_year + "_" + T_month num, err := o.Raw("UPDATE "+Wtab+" SET `t__text` = ?,`t__state` = ?, `update_time` = ? WHERE `ID` = ?", r.T_Text, r.T_State, r.UpdateTime, r.Id).Exec() if err != nil { logs.Error(lib.FuncName(), err) return false } fmt.Println("Number of records updated in database:", num) return true } // 获取列表 func Read_Warning_List(T_pid int, bindSN, tpList []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { o := orm.NewOrm() // 也可以直接使用 Model 结构体作为表名 var map_r []Warning qs := o.QueryTable(new(Warning)) var offset int64 if page <= 1 { offset = 0 } else { offset = int64((page - 1) * page_z) } cond := orm.NewCondition() cond1 := orm.NewCondition() if len(bindSN) > 0 { cond1 = cond1.And("T_sn__in", bindSN) } if T_pid > 0 { cond1 = cond1.And("T_pid", T_pid) } if len(tpList) > 0 { cond1 = cond1.And("T_tp__in", tpList) } if len(T_name) > 0 { if len(T_name) == 16 { cond1 = cond1.And("T_sn", T_name) } else { cond1 = cond1.AndCond(cond.Or("T_sn__icontains", T_name). Or("T_D_name__icontains", T_name). Or("T_id__icontains", T_name). Or("T_DS_name__icontains", T_name)) } } if len(Time_start_) > 0 { cond1 = cond1.And("T_Ut__gte", Time_start_) } if len(Time_end_) > 0 { cond1 = cond1.And("T_Ut__lte", Time_end_) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { cond1 = cond1.And("T_State__gt", 1) } else if T_handle == 3 { cond1 = cond1.And("T_State", 3) } else { cond1 = cond1.And("T_State__gt", 0) } var err error // 从redis获取报警统计数量 cnt, _, err = Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count() if err != nil { logs.Error(lib.FuncName(), err) return } Redis_WarningCount_Set(T_pid, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } if page_z == 9999 { // 获取全部 _, err = qs.SetCond((*orm2.Condition)(cond1)).OrderBy("-T_Ut").All(&map_r) } else { _, err = qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-T_Ut").All(&map_r) } if err != nil { logs.Error(lib.FuncName(), err) return } for _, v := range map_r { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } // 管理员报警列表 func Read_Admin_Warning_List(admin Account.Admin, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { if len(admin.T_pids) == 0 { return r, cnt } o := orm.NewOrm() // 也可以直接使用 Model 结构体作为表名 var map_r []Warning qs := o.QueryTable(new(Warning)) var offset int64 if page_z == 0 { page_z = conf.Page_size } if page <= 1 { offset = 0 } else { offset = int64((page - 1) * page_z) } cond := orm.NewCondition() cond1 := orm.NewCondition() if admin.T_pids != "*" && len(admin.T_pids) > 0 { list := lib.SplitStringIds(admin.T_pids, "P") cond1 = cond1.And("T_pid__in", list) } if len(T_tp) > 0 { cond1 = cond1.And("T_tp__in", T_tp) } if len(T_name) > 0 { if len(T_name) == 16 { cond1 = cond1.And("T_sn", T_name) } else { cond1 = cond1.AndCond(cond.Or("T_sn__icontains", T_name). Or("T_D_name__icontains", T_name). Or("T_id__icontains", T_name). Or("T_DS_name__icontains", T_name)) } } if len(Time_start_) > 0 { cond1 = cond1.And("T_Ut__gte", Time_start_) } if len(Time_end_) > 0 { cond1 = cond1.And("T_Ut__lte", Time_end_) } //1:默认 2:全部记录 3 未处理 if T_handle == 1 { cond1 = cond1.And("T_State__gt", 1) } else if T_handle == 3 { cond1 = cond1.And("T_State", 3) } else { cond1 = cond1.And("T_State__gt", 0) } var err error // 从redis获取报警统计数量 cnt, _, err = Redis_WarningCount_GetOne(admin.Id, countRedisKey) if err != nil { cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count() if err != nil { logs.Error(lib.FuncName(), err) return } Redis_WarningCount_Set(admin.Id, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } _, err = qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-T_Ut").All(&map_r) if err != nil { logs.Error(lib.FuncName(), err) } for _, v := range map_r { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } // 获取列表备份 func Read_Warning_Backups(T_pid int, bindSN []string, T_year string, T_month string, tpList []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { o := orm.NewOrm() var maps []Warning var maps_z []orm2.ParamsList // 也可以直接使用 Model 结构体作为表名 // Warning_2022_07 Wtab := "warning_" + T_year + "_" + T_month var offset int if page <= 1 { offset = 0 } else { offset = (page - 1) * page_z } sql_WHERE := "" if len(bindSN) > 0 { sql_WHERE += fmt.Sprintf(" AND t_sn in (%s)", lib.StringListToQuotesDotStr(bindSN)) } if T_pid > 0 { sql_WHERE += " AND t_pid = " + strconv.Itoa(T_pid) } if len(tpList) > 0 { tp := lib.StringListToDotStr(tpList) sql_WHERE += fmt.Sprintf(" AND t_tp in (%s)", tp) } if len(T_name) > 0 { sql_WHERE += " AND (t_sn like '%" + T_name + "%' OR t__d_name like '%" + T_name + "%' OR t_id like '%" + T_name + "%' OR t__d_s_name like '%" + T_name + "%')" } if len(Time_start_) > 0 { //cond1 = cond1.And("T_Ut__gte", Time_start_) Time_start_ = lib.ReplaceSQL(Time_start_) sql_WHERE += fmt.Sprintf(" AND t__ut >= '%s'", Time_start_) } if len(Time_end_) > 0 { //cond1 = cond1.And("T_Ut__lte", Time_end_) Time_end_ = lib.ReplaceSQL(Time_end_) sql_WHERE += fmt.Sprintf(" AND t__ut <= '%s'", Time_end_) } //1:默认 2:全部记录 3 未处理 if T_handle == 1 { sql_WHERE += " AND t__state > 1" } else if T_handle == 3 { sql_WHERE += " AND t__state = 3" } else { sql_WHERE += " AND t__state > 0" } // ------------- sql_WHERE = strings.TrimLeft(sql_WHERE, " AND") // 从redis获取报警统计数量 cnt, _, err := Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { sql := "SELECT COUNT(*) FROM " + Wtab + " WHERE " + sql_WHERE fmt.Println(sql) _, err = o.Raw(sql).ValuesList(&maps_z) if err != nil { logs.Error(lib.FuncName(), err) return r, 0 } if len(maps_z) == 0 { return r, 0 } cnt, _ = strconv.ParseInt(maps_z[0][0].(string), 10, 64) Redis_WarningCount_Set(T_pid, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } //fmt.Println("maps_z;",maps_z[0][0]) sql := "SELECT ID,t_pid,t_tp,t_sn,t__d_name,t_id,t__d_s_name,t__remark,t__ut,t__text,t__log,t__msid,t__state,create_time,update_time " + "FROM " + Wtab + " WHERE " + sql_WHERE + " ORDER BY t__ut DESC" if page_z != 9999 { sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z) } fmt.Println(sql) _, err = o.Raw(sql).QueryRows(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } for _, v := range maps { r = append(r, WarningToWarning_R(1, v)) } return r, cnt } // 获取管理员列表备份 func Read_Admin_Warning_Backups(admin Account.Admin, T_year string, T_month string, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { if len(admin.T_pids) == 0 { return r, cnt } o := orm.NewOrm() var maps []Warning var maps_z []orm2.ParamsList // 也可以直接使用 Model 结构体作为表名 // Warning_2022_07 Wtab := "warning_" + T_year + "_" + T_month var offset int if page_z == 0 { page_z = conf.Page_size } if page <= 1 { offset = 0 } else { offset = (page - 1) * page_z } sql_WHERE := "" if admin.T_pids != "*" { list := lib.SplitStringToDotStr(admin.T_pids, "P") sql_WHERE += fmt.Sprintf(" AND t_pid in (%s)", list) } if len(T_tp) > 0 { tp := lib.StringListToDotStr(T_tp) sql_WHERE += fmt.Sprintf(" AND t_tp in (%s)", tp) } if len(T_name) > 0 { sql_WHERE += " AND (t_sn like '%" + T_name + "%' OR t__d_name like '%" + T_name + "%' OR t_id like '%" + T_name + "%' OR t__d_s_name like '%" + T_name + "%')" } if len(Time_start_) > 0 { //cond1 = cond1.And("T_Ut__gte", Time_start_) Time_start_ = lib.ReplaceSQL(Time_start_) sql_WHERE += fmt.Sprintf(" AND t__ut >= '%s'", Time_start_) } if len(Time_end_) > 0 { //cond1 = cond1.And("T_Ut__lte", Time_end_) Time_end_ = lib.ReplaceSQL(Time_end_) sql_WHERE += fmt.Sprintf(" AND t__ut <= '%s'", Time_end_) } //1:默认 2:全部记录 3 未处理 if T_handle == 1 { sql_WHERE += " AND t__state > 1" } else if T_handle == 3 { sql_WHERE += " AND t__state = 3" } else { sql_WHERE += " AND t__state > 0" } sql_WHERE = strings.TrimLeft(sql_WHERE, " AND") // 从redis获取报警统计数量 cnt, _, err := Redis_WarningCount_GetOne(admin.Id, countRedisKey) if err != nil { sql := "SELECT COUNT(*) FROM " + Wtab + " WHERE " + sql_WHERE fmt.Println(sql) _, err = o.Raw(sql).ValuesList(&maps_z) if err != nil { logs.Error(lib.FuncName(), err) return r, 0 } if len(maps_z) == 0 { return r, 0 } cnt, _ = strconv.ParseInt(maps_z[0][0].(string), 10, 64) Redis_WarningCount_Set(admin.Id, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } //fmt.Println("maps_z;",maps_z[0][0]) sql := "SELECT ID,t_pid,t_tp,t_sn,t__d_name,t_id,t__d_s_name,t__remark,t__ut,t__text,t__log,t__msid,t__state,create_time,update_time " + "FROM " + Wtab + " WHERE " + sql_WHERE + " ORDER BY t__ut DESC" if page_z != 9999 { sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z) } fmt.Println(sql) _, err = o.Raw(sql).QueryRows(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } key, _ := strconv.ParseInt(maps_z[0][0].(string), 10, 64) for _, v := range maps { r = append(r, WarningToWarning_R(1, v)) } return r, key } // 用户首页统计 func Read_Warning_ALL_T_State_Count2(T_pid int, T_pids []int, T_handle int, bindSN []string, T_Warning string, Is_Today bool) (cnt int64) { o := orm.NewOrm() qs := o.QueryTable(new(Warning)) cond := orm.NewCondition() cond1 := cond.And("T_State__gt", 0) if T_pid > 0 { cond1 = cond1.And("T_pid", T_pid) } if T_pid == 0 { cond1 = cond1.And("T_pid__in", T_pids) } if len(bindSN) > 0 { cond1 = cond1.And("T_sn__in", bindSN) } if Is_Today { startTime := time.Now().Format("2006-01-02") + " 00:00:00" endTime := time.Now().Format("2006-01-02") + " 23:59:59" cond1 = cond1.And("T_Ut__gte", startTime).And("T_Ut__lte", endTime) } if len(T_Warning) > 0 && T_Warning != "*" { list := lib.SplitStringIds(T_Warning, "W") cond1 = cond1.And("T_tp__in", list) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { cond1 = cond1.And("T_State__gt", 1) } if T_handle == 3 { cond1 = cond1.And("T_State", 3) } cnt, err := qs.SetCond((*orm2.Condition)(cond1)).Count() if err != nil { logs.Error(lib.FuncName(), err) } return cnt } // 用户首页统计,使用gorm查询 func Read_Warning_ALL_T_State_Count(T_pid int, T_pids []int, T_handle int, bindSN []string, T_Warning string, Is_Today bool) (cnt int64) { tableName := "warning" if conf.UseNewWarningQuery { tableName = fmt.Sprintf("warning_%s_%s", time.Now().Format("2006"), time.Now().Format("01")) } gormDB := db.DB.Table(tableName) daysAgo40 := time.Now().AddDate(0, 0, -40).Format("2006-01-02") gormDB.Where("t__state > 0 ").Where("t__ut > ?", daysAgo40+" 00:00:00") if T_pid > 0 { gormDB.Where("t_pid = ?", T_pid) } if T_pid == 0 { gormDB.Where("t_pid in (?)", T_pids) } if len(bindSN) > 0 { gormDB.Where("t_sn in (?)", bindSN) } if Is_Today { startTime := time.Now().Format("2006-01-02") + " 00:00:00" endTime := time.Now().Format("2006-01-02") + " 23:59:59" gormDB.Where("t__ut between ? and ?", startTime, endTime) } if len(T_Warning) > 0 && T_Warning != "*" { list := lib.SplitStringIds(T_Warning, "W") gormDB.Where("t_tp in (?)", list) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { gormDB.Where("t__state > ?", 1) } if T_handle == 3 { gormDB.Where("t__state = ?", 3) } err := gormDB.Count(&cnt).Error if err != nil { logs.Error(lib.FuncName(), err) } return cnt } // 设备日志 type DeviceLogs struct { Id int64 T_sn string // Logs_Txt string // 详情 CreateTime string } func WarningToDeviceLogs(t Warning) (r DeviceLogs) { r.Id = t.Id r.T_sn = t.T_sn r.Logs_Txt = t.T_Remark r.CreateTime = t.CreateTime.Format("2006-01-02 15:04:05") return r } // 获取列表 func Read_DeviceLogs_List(T_sn string, page, page_z int) (r []DeviceLogs, cnt int64) { o := orm.NewOrm() // 也可以直接使用 Model 结构体作为表名 qs := o.QueryTable(new(Warning)) var maps []Warning var offset int64 if page <= 1 { offset = 0 } else { offset = int64((page - 1) * page_z) } _, err := qs.Limit(page_z, offset).Filter("T_sn", T_sn).Filter("T_tp__in", DeviceLogType).OrderBy("-Id").All(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } cnt, err = qs.Filter("T_sn", T_sn).Filter("T_tp__in", DeviceLogType).Count() if err != nil { logs.Error(lib.FuncName(), err) return } for _, v := range maps { r = append(r, WarningToDeviceLogs(v)) } return r, cnt } // 通过传感器类型获取报警列表 func Read_Warning_List_By_DS_T_type(admin *Account.Admin, T_pid int, bindSN []string, T_pids []int, DS_T_type int, T_name string, T_tp []string, page int, page_z int, countRedisKey string) (r []Warning_Applet, cnt int64) { o := orm.NewOrm() // 也可以直接使用 Model 结构体作为表名 var maps []Warning var maps_z []orm2.ParamsList var offset int if page <= 1 { offset = 0 } else { offset = (page - 1) * page_z } // T_State 0 删除 1 不处理 2 已处理 3 未处理 sql_WHERE := "1 < t__state" if admin.T_pid > 0 { if len(T_pids) > 0 { sql_WHERE += fmt.Sprintf(" AND t_pid in (%s) ", lib.IntListToDotStr(T_pids)) } } else { sql_WHERE += " AND t_pid = " + strconv.Itoa(T_pid) } if len(T_tp) > 0 { tp := lib.StringListToDotStr(T_tp) sql_WHERE += fmt.Sprintf(" AND w.t_tp in (%s)", tp) } if len(bindSN) > 0 { sql_WHERE += fmt.Sprintf(" AND t_sn in (%s)", lib.StringListToQuotesDotStr(bindSN)) } if DS_T_type > 0 { sql_WHERE += " AND ds.t_type = " + strconv.Itoa(DS_T_type) } if len(T_name) > 0 { sql_WHERE += " AND (t_sn like '%" + T_name + "%' OR t__d_name like '%" + T_name + "%' OR t_id like '%" + T_name + "%' OR t__d_s_name like '%" + T_name + "%')" } sql := "SELECT COUNT(w.ID) FROM warning w " + "LEFT JOIN ( SELECT t_sn AS tsn,t_id AS tid,t_type FROM device_sensor) AS ds " + "ON w.t_sn = ds.tsn AND w.t_id = ds.tid " + "WHERE " + sql_WHERE cnt, _, err := Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { fmt.Println(sql) _, err = o.Raw(sql).ValuesList(&maps_z) if err != nil { logs.Error(lib.FuncName(), err) return r, 0 } if len(maps_z) == 0 { return r, 0 } cnt, _ = strconv.ParseInt(maps_z[0][0].(string), 10, 64) Redis_WarningCount_Set(T_pid, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } sql = "SELECT w.*, ds.tsn, ds.tid, ds.t_type FROM warning w " + "LEFT JOIN ( SELECT t_sn AS tsn,t_id AS tid,t_type FROM device_sensor) AS ds " + "ON w.t_sn = ds.tsn AND w.t_id = ds.tid " + "WHERE " + sql_WHERE + " ORDER BY t__ut DESC" if page_z != 9999 { sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z) } fmt.Println(sql) _, err = o.Raw(sql).QueryRows(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } for _, v := range maps { r = append(r, WarningToWarning_Applet(v)) } return r, cnt } // 获取当天设备报警总数 func Read_WarningCount_byDay(T_pids []int) (cnt int64) { o := orm.NewOrm() qs := o.QueryTable(new(Warning)) cond := orm.NewCondition() yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02") cond = cond.And("T_State__gt", 0).And("T_tp__in", RateType).And("CreateTime__gte", yesterday+" 00:00:00").And("CreateTime__lte", yesterday+" 23:59:59") if len(T_pids) == 1 { cond = cond.And("T_pid", T_pids[0]) } else if len(T_pids) > 1 { cond = cond.And("T_pid__in", T_pids) } cnt, err := qs.SetCond((*orm2.Condition)(cond)).Count() if err != nil { logs.Error(lib.FuncName(), err) } return cnt } // 公司管理报警列表 func Read_Company_Warning_List(T_pids []int, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, T_pid int, countRedisKey string) (r []CompanyWarning_R, cnt int64) { o := orm.NewOrm() // 也可以直接使用 Model 结构体作为表名 var map_r []Warning qs := o.QueryTable(new(Warning)) var offset int64 if page_z == 0 { page_z = conf.Page_size } if page <= 1 { offset = 0 } else { offset = int64((page - 1) * page_z) } cond := orm.NewCondition() cond1 := orm.NewCondition() if len(T_pids) == 1 { cond1 = cond1.And("T_pid", T_pids[0]) } else if len(T_pids) > 1 { cond1 = cond1.And("T_pid__in", T_pids) } if len(T_tp) > 0 { cond1 = cond1.And("T_tp__in", T_tp) } if len(T_name) > 0 { if len(T_name) == 16 { cond1 = cond1.And("T_sn", T_name) } else { cond1 = cond1.AndCond(cond.Or("T_sn__icontains", T_name). Or("T_D_name__icontains", T_name). Or("T_id__icontains", T_name). Or("T_DS_name__icontains", T_name)) } } if len(Time_start_) > 0 { cond1 = cond1.And("T_Ut__gte", Time_start_) } if len(Time_end_) > 0 { cond1 = cond1.And("T_Ut__lte", Time_end_) } //1:默认 2:全部记录 3 未处理 if T_handle == 1 { cond1 = cond1.And("T_State__gt", 1) } else if T_handle == 3 { cond1 = cond1.And("T_State", 3) } else { cond1 = cond1.And("T_State__gt", 0) } var err error // 从redis获取报警统计数量 cnt, _, err = Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count() if err != nil { logs.Error(lib.FuncName(), err) return } Redis_WarningCount_Set(T_pid, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } _, err = qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-T_Ut").All(&map_r) if err != nil { logs.Error(lib.FuncName(), err) } for _, v := range map_r { r = append(r, WarningToCompanyWarning_R(0, v)) } return r, cnt } // 获取公司管理列表备份 func Read_Company_Warning_Backups(T_pids []int, T_year string, T_month string, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, T_pid int, countRedisKey string) (r []CompanyWarning_R, cnt int64) { if len(T_pids) == 0 { return r, cnt } o := orm.NewOrm() var maps []Warning var maps_z []orm2.ParamsList // 也可以直接使用 Model 结构体作为表名 // Warning_2022_07 Wtab := "warning_" + T_year + "_" + T_month var offset int if page_z == 0 { page_z = conf.Page_size } if page <= 1 { offset = 0 } else { offset = (page - 1) * page_z } sql_WHERE := "" if len(T_pids) == 1 { sql_WHERE += fmt.Sprintf(" AND t_pid = %d", T_pids[0]) } else if len(T_pids) > 1 { sql_WHERE += fmt.Sprintf(" AND t_pid in (%s)", lib.IntListToDotStr(T_pids)) } if len(T_tp) > 0 { tp := lib.StringListToDotStr(T_tp) sql_WHERE += fmt.Sprintf(" AND t_tp in (%s)", tp) } if len(T_name) > 0 { sql_WHERE += " AND (t_sn like '%" + T_name + "%' OR t__d_name like '%" + T_name + "%' OR t_id like '%" + T_name + "%' OR t__d_s_name like '%" + T_name + "%')" } if len(Time_start_) > 0 { //cond1 = cond1.And("T_Ut__gte", Time_start_) Time_start_ = lib.ReplaceSQL(Time_start_) sql_WHERE += fmt.Sprintf(" AND t__ut >= '%s'", Time_start_) } if len(Time_end_) > 0 { //cond1 = cond1.And("T_Ut__lte", Time_end_) Time_end_ = lib.ReplaceSQL(Time_end_) sql_WHERE += fmt.Sprintf(" AND t__ut <= '%s'", Time_end_) } //1:默认 2:全部记录 3 未处理 if T_handle == 1 { sql_WHERE += " AND t__state > 1" } else if T_handle == 3 { sql_WHERE += " AND t__state = 3" } else { sql_WHERE += " AND t__state > 0" } sql_WHERE = strings.TrimLeft(sql_WHERE, " AND") // 从redis获取报警统计数量 cnt, _, err := Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { sql := "SELECT COUNT(*) FROM " + Wtab + " WHERE " + sql_WHERE fmt.Println(sql) _, err = o.Raw(sql).ValuesList(&maps_z) if err != nil { logs.Error(lib.FuncName(), err) return r, 0 } if len(maps_z) == 0 { return r, 0 } cnt, _ = strconv.ParseInt(maps_z[0][0].(string), 10, 64) Redis_WarningCount_Set(T_pid, countRedisKey, cnt, map[string]int64{}) } if cnt == 0 { return r, 0 } sql := "SELECT ID,t_pid,t_tp,t_sn,t__d_name,t_id,t__d_s_name,t__remark,t__ut,t__text,t__log,t__msid,t__state,create_time,update_time " + "FROM " + Wtab + " WHERE " + sql_WHERE + " ORDER BY t__ut DESC" if page_z != 9999 { sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z) } fmt.Println(sql) _, err = o.Raw(sql).QueryRows(&maps) if err != nil { logs.Error(lib.FuncName(), err) return } for _, v := range maps { r = append(r, WarningToCompanyWarning_R(1, v)) } return r, cnt } func GormReadWarningListScopes(T_pid int, bindSN, tpList []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { if T_pid > 0 { db.Where("t_pid = ?", T_pid) } if T_abandon == 1 { // 弃用 if len(abandonSN) > 0 { db.Where("t_sn in (?)", abandonSN) } else { db.Where("1=0") return db } } else { if len(bindSN) > 0 { // 将绑定sn内非弃用sn筛选出来 bindSNWithOutAbandon := lib.FindUniqueElements(bindSN, abandonSN) if len(bindSNWithOutAbandon) > 0 { db.Where("t_sn in (?)", bindSNWithOutAbandon) } else { db.Where("1=0") return db } } else { if len(abandonSN) > 0 { db.Where("t_sn not in (?)", abandonSN) } } } if len(tpList) > 0 { min, max, is := checkStringListContinuous(tpList) if is { db.Where("t_tp between ? and ?", min, max) } else { db.Where("t_tp in (?)", tpList) } } if len(T_name) > 0 { if len(T_name) == 16 { db.Where("t_sn = ?", T_name) } else { likeName := "%" + T_name + "%" db.Where("t_sn like ? or t__d_name like ? or t_id like ? or t__d_s_name like ? ", likeName, likeName, likeName, likeName) } } if len(Time_start_) > 0 { db.Where("t__ut >= ?", Time_start_) } if len(Time_end_) > 0 { db.Where("t__ut <= ?", Time_end_) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { db.Where("t__state > ?", 1) } else if T_handle == 3 { db.Where("t__state = ?", 3) } else { db.Where("t__state > ?", 0) } return db } } // 获取列表 func Gorm_Read_Warning_List(T_pid int, bindSN, tpList []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { tableNames := GenerateWarningTableNames(Time_start_, Time_end_) var err error var warnings []Warning tableCount := make(map[string]int64) gormReadWarningListScopes := GormReadWarningListScopes(T_pid, bindSN, tpList, T_name, T_handle, Time_start_, Time_end_, T_abandon, abandonSN) // 从redis获取报警统计数量 cnt, tableCount, err = Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { for _, tableName := range tableNames { tableDB := db.DB.Table(tableName) var count int64 tableDB.Scopes(gormReadWarningListScopes).Count(&count) tableCount[tableName] = count cnt += count } Redis_WarningCount_Set(T_pid, countRedisKey, cnt, tableCount) } //if cnt == 0 { // return r, 0 //} if page_z == 9999 { for _, tableName := range tableNames { var tableWarning []Warning tableDB := db.DB.Table(tableName) tableDB.Scopes(gormReadWarningListScopes). Order("t__ut desc").Offset(-1).Limit(-1).Find(&tableWarning) warnings = append(warnings, tableWarning...) } for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } offset := (page - 1) * page_z remaining := offset for _, tableName := range tableNames { var tableWarning []Warning tableDB := db.DB.Table(tableName) var count int64 if tableName == fmt.Sprintf("warning_%d_%02d", time.Now().Year(), time.Now().Month()) { if saveTime, ok := tableCount["SaveTime"]; ok { t1 := time.Unix(saveTime, 0) if time.Now().Sub(t1) < 5*time.Minute { if count, ok = tableCount[tableName]; !ok { tableDB.Scopes(gormReadWarningListScopes).Count(&count) tableCount[tableName] = count } } else { tableDB.Scopes(gormReadWarningListScopes).Count(&count) tableCount[tableName] = count } } } else { var ok bool if count, ok = tableCount[tableName]; !ok { tableDB.Scopes(gormReadWarningListScopes).Count(&count) tableCount[tableName] = count } } if remaining >= int(count) { remaining -= int(count) continue } tableDB2 := db.DB.Table(tableName) tableDB2.Scopes(gormReadWarningListScopes).Order("t__ut desc").Offset(remaining).Limit(page_z - len(warnings)).Find(&tableWarning) warnings = append(warnings, tableWarning...) if len(warnings) >= page_z { break } remaining = 0 } for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } func Gorm_Read_Warning_List_Excel(T_pid int, bindSN, tpList []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { tableNames := GenerateWarningTableNames(Time_start_, Time_end_) gormReadWarningListScopes := GormReadWarningListScopes(T_pid, bindSN, tpList, T_name, T_handle, Time_start_, Time_end_, T_abandon, abandonSN) var warnings []Warning var wg sync.WaitGroup for _, tableName := range tableNames { wg.Add(1) go func(table string) { defer wg.Done() offset := 0 limit := 10000 for { var tableWarning []Warning tableDB := db.DB.Table(table) tableDB.Scopes(gormReadWarningListScopes). Order("t__ut desc").Offset(offset).Limit(limit).Find(&tableWarning) if len(tableWarning) == 0 { break // 如果没有数据则结束循环 } offset += limit // 更新偏移量 warnings = append(warnings, tableWarning...) } }(tableName) } // 等待所有协程完成 wg.Wait() // 倒序 sort.Slice(warnings, func(i, j int) bool { if warnings[i].T_Ut.After(warnings[j].T_Ut) { return true } return false }) for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } func GormReadAdminWarningListScopes(admin Account.Admin, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { if admin.T_pids != "*" && len(admin.T_pids) > 0 { list := lib.SplitStringIds(admin.T_pids, "P") db.Where("t_pid in (?)", list) } if T_abandon == 1 { // 查询弃用设备 if len(abandonSN) > 0 { db.Where("t_sn in (?)", abandonSN) } else { db.Where("1=0") return db } } else { if len(abandonSN) > 0 { db.Where("t_sn not in (?)", abandonSN) } } if len(T_tp) > 0 { min, max, is := checkStringListContinuous(T_tp) if is { db.Where("t_tp between ? and ?", min, max) } else { db.Where("t_tp in (?)", T_tp) } } if len(T_name) > 0 { if len(T_name) == 16 { db.Where("t_sn = ?", T_name) } else { likeName := "%" + T_name + "%" db.Where("t_sn like ? or t__d_name like ? or t_id like ? or t__d_s_name like ? ", likeName, likeName, likeName, likeName) } } if len(Time_start_) > 0 { db.Where("t__ut >= ?", Time_start_) } if len(Time_end_) > 0 { db.Where("t__ut <= ?", Time_end_) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { db.Where("t__state > ?", 1) } else if T_handle == 3 { db.Where("t__state = ?", 3) } else { db.Where("t__state > ?", 0) } return db } } // 管理员报警列表 func Gorm_Read_Admin_Warning_List(admin Account.Admin, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { if len(admin.T_pids) == 0 { return r, cnt } gormReadAdminWarningListScopes := GormReadAdminWarningListScopes(admin, T_tp, T_name, T_handle, Time_start_, Time_end_, T_abandon, abandonSN) tableNames := GenerateWarningTableNames(Time_start_, Time_end_) var err error var warnings []Warning tableCount := make(map[string]int64) // 从redis获取报警统计数量 cnt, tableCount, err = Redis_WarningCount_GetOne(admin.Id, countRedisKey) if err != nil { for _, tableName := range tableNames { tableDB := db.DB.Table(tableName) var count int64 tableDB.Scopes(gormReadAdminWarningListScopes).Count(&count) tableCount[tableName] = count cnt += count } Redis_WarningCount_Set(admin.Id, countRedisKey, cnt, tableCount) } if cnt == 0 { return r, 0 } // page_z == 9999 获取全部 if page_z == 9999 { for _, tableName := range tableNames { var tableWarning []Warning tableDB := db.DB.Table(tableName) tableDB.Scopes(gormReadAdminWarningListScopes). Order("t__ut desc").Offset(-1).Limit(-1).Find(&tableWarning) warnings = append(warnings, tableWarning...) } for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } offset := (page - 1) * page_z remaining := offset for _, tableName := range tableNames { var tableWarning []Warning tableDB := db.DB.Table(tableName) count := tableCount[tableName] if remaining >= int(count) { remaining -= int(count) continue } tableDB.Scopes(gormReadAdminWarningListScopes). Order("t__ut desc").Offset(remaining).Limit(page_z - len(warnings)).Find(&tableWarning) warnings = append(warnings, tableWarning...) if len(warnings) >= page_z { break } remaining = 0 } for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } func Gorm_Read_Admin_Warning_List_Excel(admin Account.Admin, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, T_abandon int, abandonSN []string, page int, page_z int, countRedisKey string) (r []Warning_R, cnt int64) { if len(admin.T_pids) == 0 { return r, cnt } gormReadAdminWarningListScopes := GormReadAdminWarningListScopes(admin, T_tp, T_name, T_handle, Time_start_, Time_end_, T_abandon, abandonSN) tableNames := GenerateWarningTableNames(Time_start_, Time_end_) var warnings []Warning var wg sync.WaitGroup for _, tableName := range tableNames { wg.Add(1) go func(table string) { defer wg.Done() offset := 0 limit := 10000 for { var tableWarning []Warning tableDB := db.DB.Table(table) tableDB.Scopes(gormReadAdminWarningListScopes). Order("t__ut desc").Offset(offset).Limit(limit).Find(&tableWarning) if len(tableWarning) == 0 { break // 如果没有数据则结束循环 } offset += limit // 更新偏移量 warnings = append(warnings, tableWarning...) } }(tableName) } // 等待所有协程完成 wg.Wait() // 倒序 sort.Slice(warnings, func(i, j int) bool { if warnings[i].T_Ut.After(warnings[j].T_Ut) { return true } return false }) for _, v := range warnings { r = append(r, WarningToWarning_R(0, v)) } return r, cnt } func GormReadCompanyWarningListScopes(T_pids []int, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { if len(T_pids) > 0 { db.Where("t_pid in (?)", T_pids) } if len(T_tp) > 0 { min, max, is := checkStringListContinuous(T_tp) if is { db.Where("t_tp between ? and ?", min, max) } else { db.Where("t_tp in (?)", T_tp) } } if len(T_name) > 0 { if len(T_name) == 16 { db.Where("t_sn = ?", T_name) } else { likeName := "%" + T_name + "%" db.Where("t_sn like ? or t__d_name like ? or t_id like ? or t__d_s_name like ?", likeName, likeName, likeName, likeName) } } if len(Time_start_) > 0 { db.Where("t__ut >= ?", Time_start_) } if len(Time_end_) > 0 { db.Where("t__ut <= ?", Time_end_) } // T_State 0 删除 1 不处理 2 已处理 3 未处理 // T_handle 1:默认 2:全部记录 3 未处理 if T_handle == 1 { db.Where("t__state > ?", 1) } else if T_handle == 3 { db.Where("t__state = ?", 3) } else { db.Where("t__state > ?", 0) } return db } } // 公司管理报警列表 func Gorm_Read_Company_Warning_List(T_pids []int, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, T_pid int, countRedisKey string) (r []CompanyWarning_R, cnt int64) { gormReadCompanyWarningListScopes := GormReadCompanyWarningListScopes(T_pids, T_tp, T_name, T_handle, Time_start_, Time_end_) tableNames := GenerateWarningTableNames(Time_start_, Time_end_) var err error var warnings []Warning tableCount := make(map[string]int64) // 从redis获取报警统计数量 cnt, tableCount, err = Redis_WarningCount_GetOne(T_pid, countRedisKey) if err != nil { for _, tableName := range tableNames { tableDB := db.DB.Table(tableName) var count int64 tableDB.Scopes(gormReadCompanyWarningListScopes).Count(&count) tableCount[tableName] = count cnt += count } Redis_WarningCount_Set(T_pid, countRedisKey, cnt, tableCount) } if cnt == 0 { return r, 0 } offset := (page - 1) * page_z remaining := offset for _, tableName := range tableNames { var tableWarning []Warning tableDB := db.DB.Table(tableName) count := tableCount[tableName] if remaining >= int(count) { remaining -= int(count) continue } tableDB.Scopes(gormReadCompanyWarningListScopes). Order("t__ut desc").Offset(remaining).Limit(page_z - len(warnings)).Find(&tableWarning) warnings = append(warnings, tableWarning...) if len(warnings) >= page_z { break } remaining = 0 } for _, v := range warnings { r = append(r, WarningToCompanyWarning_R(0, v)) } return r, cnt } func Gorm_Read_Company_Warning_List_Excel(T_pids []int, T_tp []string, T_name string, T_handle int, Time_start_ string, Time_end_ string, page int, page_z int, T_pid int, countRedisKey string) (r []CompanyWarning_R, cnt int64) { gormReadCompanyWarningListScopes := GormReadCompanyWarningListScopes(T_pids, T_tp, T_name, T_handle, Time_start_, Time_end_) tableNames := GenerateWarningTableNames(Time_start_, Time_end_) var warnings []Warning var wg sync.WaitGroup for _, tableName := range tableNames { wg.Add(1) go func(table string) { defer wg.Done() offset := 0 limit := 10000 for { var tableWarning []Warning tableDB := db.DB.Table(table) tableDB.Scopes(gormReadCompanyWarningListScopes). Order("t__ut desc").Offset(offset).Limit(limit).Find(&tableWarning) if len(tableWarning) == 0 { break // 如果没有数据则结束循环 } offset += limit // 更新偏移量 warnings = append(warnings, tableWarning...) } }(tableName) } // 等待所有协程完成 wg.Wait() // 倒序 sort.Slice(warnings, func(i, j int) bool { if warnings[i].T_Ut.After(warnings[j].T_Ut) { return true } return false }) for _, v := range warnings { r = append(r, WarningToCompanyWarning_R(0, v)) } return r, cnt } func GenerateWarningTableNames(startDateStr string, endDateStr string) []string { if len(startDateStr) == 0 || len(endDateStr) == 0 { return []string{} } startDate, _ := lib.TimeStrToTime(startDateStr) endDate, _ := lib.TimeStrToTime(endDateStr) monthsArray := []string{} for startDate.Before(endDate) || startDate.Equal(endDate) { monthsArray = append(monthsArray, fmt.Sprintf("warning_%d_%02d", startDate.Year(), startDate.Month())) startDate = time.Date(startDate.Year(), startDate.Month()+1, 1, 0, 0, 0, 0, time.Local) } sort.Stable(sort.Reverse(sort.StringSlice(monthsArray))) return monthsArray } // 检查数据列表是否连续 返回最小值 最大值 func checkStringListContinuous(nums []string) (int, int, bool) { intNums := make([]int, len(nums)) for i, num := range nums { parsedNum, err := strconv.Atoi(num) if err != nil { fmt.Println("Error converting string to int:", err) return 0, 0, false } intNums[i] = parsedNum } sort.Ints(intNums) for i := 1; i < len(intNums); i++ { if intNums[i] != intNums[i-1]+1 { return 0, 0, false } } return intNums[0], intNums[len(intNums)-1], true }