12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757 |
- 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
- }
|