| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250 |
- package controllers
- import (
- // 根据实际项目结构调整导入路径
- "Tech/common"
- "Tech/models"
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "strings"
- "time"
- "github.com/beego/beego/v2/client/orm"
- beego "github.com/beego/beego/v2/server/web"
- // 新增导入
- )
- var (
- dtLastPauseTime time.Time // 全局变量记录上次暂停时间
- )
- type CourseRunController struct {
- beego.Controller
- }
- func (c *CourseRunController) CourseRun() {
- type Request struct {
- CourseID int `json:"courseID"`
- TraineeGUID string `json:"traineeGUID"`
- TrainingImplementationID string `json:"trainingImplementationID"`
- TrainingPlanID string `json:"trainingPlanID"`
- TrainingPlanName string `json:"trainingPlanName"`
- }
- var req Request
- requestBody := c.Ctx.Input.RequestBody
- println("Request Body:", string(requestBody))
- if err := json.Unmarshal(requestBody, &req); err != nil {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- if req.CourseID == 0 {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "缺少课程ID参数",
- }
- c.ServeJSON()
- return
- }
- o := orm.NewOrm()
- // 查询是否存在正在运行的课程(课程用时为0表示正在运行)
- var runningCourse models.CourseRunLog
- err := o.QueryTable(new(models.CourseRunLog)).
- Filter("CourseTime", 0).
- OrderBy("-RunLogID").
- One(&runningCourse)
- if err == nil {
- // 存在正在运行的课程
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "有课程正在运行中,无法开始新课程",
- }
- c.ServeJSON()
- return
- } else if err != orm.ErrNoRows {
- // 查询出错
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询运行课程状态失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 查询课程信息
- var course models.CourseInfo
- err = o.QueryTable(new(models.CourseInfo)).
- Filter("CourseID", req.CourseID).
- One(&course)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程信息失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 获取最大的课程运行ID号,然后ID号加1
- var maxRunLogID int
- err = o.Raw("SELECT COALESCE(MAX(运行记录编号), 0) FROM CourseRunLog").QueryRow(&maxRunLogID)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询最大运行日志ID失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- nextRunLogID := maxRunLogID + 1
- // 从用户信息缓存中通过TraineeGUID查询TraineeName
- traineeName := ""
- if req.TraineeGUID != "" {
- // 从缓存中获取用户信息
- userInfo, exists := GetUserInfoFromCache_RYEMPID(req.TraineeGUID)
- if exists {
- traineeName = userInfo.XM
- }
- }
- // 生成唯一的TrainingRecordGUID,使用时间戳+随机数确保唯一性
- trainingRecordGUID := fmt.Sprintf("%s-%d", time.Now().Format("20060102150405"), time.Now().UnixNano()%1000000)
- // 创建新的课程运行记录
- newRunLog := models.CourseRunLog{
- RunLogID: nextRunLogID, // 使用计算出的ID
- RunCourseID: req.CourseID,
- RunCourseName: course.CourseName,
- RunDateTime: time.Now().Format("2006-01-02 15:04:05"),
- CourseTime: 0, // 初始为0,表示正在运行
- CourseScore: 0,
- TraineeGUID: req.TraineeGUID,
- TraineeName: traineeName,
- TrainingRecordGUID: trainingRecordGUID,
- TrainingImplementationID: req.TrainingImplementationID,
- TrainingPlanID: req.TrainingPlanID,
- }
- // 插入课程运行记录
- id, err := o.Insert(&newRunLog)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "创建课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- if req.TrainingImplementationID != "" && req.TrainingPlanID != "" && CurrentLoginMode == 0 {
- // 通知信息化系统开始培训
- err = common.NotifyTMSStartTraining(int(id), course, req.TraineeGUID, req.TrainingImplementationID, req.TrainingPlanID, "")
- if err != nil {
- // 如果通知信息化系统失败,删除刚刚创建的课程运行记录
- o.Delete(&newRunLog)
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "通知信息化系统开始培训失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- }
- // 通知电调开课
- isret, err := c.tellEStartCourse(req.CourseID, int(id), course.LineNo)
- if !isret || err != nil {
- // 如果通知电调开课失败,删除刚刚创建的课程运行记录
- o.Delete(&newRunLog)
- // 错误信息已经在 tellEStartCourse 中设置
- c.ServeJSON()
- return
- }
- // 开课成功则继续后续操作
- // 根据课程评价列表生成评价日志记录
- var evaList []*models.CourseEvaList
- _, err = o.QueryTable(new(models.CourseEvaList)).
- Filter("CourseID", req.CourseID).
- OrderBy("SeqNo").
- All(&evaList)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程评价列表失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 为每个评价项创建评价日志记录
- for _, eva := range evaList {
- evaLog := models.CourseEvaLog{
- RunLogID: int(id), // 使用运行记录ID作为关联标识
- RunCourseID: req.CourseID,
- RunOperID: eva.SeqNo, // 使用评价序号作为操作ID
- OperTime: 0, // 初始化时间为0
- OperScore: 0, // 初始化得分为0
- SeqNo: eva.SeqNo,
- EvaTargetRole: eva.EvaTargetRole,
- EvaName: eva.EvaName,
- EvaMapID: eva.EvaMapID,
- EvaType: eva.EvaType,
- EvaSource: eva.EvaSource,
- EvaScore: eva.EvaScore,
- EvaDeduction: eva.EvaDeduction,
- DisqualificationItem: eva.DisqualificationItem,
- IsOperated: 0, // 节点是否操作 0 未操作 1 已操作
- }
- _, err = o.Insert(&evaLog)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "创建课程评价日志失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- }
- // 成功返回记录ID
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "课程开始运行",
- "data": map[string]interface{}{
- "runLogID": id,
- "TrainingPlanName": req.TrainingPlanName,
- },
- }
- c.ServeJSON()
- }
- // / 通知电调服务课程开始
- func (c *CourseRunController) tellEStartCourse(courseID int, runLogID int, lineNo int) (bool, error) {
- // 从配置文件读取电调服务IP和端口
- electricalIP, err := beego.AppConfig.String("ElectricalIP")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "读取电调服务IP配置失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- electricalPort, err := beego.AppConfig.Int("ElectricalPort")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "读取电调服务端口配置失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- // 构造电调服务地址
- electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/Run", electricalIP, electricalPort)
- // 准备请求数据
- type CourseStartReq struct {
- CourseID int `json:"CourseID"`
- CourseRunID int `json:"CourseRunID"`
- LineNo int `json:"LineID"`
- SubParam1 string `json:"subParam1"`
- SubParam2 string `json:"subParam2"`
- }
- startReq := CourseStartReq{
- CourseID: courseID,
- CourseRunID: runLogID,
- LineNo: lineNo,
- SubParam1: "",
- SubParam2: "",
- }
- reqBody, err := json.Marshal(startReq)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "构造通知电调服务请求体失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- // 调用电调服务CourseStart接口
- resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody))
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "调用电调服务开课接口失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- defer resp.Body.Close()
- // 检查响应状态
- if resp.StatusCode != http.StatusOK {
- bodyBytes, _ := io.ReadAll(resp.Body)
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
- }
- c.ServeJSON()
- return false, fmt.Errorf("电调服务返回异常状态码: %d", resp.StatusCode)
- }
- // 读取响应体(可根据实际需求解析响应内容)
- _, _ = io.ReadAll(resp.Body)
- return true, nil
- }
- // / 通知电调服务课程结束
- func (c *CourseRunController) tellEStopCourse(courseID int, runLogID int) (bool, error) {
- // 从配置文件读取电调服务IP和端口
- electricalIP, err := beego.AppConfig.String("ElectricalIP")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "读取电调服务IP配置失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- electricalPort, err := beego.AppConfig.Int("ElectricalPort")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "读取电调服务端口配置失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- // 构造电调服务地址
- electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/Stop", electricalIP, electricalPort)
- // 准备请求数据
- type CourseStopReq struct {
- CourseID int `json:"CourseID"`
- CourseRunID int `json:"CourseRunID"`
- CtrlStatus int `json:"CtrlStatus"`
- }
- stopReq := CourseStopReq{
- CourseID: courseID,
- CourseRunID: runLogID,
- CtrlStatus: 0,
- }
- reqBody, err := json.Marshal(stopReq)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "构造通知电调服务请求体失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- // 调用电调服务CourseStop接口
- resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody))
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "调用电调服务停课接口失败: " + err.Error(),
- }
- c.ServeJSON()
- return false, err
- }
- defer resp.Body.Close()
- // 检查响应状态
- if resp.StatusCode != http.StatusOK {
- bodyBytes, _ := io.ReadAll(resp.Body)
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
- }
- c.ServeJSON()
- return false, fmt.Errorf("电调服务返回异常状态码: %d", resp.StatusCode)
- }
- // 读取响应体(可根据实际需求解析响应内容)
- _, _ = io.ReadAll(resp.Body)
- return true, nil
- }
- func (c *CourseRunController) CoursePause() {
- type Request struct {
- SetFlag int `json:"setFlag"` // 1表示暂停,2表示恢复
- }
- var req Request
- if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- if req.SetFlag != 1 && req.SetFlag != 2 {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "参数值错误,SetFlag应为1或2",
- }
- c.ServeJSON()
- return
- }
- o := orm.NewOrm()
- // 查询正在进行的课程(课程用时为0表示正在运行)
- var runningCourse models.CourseRunLog
- err := o.QueryTable(new(models.CourseRunLog)).
- Filter("CourseTime", 0).
- OrderBy("-RunLogID").
- One(&runningCourse)
- if err != nil {
- if err == orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "没有正在运行的课程",
- }
- c.ServeJSON()
- return
- }
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询运行课程状态失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- switch req.SetFlag {
- case 1: // 暂停课程
- if runningCourse.PauseFlag == 1 {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "课程已在暂停状态",
- }
- c.ServeJSON()
- return
- }
- // 设置暂停标记并记录暂停开始时间
- runningCourse.PauseFlag = 1
- dtLastPauseTime = time.Now()
- case 2: // 恢复课程
- if runningCourse.PauseFlag != 1 {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "课程未处于暂停状态",
- }
- c.ServeJSON()
- return
- }
- // 如果有暂停开始时间,则计算暂停时长并累加到总暂停时长
- if !dtLastPauseTime.IsZero() {
- pauseDuration := int(time.Since(dtLastPauseTime).Seconds())
- if pauseDuration > 0 {
- runningCourse.PauseTotalTime += pauseDuration
- }
- // 清除暂停开始时间
- dtLastPauseTime = time.Time{}
- }
- // 清除暂停标记
- runningCourse.PauseFlag = 0
- }
- // 更新课程运行记录,修改PauseFlag和PauseTotalTime字段
- _, err = o.Update(&runningCourse, "PauseFlag", "PauseTotalTime")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "更新课程暂停状态失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- var msg string
- if req.SetFlag == 1 {
- msg = "课程已暂停"
- } else {
- msg = "课程已恢复"
- }
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": msg,
- "data": runningCourse, // 返回完整的CourseRunLog数据
- }
- c.ServeJSON()
- }
- // /course/stop 停止课程运行
- func (c *CourseRunController) CourseStop() {
- o := orm.NewOrm()
- // 查询最新的课程运行记录
- var latestCourse models.CourseRunLog
- err := o.QueryTable(new(models.CourseRunLog)).
- OrderBy("-RunLogID").
- One(&latestCourse)
- if err != nil {
- if err == orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "没有找到任何课程运行记录",
- }
- c.ServeJSON()
- return
- }
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 检查课程是否已经结束
- if latestCourse.CourseTime > 0 {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "课程已经结束,无法再次结束",
- }
- c.ServeJSON()
- return
- }
- // 计算课程用时(从开始时间到当前时间的秒数)
- startTime, err := time.ParseInLocation("2006-01-02 15:04:05", latestCourse.RunDateTime, time.Local)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "解析课程开始时间失败: " + err.Error(),
- "runStatus": 0,
- "data": nil,
- }
- c.ServeJSON()
- return
- }
- courseDuration := int(time.Since(startTime).Seconds())
- // 更新课程记录
- latestCourse.CourseTime = courseDuration
- latestCourse.PauseFlag = -1
- latestCourse.FinishDateTime = time.Now().Format("2006-01-02 15:04:05")
- _, err = o.Update(&latestCourse, "CourseTime", "PauseFlag", "FinishDateTime")
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "更新课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "课程运行已停止",
- "data": map[string]interface{}{
- "runLogID": latestCourse.RunLogID,
- "courseID": latestCourse.RunCourseID,
- "duration": courseDuration,
- "startTime": latestCourse.RunDateTime,
- },
- }
- // 通知电调服务课程结束
- _, err = c.tellEStopCourse(latestCourse.RunCourseID, latestCourse.RunLogID)
- if err != nil {
- fmt.Println("通知电调服务停止课程失败: " + err.Error())
- // c.Data["json"] = map[string]interface{}{
- // "code": 500,
- // "msg": "通知电调服务停止课程失败: " + err.Error(),
- // }
- // c.ServeJSON()
- // return
- }
- if CurrentLoginMode == 0 {
- // 通知信息化系统结束培训
- err = common.NotifyTMSStopTraining(latestCourse.TrainingRecordGUID)
- if err != nil {
- // 记录错误日志,但不中断操作
- fmt.Println("通知信息化系统结束培训失败: " + err.Error())
- }
- err = DoUploadTMS(latestCourse.RunLogID)
- if err != nil {
- fmt.Println("上传电子考评表失败: " + err.Error())
- }
- }
- c.ServeJSON()
- }
- // /course/status 查询课程运行状态
- func (c *CourseRunController) CourseStatus() {
- o := orm.NewOrm()
- // 查询最新的课程运行记录
- var latestCourse models.CourseRunLog
- err := o.QueryTable(new(models.CourseRunLog)).
- OrderBy("-RunLogID").
- One(&latestCourse)
- if err != nil {
- if err == orm.ErrNoRows {
- // 没有课程运行记录
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "成功",
- "data": map[string]interface{}{
- "runStatus": 0, // 0表示无记录/未运行
- },
- }
- c.ServeJSON()
- return
- }
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- "data": map[string]interface{}{
- "runStatus": 0,
- },
- }
- c.ServeJSON()
- return
- }
- // 判断课程是否结束
- if latestCourse.CourseTime > 0 {
- // 课程已结束,返回空data
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "成功",
- "data": map[string]interface{}{
- "runStatus": 0, // 0表示未运行(课程已结束)
- },
- }
- } else {
- // 课程正在进行中,计算运行时间并返回详细信息
- startTime, err := time.ParseInLocation("2006-01-02 15:04:05", latestCourse.RunDateTime, time.Local)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "解析课程开始时间失败: " + err.Error(),
- "data": map[string]interface{}{
- "runStatus": 0,
- },
- }
- c.ServeJSON()
- return
- }
- // 获取当前时间
- now := time.Now()
- fmt.Printf("目标时间: %v\n", startTime)
- fmt.Printf("当前时间: %v\n", now)
- // 计算时间差(秒)
- diff := int(now.Sub(startTime).Seconds())
- // 确定运行状态
- runStatus := 1 // 默认为正在运行
- if latestCourse.PauseFlag == 1 {
- runStatus = 2 // 2表示暂停中
- }
- // 计算calTime为开始时间加上暂停时间后的格式化时间
- calTime := startTime.Add(time.Duration(latestCourse.PauseTotalTime) * time.Second).Format("2006-01-02 15:04:05")
- // 课程正在进行中,返回详细信息
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "成功",
- "data": map[string]interface{}{
- "runLogID": latestCourse.RunLogID,
- "runCourseID": latestCourse.RunCourseID,
- "runCourseName": latestCourse.RunCourseName,
- "runDateTime": latestCourse.RunDateTime,
- "courseTime": diff, // 实时计算的运行时间
- "courseScore": latestCourse.CourseScore,
- "pauseFlag": latestCourse.PauseFlag,
- "pauseTotalTime": latestCourse.PauseTotalTime,
- "calTime": calTime, // 开始时间+暂停时间后的时间
- "runStatus": runStatus, // 0表示未运行,1表示正在运行,2表示暂停中
- },
- }
- }
- c.ServeJSON()
- }
- // /runrecord/listone 获取课程运行记录数据
- func (c *CourseRunController) RunRecordListOne() {
- // 定义请求参数结构体
- type Request struct {
- RunLogID int `json:"runLogID"`
- }
- var req Request
- // 解析请求参数
- if len(c.Ctx.Input.RequestBody) > 0 {
- if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- }
- o := orm.NewOrm()
- var runRecords []models.CourseRunLog
- var err error
- // 如果RunLogID > 0,则查询对应运行记录ID的记录
- // 如果RunLogID = 0 或者没有传参,则查询最新一条记录
- if req.RunLogID > 0 {
- // 查询指定RunLogID的运行记录
- var record models.CourseRunLog
- err = o.QueryTable(new(models.CourseRunLog)).Filter("RunLogID", req.RunLogID).One(&record)
- if err != nil && err != orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 如果找到了记录,则添加到数组中
- if err != orm.ErrNoRows {
- runRecords = append(runRecords, record)
- }
- } else {
- // 查询最新一条运行记录
- var latestRecord models.CourseRunLog
- err = o.QueryTable(new(models.CourseRunLog)).OrderBy("-RunLogID").One(&latestRecord)
- if err != nil && err != orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 如果找到了记录,则添加到数组中
- if err != orm.ErrNoRows {
- runRecords = append(runRecords, latestRecord)
- }
- }
- //判断课程是否结束,如果课程未结束,计算课程运行时间 CourseTime
- // 构建结果
- type RunRecordDetail struct {
- RunLogID int `json:"runLogID"`
- RunCourseID int `json:"runCourseID"`
- RunCourseName string `json:"runCourseName"`
- RunDateTime string `json:"runDateTime"`
- CourseTime int `json:"courseTime"`
- CourseScore float64 `json:"courseScore"`
- PauseFlag int `json:"pauseFlag"` //1:已经暂停,1运行中,-1课程结束
- PauseTotalTime int `json:"pauseTotalTime"`
- RunStatus int `json:"runStatus"` // 0表示未运行,1表示正在运行,2表示暂停中
- }
- var results []RunRecordDetail
- // 遍历运行记录并获取课程详细信息及应用筛选
- for _, record := range runRecords {
- // 查询对应的课程信息
- var courseInfo models.CourseInfo
- err = o.QueryTable(new(models.CourseInfo)).Filter("CourseID", record.RunCourseID).One(&courseInfo)
- if err != nil && err != orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程信息失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 判断课程是否结束,如果课程未结束,计算课程运行时间 CourseTime
- if record.PauseFlag != -1 {
- // 课程未结束,重新计算运行时间
- // 将字符串转换为时间
- startTime, err := time.ParseInLocation("2006-01-02 15:04:05", record.RunDateTime, time.Local)
- if err == nil {
- // 计算从开始时间到当前时间的时间差(秒)
- duration := time.Since(startTime).Seconds()
- // 减去暂停的总时间得到实际运行时间
- record.CourseTime = int(duration) - record.PauseTotalTime
- if record.CourseTime < 0 {
- record.CourseTime = 0
- }
- }
- }
- detail := RunRecordDetail{
- RunLogID: record.RunLogID,
- RunCourseID: record.RunCourseID,
- RunCourseName: record.RunCourseName,
- RunDateTime: record.RunDateTime,
- CourseTime: record.CourseTime,
- CourseScore: record.CourseScore,
- PauseFlag: record.PauseFlag,
- PauseTotalTime: record.PauseTotalTime,
- RunStatus: func() int {
- // 根据PauseFlag确定运行状态
- if record.PauseFlag == 1 {
- return 2 // 暂停中(默认情况)
- } else if record.PauseFlag == -1 {
- return 0 // 课程结束(未运行)
- } else {
- return 1
- }
- }(),
- }
- results = append(results, detail)
- }
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "查询成功",
- "count": len(results),
- "data": results,
- }
- c.ServeJSON()
- }
- // /runrecord/list 获取课程运行记录数据列表
- func (c *CourseRunController) RunRecordList() {
- // 定义请求参数结构体
- type Request struct {
- CourseName string `json:"courseName"`
- TypeID int `json:"typeID"`
- CourseID int `json:"courseID"`
- LineNo int `json:"lineNo"`
- Creator string `json:"creator"`
- StartTime string `json:"startTime"`
- EndTime string `json:"endTime"`
- }
- var req Request
- // 解析请求参数
- if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
- c.Ctx.Output.SetStatus(400)
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- o := orm.NewOrm()
- // 构建结果
- type RunRecordDetail struct {
- RunLogID int `json:"runLogID"`
- RunCourseID int `json:"runCourseID"`
- RunCourseName string `json:"runCourseName"`
- RunDateTime string `json:"runDateTime"`
- CourseTime int `json:"courseTime"`
- CourseScore float64 `json:"courseScore"`
- PauseFlag int `json:"pauseFlag"`
- PauseTotalTime int `json:"pauseTotalTime"`
- RunStatus int `json:"runStatus"` // 0表示未运行,1表示正在运行,2表示暂停中
- }
- var results []RunRecordDetail
- // 使用原生SQL进行联合查询,提高查询效率
- sql := `SELECT
- r.运行记录编号,
- r.运行课程ID,
- r.运行课程名称,
- r.运行日期时间,
- r.课程用时,
- r.课程得分,
- r.暂停标记,
- r.暂停累计时长
- FROM CourseRunLog r`
- // 构建WHERE条件
- var conditions []string
- var args []interface{}
- // 添加课程ID筛选条件
- if req.CourseID != 0 {
- conditions = append(conditions, "r.运行课程ID = ?")
- args = append(args, req.CourseID)
- }
- // 添加时间范围筛选条件
- if req.StartTime != "" && req.EndTime != "" {
- conditions = append(conditions, "r.运行日期时间 >= ?")
- args = append(args, req.StartTime)
- conditions = append(conditions, "r.运行日期时间 <= ?")
- args = append(args, req.EndTime)
- }
- // 如果有其他筛选条件,则需要JOIN CourseInfo表
- needJoin := req.CourseName != "" || req.TypeID != 0 || req.LineNo != 0 || req.Creator != ""
- if needJoin {
- sql += " LEFT JOIN CourseInfo c ON r.运行课程ID = c.课程ID"
- if req.CourseName != "" {
- conditions = append(conditions, "c.课程名称 LIKE ?")
- args = append(args, "%"+req.CourseName+"%")
- }
- if req.TypeID != 0 {
- conditions = append(conditions, "c.分类ID = ?")
- args = append(args, req.TypeID)
- }
- if req.LineNo != 0 {
- conditions = append(conditions, "c.线路号 = ?")
- args = append(args, req.LineNo)
- }
- if req.Creator != "" {
- conditions = append(conditions, "c.创建人 LIKE ?")
- args = append(args, "%"+req.Creator+"%")
- }
- }
- // 添加WHERE条件到SQL
- if len(conditions) > 0 {
- sql += " WHERE " + strings.Join(conditions, " AND ")
- }
- // 添加排序
- sql += " ORDER BY r.运行记录编号 DESC"
- // 执行查询
- var runRecords []models.CourseRunLog
- _, err := o.Raw(sql, args...).QueryRows(&runRecords)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 转换为结果格式
- for _, record := range runRecords {
- // 判断课程是否结束,如果课程未结束,计算课程运行时间 CourseTime
- courseTime := record.CourseTime
- if record.PauseFlag != -1 {
- // 课程未结束,重新计算运行时间
- // 将字符串转换为时间
- startTime, err := time.ParseInLocation("2006-01-02 15:04:05", record.RunDateTime, time.Local)
- if err == nil {
- // 计算从开始时间到当前时间的时间差(秒)
- duration := time.Since(startTime).Seconds()
- // 减去暂停的总时间得到实际运行时间
- calculatedTime := int(duration) - record.PauseTotalTime
- if calculatedTime > 0 {
- courseTime = calculatedTime
- }
- }
- }
- detail := RunRecordDetail{
- RunLogID: record.RunLogID,
- RunCourseID: record.RunCourseID,
- RunCourseName: record.RunCourseName,
- RunDateTime: record.RunDateTime,
- CourseTime: courseTime,
- CourseScore: record.CourseScore,
- PauseFlag: record.PauseFlag,
- PauseTotalTime: record.PauseTotalTime,
- RunStatus: func() int {
- // 根据PauseFlag确定运行状态
- if record.PauseFlag == 1 {
- return 2 // 暂停中(默认情况)
- } else if record.PauseFlag == -1 {
- return 0 // 课程结束(未运行)
- } else {
- return 1
- }
- }(),
- }
- results = append(results, detail)
- }
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "查询成功",
- "count": len(results),
- "data": results,
- }
- c.ServeJSON()
- }
- // /runrecord/delete 删除课程运行记录
- func (c *CourseRunController) RunRecordDelete() {
- // 定义请求参数结构体
- type Request struct {
- RunLogID int `json:"runLogID"`
- }
- var req Request
- if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- if req.RunLogID == 0 {
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请提供有效的运行记录ID",
- }
- c.ServeJSON()
- return
- }
- o := orm.NewOrm()
- // 删除课程运行记录
- n, err := o.Delete(&models.CourseRunLog{RunLogID: req.RunLogID})
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "删除失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- if n == 0 {
- c.Data["json"] = map[string]interface{}{
- "code": 404,
- "msg": "运行记录不存在",
- }
- c.ServeJSON()
- return
- }
- // 同时删除相关的操作记录和评价记录
- o.QueryTable(new(models.CourseOperLog)).Filter("RunLogID", req.RunLogID).Delete()
- o.QueryTable(new(models.CourseEvaLog)).Filter("RunLogID", req.RunLogID).Delete()
- // 构造返回结果
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "删除成功",
- }
- c.ServeJSON()
- }
- // /oper/runrecord/list 获取操作运行记录列表
- func (c *CourseRunController) OperRunRecordList() {
- // 定义请求参数结构体
- type Request struct {
- RunLogID int `json:"runLogID"`
- }
- // 解析请求参数
- var req Request
- if len(c.Ctx.Input.RequestBody) > 0 {
- if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 400,
- "msg": "请求参数格式错误: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- }
- // 获取数据库连接
- o := orm.NewOrm()
- // 查找课程运行记录:如果RunLogID > 0,则查询对应的记录,否则查询最近一条记录
- var latestCourseRun models.CourseRunLog
- var err error
- if req.RunLogID > 0 {
- // 查询指定RunLogID的课程运行记录
- err = o.QueryTable(new(models.CourseRunLog)).
- Filter("RunLogID", req.RunLogID).
- One(&latestCourseRun)
- } else {
- // 查找最近的课程运行记录(按RunLogID倒序排列,取第一个)
- err = o.QueryTable(new(models.CourseRunLog)).
- OrderBy("-RunLogID").
- One(&latestCourseRun)
- }
- if err != nil {
- if err == orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 404,
- "msg": "未找到任何课程运行记录",
- }
- } else {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询课程运行记录失败: " + err.Error(),
- }
- }
- c.ServeJSON()
- return
- }
- // 查找该课程运行记录对应的所有操作日志,并按RunOperID排序
- var operLogs []models.CourseOperLog
- _, err = o.QueryTable(new(models.CourseOperLog)).
- Filter("RunLogID", latestCourseRun.RunLogID).
- OrderBy("RunOperID").
- All(&operLogs)
- if err != nil {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询操作日志失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 一次性查询所有模板信息到内存中
- var allTemplates []models.TemplateOperation
- _, err = o.QueryTable(new(models.TemplateOperation)).All(&allTemplates)
- if err != nil && err != orm.ErrNoRows {
- c.Data["json"] = map[string]interface{}{
- "code": 500,
- "msg": "查询模板信息失败: " + err.Error(),
- }
- c.ServeJSON()
- return
- }
- // 建立模板ID到模板信息的映射
- templateMap := make(map[int]models.TemplateOperation)
- for _, tmpl := range allTemplates {
- templateMap[tmpl.TemplateID] = tmpl
- }
- // 为每个操作日志添加课程名称和模板信息
- type OperLogWithCourseName struct {
- RunLogID int `json:"runLogID"`
- RunCourseID int `json:"runCourseID"`
- RunOperID int `json:"runOperID"`
- TemplateID int `json:"templateID"`
- CategoryName string `json:"categoryName"`
- SubCategoryName string `json:"subCategoryName"`
- TemplateName string `json:"templateName"`
- TemplateType int `json:"templateType"`
- OperName string `json:"operName"`
- OperTime int `json:"operTime"`
- OperScore float64 `json:"operScore"`
- OperParam1 string `json:"operParam1"`
- OperParam2 string `json:"operParam2"`
- OperParam3 string `json:"operParam3"`
- OperParam4 string `json:"operParam4"`
- OperParam5 string `json:"operParam5"`
- CourseName string `json:"courseName"`
- }
- operLogsWithCourseName := make([]OperLogWithCourseName, len(operLogs))
- for i, log := range operLogs {
- // 从内存中获取模板信息
- categoryName := ""
- subCategoryName := ""
- templateName := ""
- templateType := 0
- if template, exists := templateMap[log.TemplateID]; exists {
- categoryName = template.CategoryName
- subCategoryName = template.SubCategoryName
- templateName = template.TemplateName
- templateType = template.TemplateType
- }
- operLogsWithCourseName[i] = OperLogWithCourseName{
- RunLogID: log.RunLogID,
- RunCourseID: log.RunCourseID,
- RunOperID: log.RunOperID,
- TemplateID: log.TemplateID,
- CategoryName: categoryName,
- SubCategoryName: subCategoryName,
- TemplateName: templateName,
- TemplateType: templateType,
- OperName: log.OperName,
- OperTime: log.OperTime,
- OperScore: log.OperScore,
- OperParam1: log.OperParam1,
- OperParam2: log.OperParam2,
- OperParam3: log.OperParam3,
- OperParam4: log.OperParam4,
- OperParam5: log.OperParam5,
- CourseName: latestCourseRun.RunCourseName,
- }
- }
- // 返回结果,返回操作日志列表和课程名称
- c.Data["json"] = map[string]interface{}{
- "code": 200,
- "msg": "获取操作日志列表成功",
- "data": operLogsWithCourseName,
- }
- c.ServeJSON()
- }
|