package com.srs.web.controller.common;

import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.core.page.TableDataInfo;
import com.srs.common.utils.WeChatUtil;
import com.srs.framework.web.service.TokenService;
import com.srs.system.domain.StudentMentalRating;
import com.srs.system.domain.vo.StudentMentalRatingVo;
import com.srs.system.mapper.StudentMentalRatingMapper;
import com.srs.system.mapper.SysUserMapper;
import com.srs.system.service.ISysPostService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;

/**
 * Dify心理问题发送企业微信  知无涯
 */
@Slf4j
@RestController
@RequestMapping("/api/wechat")
public class WeChatMentalAlertController extends BaseController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WeChatUtil weChatUtil;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private StudentMentalRatingMapper studentMentalRatingMapper;
    //岗位
    @Autowired
    private ISysPostService sysPostService;

    /**
     * 处理心理预警通知请求
     */
    @PostMapping("/mentalAlert")
    public AjaxResult handleMentalAlert(@RequestBody MentalAlertRequest request,
                                        HttpServletRequest httpRequest) {

        //  校验 token 是否有效
        LoginUser loginUser = tokenService.getLoginUser(httpRequest);
        if (loginUser == null) {
            return AjaxResult.error("Token无效或已过期");
        }

        String studentId = request.getUserId();

        //  查询辅导员信息
        SysUser teacher = sysUserMapper.selectTeacherByStuNo(request.getUserId());
        if (teacher == null || !StringUtils.hasText(teacher.getUserName())) {
            log.error("辅导员信息不完整，学号: {}", request.getUserId());
            return AjaxResult.error("未分配辅导员或信息不完整");
        }

        // 获取今天日期
        LocalDate today = LocalDate.now();

        // 查询该学生今天已触发的心理预警次数
        int todayCount = studentMentalRatingMapper.countTodayByStudentId(studentId, today);

        /* 保存学生心理问题评级 */
        StudentMentalRating record = new StudentMentalRating();
        record.setStudentId(request.getUserId());
        record.setRating(request.getRating());
        studentMentalRatingMapper.insert(record);

        // 只有评级为"一级风险"时才发送企业微信通知 陈冠元
        if (!"一级风险".equals(request.getRating())) {
            return AjaxResult.success("预警已记录，因评级非一级风险未发送通知");
        }

        // === 判断是否超过当日发送上限（3次）=== 陈冠元
        if (todayCount > 3) {
            return AjaxResult.success("预警已记录，因当日已达上限未发送通知");
        }

        // 构建并发送消息
        try {
            String content = buildContent(request, teacher);
            weChatUtil.sendTextMessage(teacher.getUserName(), content);
            return AjaxResult.success("消息已发送至辅导员");
        } catch (Exception e) {
            log.error("发送企业微信失败", e);
            return AjaxResult.error("发送失败: " + e.getMessage());
        }
    }

    /**
     * 构建企业微信消息内容
     */
    private String buildContent(MentalAlertRequest request, SysUser teacher) {
        String teacherName = StringUtils.hasText(teacher.getNickName())
                ? teacher.getNickName()
                : teacher.getUserName();
        return String.format(
                "【智水AI心理预警通知】\n" +
                        "辅导员：%s（%s）\n" +
                        "学生姓名：%s\n" +
                        "学号：%s\n" +
                        "问题描述：%s\n" +
                        "心理问题评级：%s\n"+
                        "复制链接登陆学工系统PC端查看更多：" +
                        "zhxg.gxsdxy.cn/srs/#/aitutor/chatwarning",
                teacherName,
                teacher.getUserName(),
                request.getUserName(),
                request.getUserId(),
                request.getStudentQuestion(),
                request.getRating()
        );
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class MentalAlertRequest {
        private String userId;          // 学生学号
        private String userName;        // 学生姓名
        private String studentQuestion; // 学生提问内容
        private String aiAnswer;        // AI回复内容
        private String rating;          // 心理问题评级
    }

    /**
     * 获取全部学生心理评级记录
     */
    /**
     * 获取全部学生心理评级记录（支持条件查询和分页）
     */
    @GetMapping("/rating/all")
    public TableDataInfo allRatings(StudentMentalRatingVo queryVo) {
        // 获取当前登录用户信息
        String teacherId = getUsername();
        Long userId = getUserId();
        // 判断是否为学工
        boolean isJwc = RoleBool.isJwc(userId, sysPostService);

        startPage();

        if (isJwc) {
            return getDataTable(studentMentalRatingMapper.selectLatestAllWithConditions(
                    queryVo.getStuNo(), queryVo.getStuName()));
        } else {
            return getDataTable(studentMentalRatingMapper.selectLatestByTeacherIdWithConditions(
                    teacherId, queryVo.getStuNo(), queryVo.getStuName()));
        }
    }
    /**
     * 根据学号获取全部记录
     */
    @GetMapping("/rating/{stuNo}")
    public AjaxResult listByStuNo(@PathVariable String stuNo) {
        return AjaxResult.success(studentMentalRatingMapper.selectByStuNo(stuNo));
    }
}