1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753 |
- 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
- logs.Debug(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
- }
- logs.Info("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
- }
- logs.Info("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
- logs.Debug(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)
- }
- logs.Debug(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
- logs.Debug(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
- }
- 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)
- }
- logs.Debug(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
- }
- // 用户首页统计(查询最近40天),使用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"
- 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 {
- logs.Debug(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)
- }
- logs.Debug(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
- logs.Debug(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)
- }
- logs.Debug(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 conf.UseNewWarningQuery {
- 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 conf.UseNewWarningQuery {
- 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 {
- logs.Error("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
- }
|