From e4fc307d58856a0b319c41f0930cd3b731cb0b24 Mon Sep 17 00:00:00 2001
From: zhangzengfei <zhangzengfei@smartai.com>
Date: 星期二, 11 二月 2025 10:19:47 +0800
Subject: [PATCH] 修复规律分析bug

---
 models/accessRegularity.go |  143 +++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 137 insertions(+), 6 deletions(-)

diff --git a/models/accessRegularity.go b/models/accessRegularity.go
index 8e2d123..286734c 100644
--- a/models/accessRegularity.go
+++ b/models/accessRegularity.go
@@ -15,16 +15,17 @@
 type RegularityModel struct {
 	OrgIds        []interface{} `json:"-"`
 	AreaIds       []interface{} `json:"-"`
-	IdentityType  string        // 浜哄憳韬唤绫诲瀷 闄岀敓浜�, 璁垮, 浣忔埛
+	IdentityType  []string      // 浜哄憳韬唤绫诲瀷 闄岀敓浜�, 璁垮, 浣忔埛
 	KeyPersonType string        // 閲嶇偣浜哄憳绫诲瀷
 	PersonLabel   string        // 浜哄憳韬唤鏍囩
 	Task          *db.ModelTask
 	AlarmType     db.AlarmType // 棰勮鏂瑰紡
 
-	Appearances int // 鍑虹幇娆℃暟
-	Duration    int // 鏃堕棿鑼冨洿, 鍗曚綅澶�
-	StartHour   int // 寮�濮嬭绠楃殑鏃堕棿 閰嶇疆涓哄皬鏃� 23 - 02 琛ㄧず绗竴澶�23鐐� - 绗簩澶╃殑2鐐�
-	EndHour     int // 缁撴潫鏃堕棿
+	Appearances   int    // 鍑虹幇娆℃暟
+	Duration      int    // 鏃堕棿鑼冨洿, 鍗曚綅澶�
+	LastDirection string // 鏈�鍚庝竴娆″嚭琛岀殑鏂瑰悜
+	StartHour     int    // 寮�濮嬭绠楃殑鏃堕棿 閰嶇疆涓哄皬鏃� 23 - 02 琛ㄧず绗竴澶�23鐐� - 绗簩澶╃殑2鐐�
+	EndHour       int    // 缁撴潫鏃堕棿
 }
 
 func (m *RegularityModel) Init(task *db.ModelTask) error {
@@ -42,7 +43,19 @@
 	m.AlarmType = task.AlarmType
 	m.KeyPersonType = task.PersonType
 	m.PersonLabel = task.PersonLabel
-	m.IdentityType = task.IdentityType
+	m.LastDirection = "out"
+	if task.IdentityType != "" {
+		for _, t := range strings.Split(task.IdentityType, ",") {
+			if t == "all" {
+				m.IdentityType = []string{"stranger", "visitor", "resident"}
+				break
+			} else {
+				m.IdentityType = append(m.IdentityType, t)
+			}
+		}
+	} else {
+		m.IdentityType = []string{"stranger", "visitor", "resident"}
+	}
 
 	for _, v := range task.Rules {
 		if v.Alias == "timeRange" {
@@ -64,6 +77,12 @@
 				m.Duration = int(val)
 			}
 		}
+
+		if v.Alias == "direction" {
+			if val, ok := v.Value.(string); ok {
+				m.LastDirection = val
+			}
+		}
 	}
 
 	// 榛樿璁$畻30澶╃殑鏁版嵁
@@ -82,6 +101,59 @@
 
 func (m *RegularityModel) Run() error {
 	results := make([]*db.ModelTaskResults, 0)
+	baseFilter := make([]PersonInfo, 0)
+
+	// 鏌ユ壘鎸囧畾鏃堕棿鑼冨洿鍐呭嚭琛岃繃鐨勬。妗堢紪鍙�
+	now := time.Now()
+	startDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).AddDate(0, 0, -m.Duration)
+	err := db.GetDB().Raw(`
+		SELECT
+			document_number,
+			frequent_address,
+			community_id,
+		FROM
+			snapshot_count_summary
+		WHERE
+			last_appearance_time > ?
+			AND (community_id IN ?
+			OR org_id IN ?)
+			AND status IN ?
+		`, startDate.Unix(), m.AreaIds, m.OrgIds, m.IdentityType).Scan(&baseFilter).Error
+	if err != nil {
+		logger.Warnf(err.Error())
+	}
+
+	esCli := db.GetEsClient()
+	for _, p := range baseFilter {
+		// 璋冪敤es鍒嗘瀽姝や汉鐨勫嚭琛岃寰嬫槸鍚︾鍚堟潯浠讹紝 杩斿洖绗﹀悎鏉′欢鐨勬鏁板拰鏈�鍚庝竴娆$鍚堟潯浠剁殑鏃堕棿
+		sTime := startDate.Format(time.DateTime)
+		eTime := time.Now().Format(time.DateTime)
+		captures, err := service.QueryEsRecord(esCli, sTime, eTime, nil, []interface{}{p.CommunityId}, []string{p.DocumentNumber})
+		if len(captures) == 0 || err != nil {
+			continue
+		}
+
+		// 鏍规嵁鎶撴媿鏃堕棿鍜屽嚭鍏ユ柟鍚戯紝璁$畻绗﹀悎瑙勫垯鍐呯殑鍑哄叆娆℃暟
+		hitCount := countValidDays(captures, m.StartHour, m.EndHour, m.LastDirection)
+
+		if hitCount > m.Appearances {
+			// 鍐欐暟鎹簱
+			result := &db.ModelTaskResults{
+				Title:         m.Task.Name,
+				Event:         fmt.Sprintf("%s %d娆�", m.Task.Name, hitCount),
+				ModelID:       m.Task.ModelID,
+				ModelTaskID:   m.Task.ID,
+				CommunityId:   p.CommunityId,
+				OrgID:         p.OrgId,
+				ObjectIds:     p.DocumentNumber,
+				Location:      p.FrequentAddress,
+				PicDate:       time.Unix(p.LastAppearanceTime, 0).Format(time.DateTime),
+				FirstPersonID: p.DocumentNumber,
+			}
+
+			results = append(results, result)
+		}
+	}
 
 	logger.Debugf("task %s last filter result %d", m.Task.Name, len(results))
 	return service.SaveTaskResults(results)
@@ -101,3 +173,62 @@
 func (m *RegularityModel) eventFormat() string {
 	return ""
 }
+
+func countValidDays(records []*service.ESRecordInfo, startHour, endHour int, direction string) int {
+	layout := "2006-01-02 15:04:05"             // 鏃堕棿鏍煎紡
+	lastDirectionMap := make(map[string]string) // 璁板綍鏈�鍚庝竴鏉� Direction
+	lastTimeMap := make(map[string]time.Time)   // 璁板綍鏈�鍚庝竴鏉℃椂闂�
+
+	// 鍒ゆ柇鏄惁璺ㄥぉ
+	var isCrossDay bool
+	if endHour < startHour {
+		isCrossDay = true
+	}
+
+	for _, record := range records {
+		// 瑙f瀽鏃堕棿
+		t, err := time.Parse(layout, record.PicDate)
+		if err != nil {
+			fmt.Println("瑙f瀽鏃堕棿澶辫触:", err)
+			continue
+		}
+
+		// 鑾峰彇灏忔椂
+		hour := t.Hour()
+		var key string
+
+		if !isCrossDay {
+			// 鍒ゆ柇鏃堕棿鑼冨洿锛屽苟褰掑睘鍒版煇涓�澶�
+			if hour >= startHour && hour < endHour {
+				key = t.Format("2006-01-02")
+			} else {
+				continue // 涓嶅湪缁熻鑼冨洿鍐�
+			}
+		} else {
+			// 鍒ゆ柇鏃堕棿鑼冨洿锛屽苟褰掑睘鍒版煇涓�澶�
+			if hour >= startHour { // 21:00-23:59 褰掑睘褰撳ぉ
+				key = t.Format("2006-01-02")
+			} else if hour < endHour { // 00:00-02:59 褰掑睘鍓嶄竴澶�
+				key = t.AddDate(0, 0, -1).Format("2006-01-02")
+			} else {
+				continue // 涓嶅湪缁熻鑼冨洿鍐�
+			}
+		}
+
+		// 璁板綍璇ユ椂闂存鍐呯殑鏈�鍚庝竴鏉℃暟鎹�
+		if lastTime, exists := lastTimeMap[key]; !exists || t.After(lastTime) {
+			lastTimeMap[key] = t
+			lastDirectionMap[key] = record.CameraLocation.Direction
+		}
+	}
+
+	// 缁熻绗﹀悎鏉′欢
+	count := 0
+	for _, dir := range lastDirectionMap {
+		if dir == direction || direction == "" {
+			count++
+		}
+	}
+
+	return count
+}

--
Gitblit v1.8.0