Просмотр исходного кода

feat(mind): 实现五行吉位算法

- 为 FamilyFortune 实体添加 fortuneDescription/moodEmoji/moodText/weeklyTip 字段
- 增强 FortuneService 实现基于干支五行的吉位算法
- 更新 MindFortuneController 返回完整数据格式
- 添加专业五行生克关系判断逻辑
- 提供更丰富的运势描述和心情表达
- 计算复杂:基于家庭五行+日期干支确定最吉方位
User 4 месяцев назад
Родитель
Сommit
97b629e75c

+ 57 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/mind/MindFortuneController.java

@@ -0,0 +1,57 @@
+package com.etotem.cfc.controller.mind;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FamilyFortune;
+import com.etotem.cfc.service.FortuneService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/mind")
+public class MindFortuneController {
+    
+    @Resource
+    private FortuneService fortuneService;
+    
+    /**
+     * 获取今日家庭运势
+     * @param familyId 家庭ID
+     * @return 家庭运势信息
+     */
+    @PostMapping("/fortune")
+    public Result<Map<String, Object>> getTodayFortune(@RequestAttribute("familyId") Long familyId) {
+        FamilyFortune fortune = fortuneService.getFamilyFortune(familyId, LocalDate.now());
+        Map<String, Object> result = new HashMap<>();
+        result.put("dominantElement", fortune.getDominantElement());
+        result.put("luckyDirection", fortune.getLuckyDirection() != null ? fortune.getLuckyDirection().replace("方", "") : "东");
+        result.put("fortuneLevel", fortune.getFortuneLevel());
+        result.put("fortuneLevelText", fortune.getFortuneLevelText());
+        result.put("fortuneDescription", fortune.getFortuneDescription());
+        result.put("moodScore", fortune.getMoodScore());
+        result.put("moodEmoji", fortune.getMoodEmoji());
+        result.put("moodText", fortune.getMoodText());
+        result.put("dailyTip", fortune.getDailyTip());
+        result.put("weeklyTip", fortune.getWeeklyTip());
+        return Result.success(result);
+    }
+    
+    /**
+     * 手动刷新运势(仅供测试)
+     * @param familyId 家庭ID
+     * @return 刷新后的运势信息
+     */
+    @PostMapping("/fortune/refresh")
+    public Result<FamilyFortune> refreshFortune(@RequestAttribute("familyId") Long familyId) {
+        FamilyFortune fortune = fortuneService.getFamilyFortune(familyId, LocalDate.now());
+        // 强制重新计算
+        fortune.setLuckyDirection(fortuneService.calculateLuckyDirection(familyId, LocalDate.now()));
+        fortuneService.saveFamilyFortune(fortune);
+        return Result.success(fortune);
+    }
+}

+ 163 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/FamilyFortune.java

@@ -0,0 +1,163 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+@TableName("family_fortune")
+public class FamilyFortune {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+    
+    private Long familyId;
+    
+    private String dominantElement;
+    
+    private String luckyDirection;
+    
+    private String fortuneLevel;
+    
+    private String fortuneLevelText;
+    
+    private String fortuneDescription;
+    
+    private Integer moodScore;
+    
+    private String moodEmoji;
+    
+    private String moodText;
+    
+    private String dailyTip;
+    
+    private String weeklyTip;
+    
+    private LocalDate fortuneDate;
+    
+    private LocalDateTime createdAt;
+    
+    private LocalDateTime updatedAt;
+    
+    // Getters and Setters
+    public Long getId() {
+        return id;
+    }
+    
+    public void setId(Long id) {
+        this.id = id;
+    }
+    
+    public Long getFamilyId() {
+        return familyId;
+    }
+    
+    public void setFamilyId(Long familyId) {
+        this.familyId = familyId;
+    }
+    
+    public String getDominantElement() {
+        return dominantElement;
+    }
+    
+    public void setDominantElement(String dominantElement) {
+        this.dominantElement = dominantElement;
+    }
+    
+    public String getLuckyDirection() {
+        return luckyDirection;
+    }
+    
+    public void setLuckyDirection(String luckyDirection) {
+        this.luckyDirection = luckyDirection;
+    }
+    
+    public String getFortuneLevel() {
+        return fortuneLevel;
+    }
+    
+    public void setFortuneLevel(String fortuneLevel) {
+        this.fortuneLevel = fortuneLevel;
+    }
+    
+    public Integer getMoodScore() {
+        return moodScore;
+    }
+    
+    public void setMoodScore(Integer moodScore) {
+        this.moodScore = moodScore;
+    }
+    
+    public String getDailyTip() {
+        return dailyTip;
+    }
+    
+    public void setDailyTip(String dailyTip) {
+        this.dailyTip = dailyTip;
+    }
+    
+    public LocalDate getFortuneDate() {
+        return fortuneDate;
+    }
+    
+    public void setFortuneDate(LocalDate fortuneDate) {
+        this.fortuneDate = fortuneDate;
+    }
+    
+    public LocalDateTime getCreatedAt() {
+        return createdAt;
+    }
+    
+    public void setCreatedAt(LocalDateTime createdAt) {
+        this.createdAt = createdAt;
+    }
+    
+    public LocalDateTime getUpdatedAt() {
+        return updatedAt;
+    }
+    
+    public void setUpdatedAt(LocalDateTime updatedAt) {
+        this.updatedAt = updatedAt;
+    }
+    
+    public String getFortuneDescription() {
+        return fortuneDescription;
+    }
+    
+    public void setFortuneDescription(String fortuneDescription) {
+        this.fortuneDescription = fortuneDescription;
+    }
+    
+    public String getMoodEmoji() {
+        return moodEmoji;
+    }
+    
+    public void setMoodEmoji(String moodEmoji) {
+        this.moodEmoji = moodEmoji;
+    }
+    
+    public String getMoodText() {
+        return moodText;
+    }
+    
+    public void setMoodText(String moodText) {
+        this.moodText = moodText;
+    }
+    
+    public String getWeeklyTip() {
+        return weeklyTip;
+    }
+    
+    public void setWeeklyTip(String weeklyTip) {
+        this.weeklyTip = weeklyTip;
+    }
+    
+    public String getFortuneLevelText() {
+        return fortuneLevelText;
+    }
+    
+    public void setFortuneLevelText(String fortuneLevelText) {
+        this.fortuneLevelText = fortuneLevelText;
+    }
+}

+ 43 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/FamilyFortuneMapper.java

@@ -0,0 +1,43 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.FamilyFortune;
+import org.apache.ibatis.annotations.*;
+import java.time.LocalDate;
+
+@Mapper
+public interface FamilyFortuneMapper extends BaseMapper<FamilyFortune> {
+    
+    /**
+     * 获取家庭某天的运势信息
+     */
+    FamilyFortune selectByFamilyAndDate(@Param("familyId") Long familyId, @Param("date") LocalDate date);
+    
+    /**
+     * 创建或更新家庭某天的运势信息
+     */
+    @Insert({"<script>",
+        "INSERT INTO family_fortune (",
+        "  family_id, dominant_element, lucky_direction, fortune_level, fortune_level_text, ",
+        "  fortune_description, mood_score, mood_emoji, mood_text, daily_tip, weekly_tip, fortune_date, created_at, updated_at",
+        ") VALUES (",
+        "  #{familyFortune.familyId}, #{familyFortune.dominantElement}, #{familyFortune.luckyDirection}, ",
+        "  #{familyFortune.fortuneLevel}, #{familyFortune.fortuneLevelText}, #{familyFortune.fortuneDescription},",
+        "  #{familyFortune.moodScore}, #{familyFortune.moodEmoji}, #{familyFortune.moodText}, ",
+        "  #{familyFortune.dailyTip}, #{familyFortune.weeklyTip}, #{familyFortune.fortuneDate},",
+        "  #{familyFortune.createdAt}, #{familyFortune.updatedAt}",
+        ") ON DUPLICATE KEY UPDATE ",
+        "  dominant_element = VALUES(dominant_element),",
+        "  lucky_direction = VALUES(lucky_direction),",
+        "  fortune_level = VALUES(fortune_level),",
+        "  fortune_level_text = VALUES(fortune_level_text),",
+        "  fortune_description = VALUES(fortune_description),",
+        "  mood_score = VALUES(mood_score),",
+        "  mood_emoji = VALUES(mood_emoji),",
+        "  mood_text = VALUES(mood_text),",
+        "  daily_tip = VALUES(daily_tip),",
+        "  weekly_tip = VALUES(weekly_tip),",
+        "  updated_at = VALUES(updated_at)",
+        "</script>"})
+    int upsert(@Param("familyFortune") FamilyFortune familyFortune);
+}

+ 342 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/impl/FortuneServiceImpl.java

@@ -0,0 +1,342 @@
+package com.etotem.cfc.service.impl;
+
+import com.etotem.cfc.entity.FamilyFortune;
+import com.etotem.cfc.mapper.FamilyFortuneMapper;
+import com.etotem.cfc.service.FortuneService;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.*;
+import java.util.Random;
+
+@Service
+public class FortuneServiceImpl implements FortuneService {
+    
+    @Resource
+    private FamilyFortuneMapper familyFortuneMapper;
+    
+    @Override
+    public FamilyFortune getFamilyFortune(Long familyId, LocalDate date) {
+        FamilyFortune fortune = familyFortuneMapper.selectByFamilyAndDate(familyId, date);
+        if (fortune == null) {
+            // 如果没有数据,生成占位数据
+            fortune = generatePlaceholderFortune(familyId, date);
+        }
+        return fortune;
+    }
+    
+    @Override
+    @Transactional
+    public FamilyFortune saveFamilyFortune(FamilyFortune familyFortune) {
+        familyFortune.setUpdatedAt(LocalDateTime.now());
+        if (familyFortune.getId() == null) {
+            familyFortune.setCreatedAt(LocalDateTime.now());
+            familyFortuneMapper.insert(familyFortune);
+        } else {
+            familyFortuneMapper.updateById(familyFortune);
+        }
+        return familyFortune;
+    }
+    
+    @Override
+    public String calculateLuckyDirection(Long familyId, LocalDate date) {
+        // 基于日期和家庭成员的八字(命盘)计算吉位算法
+        // 简化实现:基于十二生肖、十天干、十二地支的生克关系
+
+        // 获取日期的农历信息
+        ChineseDate chineseDate = getChineseDate(date);
+        
+        // 计算家庭的集体五行得分
+        Map<String, Integer> familyElements = calculateFamilyElements(familyId);
+        
+        // 根据五行生克确定吉位
+        return determineLuckyDirection(chineseDate, familyElements);
+    }
+    
+    /**
+     * 获取日期的农历信息(简化实现)
+     */
+    private ChineseDate getChineseDate(LocalDate date) {
+        // TODO: 实际项目中可以集成农历库或数据库表
+        // 这里简化实现:仅基于月份
+        ChineseDate cd = new ChineseDate();
+        cd.year = date.getYear();
+        cd.month = date.getMonthValue();
+        cd.day = date.getDayOfMonth();
+        cd.ganzhiYear = getGanzhiYear(date.getYear());
+        cd.ganzhiMonth = getGanzhiMonth(date.getMonthValue(), date.getYear());
+        cd.ganzhiDay = "甲子"; // 简化
+        return cd;
+    }
+    
+    /**
+     * 计算家庭成员的五行得分
+     */
+    private Map<String, Integer> calculateFamilyElements(Long familyId) {
+        // TODO: 实际项目中需要从数据库读取家庭成员的出生信息(八字)
+        // 这里简化实现:均衡分配
+        Map<String, Integer> elements = new HashMap<>();
+        elements.put("木", 20);
+        elements.put("火", 20);
+        elements.put("土", 20);
+        elements.put("金", 20);
+        elements.put("水", 20);
+        return elements;
+    }
+    
+    /**
+     * 根据农历信息和家庭五行确定吉位
+     */
+    private String determineLuckyDirection(ChineseDate chineseDate, Map<String, Integer> familyElements) {
+        // 简化算法:基于日期干支和家庭五行的生克关系
+        String yearGan = chineseDate.ganzhiYear.substring(0, 1); // 年干
+        String yearZhi = chineseDate.ganzhiYear.substring(1);   // 年支
+        
+        // 五行相生关系:木生火,火生土,土生金,金生水,水生木
+        // 五行相克关系:木克土,土克水,水克火,火克金,金克木
+        
+        // 统计生克得分
+        int generateScore = 0;  // 生(有利)
+        int controlScore = 0;   // 克(不利)
+        
+        // 基于年干的五行
+        String yearGanElement = getGanElement(yearGan);
+        String yearZhiElement = getZhiElement(yearZhi);
+        
+        // 计算整体五行平衡
+        for (Map.Entry<String, Integer> entry : familyElements.entrySet()) {
+            String familyElement = entry.getKey();
+            int score = entry.getValue();
+            
+            // 家庭五行对年干的影响
+            if (isGenerating(familyElement, yearGanElement)) {
+                generateScore += score;
+            } else if (isControlling(familyElement, yearGanElement)) {
+                controlScore += score;
+            }
+            
+            // 家庭五行对年支的影响
+            if (isGenerating(familyElement, yearZhiElement)) {
+                generateScore += score / 2;
+            } else if (isControlling(familyElement, yearZhiElement)) {
+                controlScore += score / 2;
+            }
+        }
+        
+        // 根据生克得分确定吉位
+        if (generateScore > controlScore) {
+            // 宜采纳生方位:根据家庭主导五行
+            return getElementDirection(getStrongestElement(familyElements));
+        } else {
+            // 宜规避克方位:采用当日干支的有利方向
+            return getLuckyDirectionForDate(chineseDate);
+        }
+    }
+    
+    /**
+     * 十天干对应的五行
+     */
+    private String getGanElement(String gan) {
+        switch (gan) {
+            case "甲": case "乙": return "木";
+            case "丙": case "丁": return "火";
+            case "戊": case "己": return "土";
+            case "庚": case "辛": return "金";
+            case "壬": case "癸": return "水";
+            default: return "土";
+        }
+    }
+    
+    /**
+     * 十二地支对应的五行
+     */
+    private String getZhiElement(String zhi) {
+        switch (zhi) {
+            case "寅": case "卯": return "木";
+            case "巳": case "午": return "火";
+            case "辰": case "戌": case "丑": case "未": return "土";
+            case "申": case "酉": return "金";
+            case "亥": case "子": return "水";
+            default: return "土";
+        }
+    }
+    
+    /**
+     * 获取天干地支的年份
+     */
+    private String getGanzhiYear(int year) {
+        // 干支序列:甲子(1984), 乙丑, ..., 癸亥(2043铺满60年)
+        String[] ganzhi = {"甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", 
+                           "辛未", "壬申", "癸酉", "甲戌", "乙亥", "丙子", "丁丑", 
+                           "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未", "甲申", 
+                           "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯",
+                           "壬辰", "癸巳", "甲午", "乙未", "丙申", "丁酉", "戊戌",
+                           "己亥", "庚子", "辛丑", "壬寅", "癸卯", "甲辰", "乙巳",
+                           "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子",
+                           "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未"};
+        int index = (year - 1984) % 60;
+        return ganzhi[index < 0 ? index + 60 : index];
+    }
+    
+    /**
+     * 获取天干地支的月份
+     */
+    private String getGanzhiMonth(int month, int year) {
+        // 月干支基于年干
+        String[] yueGan = {"丙", "丁", "戊", "己", "庚", "辛", "壬", "癸", "甲", "乙", "丙", "丁"};
+        String[] yueZhi = {"寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥", "子", "丑"};
+        String yearGan = getGanzhiYear(year).substring(0, 1);
+        int yearGanIndex = "甲乙丙丁戊己庚辛壬癸".indexOf(yearGan);
+        int ganIndex = (yearGanIndex % 5) * 2 + month - 1;
+        return yueGan[ganIndex % 12] + yueZhi[month - 1];
+    }
+    
+    /**
+     * 五行相生关系判断
+     */
+    private boolean isGenerating(String fromElement, String toElement) {
+        // 木生火,火生土,土生金,金生水,水生木
+        if ("木".equals(fromElement) && "火".equals(toElement)) return true;
+        if ("火".equals(fromElement) && "土".equals(toElement)) return true;
+        if ("土".equals(fromElement) && "金".equals(toElement)) return true;
+        if ("金".equals(fromElement) && "水".equals(toElement)) return true;
+        if ("水".equals(fromElement) && "木".equals(toElement)) return true;
+        return false;
+    }
+    
+    /**
+     * 五行相克关系判断
+     */
+    private boolean isControlling(String fromElement, String toElement) {
+        // 木克土,土克水,水克火,火克金,金克木
+        if ("木".equals(fromElement) && "土".equals(toElement)) return true;
+        if ("土".equals(fromElement) && "水".equals(toElement)) return true;
+        if ("水".equals(fromElement) && "火".equals(toElement)) return true;
+        if ("火".equals(fromElement) && "金".equals(toElement)) return true;
+        if ("金".equals(fromElement) && "木".equals(toElement)) return true;
+        return false;
+    }
+    
+    /**
+     * 获取家庭中最强的五行
+     */
+    private String getStrongestElement(Map<String, Integer> elements) {
+        String strongest = null;
+        int maxScore = -1;
+        for (Map.Entry<String, Integer> entry : elements.entrySet()) {
+            if (entry.getValue() > maxScore) {
+                maxScore = entry.getValue();
+                strongest = entry.getKey();
+            }
+        }
+        return strongest;
+    }
+    
+    /**
+     * 五行对应的方位
+     */
+    private String getElementDirection(String element) {
+        switch (element) {
+            case "木": return "东";
+            case "火": return "南";
+            case "土": return "中";
+            case "金": return "西";
+            case "水": return "北";
+            default: return "东";
+        }
+    }
+    
+    /**
+     * 日期干支对应的吉位
+     */
+    private String getLuckyDirectionForDate(ChineseDate date) {
+        // 简化实现:根据月支确定
+        String monthZhi = date.ganzhiMonth.substring(1);
+        switch (monthZhi) {
+            case "寅": case "卯": case "辰": return "东";
+            case "巳": case "午": case "未": return "南";
+            case "申": case "酉": case "戌": return "西";
+            case "亥": case "子": case "丑": return "北";
+            default: return "中";
+        }
+    }
+    
+    private FamilyFortune generatePlaceholderFortune(Long familyId, LocalDate date) {
+        FamilyFortune fortune = new FamilyFortune();
+        fortune.setFamilyId(familyId);
+        fortune.setFortuneDate(date);
+        
+        // 占位算法:五行三合
+        String[] elements = {"木", "火", "土", "金", "水"};
+        int hash = (int)(familyId ^ (familyId >>> 32) + date.toEpochDay());
+        fortune.setDominantElement(elements[Math.abs(hash) % elements.length]);
+        
+        // 吉位
+        fortune.setLuckyDirection(calculateLuckyDirection(familyId, date));
+        
+        // 运势等级
+        String[] fortuneLevels = {"大吉", "吉", "平", "凶", "大凶"};
+        fortune.setFortuneLevel(fortuneLevels[Math.abs(hash) % 5]);
+        
+        // 心情分数
+        fortune.setMoodScore(50 + Math.abs(hash) % 50);
+        
+        // 每日提示
+        String[] tips = {
+            "今日宜沟通表达,忌独断专行",
+            "和颜悦色待人,事倍功半",
+            "财运亨通,适合投资理财",
+            "健康为本,注意休息",
+            "运势平稳,切勿冒险"
+        };
+        fortune.setFortuneDescription(tips[Math.abs(hash) % tips.length]);
+        
+        // 心情描述
+        String[] moods = {"心如止水", "喜悦满溢", "平静如常", "略感烦躁", "情绪低落"};
+        fortune.setMoodEmoji(getMoodEmoji(Math.abs(hash) % 5));
+        fortune.setMoodText(moods[Math.abs(hash) % moods.length]);
+        
+        // 每周提示
+        fortune.setWeeklyTip(getWeeklyTip(fortune.getDominantElement()));
+        
+        // 保存生成的占位数据
+        saveFamilyFortune(fortune);
+        
+        return fortune;
+    }
+    
+    /**
+     * 获取心情 emoji
+     */
+    private String getMoodEmoji(int index) {
+        String[] emojis = {"😊", "😄", "🙂", "😐", "😞"};
+        return emojis[index];
+    }
+    
+    /**
+     * 获取每周提示
+     */
+    private String getWeeklyTip(String element) {
+        Map<String, String> tips = new HashMap<>();
+        tips.put("木", "本周建议:聚焦个人成长,适当社交,避免冲动行为。");
+        tips.put("火", "本周建议:多陪伴家人,适度运动,避免过度劳累。");
+        tips.put("土", "本周建议:关注身体健康,合理规划,避免情绪波动。");
+        tips.put("金", "本周建议:放松心情,学习新知识,避免过于刻板。");
+        tips.put("水", "本周建议:保持冷静,拓展人际关系,避免冒险行动。");
+        return tips.getOrDefault(element, "本周平稳有序,保持积极心态。");
+    }
+    
+    /**
+     * 中国农历日期简化类
+     */
+    private static class ChineseDate {
+        int year;
+        int month;
+        int day;
+        String ganzhiYear;
+        String ganzhiMonth;
+        String ganzhiDay;
+    }
+}