```
func ChatHandler(c *gin.Context) {
	conn, err := middleware.Upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		handleError(c, err)
		return
	}
	defer conn.Close()

	ctx, cancel := context.WithCancel(context.Background())
	defer func() {
		log.Printf("exit ChatHandler function")
		cancel()
	}()
	userID := c.GetString("userid")
	sendToClientChan := make(chan []byte)

	// Start the conversation's task processor
	conv := task.GetConversation(userID)
	if conv == nil {
		log.Println("Failed to get conversation")
		handleError(c, errors.New("conversation not found"))
		return
	}
	conv.SendToClientChan = sendToClientChan
	conv.StartTaskProcessor()

	// Start goroutine to send messages to the client
	go processMessages(ctx, conn, sendToClientChan)

	// Inactivity timers
	inactivityTimer := time.NewTimer(10 * time.Minute)
	thirtySecondTimer := time.NewTimer(50 * time.Second)

	messageProcessed := make(chan struct{})

	// Start goroutine to handle messages
	go func() {
		defer close(messageProcessed)
		for {
			select {
			case <-ctx.Done():
				log.Println("Exiting message handler goroutine")
				return
			default:
				if err := handleMessage(conn, conv, userID); err != nil {
					log.Println("Error occurred in handleMessage:", err)
					return
				}
				messageProcessed <- struct{}{}
			}
		}
	}()

	for {
		select {
		case <-inactivityTimer.C:
			log.Println("User inactive for 10 minutes, closing connection")
			return
		case <-thirtySecondTimer.C:
			log.Println("User inactive for 50 seconds, sending reminder")
			// Send reminder to the user via sendToClientChan
			sendToClientChan <- utils.NewTextMessage("你好久没回我消息了，可以告诉我你在想什么吗？", "")
		case _, ok := <-messageProcessed:
			if !ok {
				log.Println("Error processing message, exiting loop")
				return
			}
			// Reset timers
			if !inactivityTimer.Stop() {
				<-inactivityTimer.C
			}
			inactivityTimer.Reset(10 * time.Minute)

			if !thirtySecondTimer.Stop() {
				<-thirtySecondTimer.C
			}
			thirtySecondTimer.Reset(50 * time.Second)
		}
	}
}
func handleError(c *gin.Context, err error) {
	c.JSON(200, serializer.WsResponse(err.Error(), 1, "aiSaid", nil))
}

func processMessages(ctx context.Context, conn *websocket.Conn, sendToClientChan chan []byte) {
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()
	log.Println("发送消息到前端的协程创建成功！")
	for {
		select {
		case <-ctx.Done():
			log.Println("发消息到前端的协程退出了")
			return
		case msg := <-sendToClientChan:
			if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
				return
			}
		case <-ticker.C:
			if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
				return
			}
		}
	}
}

// handleMessage 用户每一次发送消息都由这个函数处理
//
//	@param conn websocket 连接对象
//	@param sendToClientChan 发送消息到这个chan 即可，不用关系如何给websocket 发送消息
//	@param userid 用户id 用户获取conversation对象，这个对象内包含上面的message chan
//	@return error 如果是nil 就不是错误，只是说明不知道要怎么处理这个错误。否则就是严重错误，需要断开websocket连接
func handleMessage(conn *websocket.Conn, conv *task.Conversation, userid string) error {
	_, message, err := conn.ReadMessage()
	if err != nil {
		log.Println("Failed to read message:", err)
		// 消费者协程因为超时已经退出了，所以没有消费者，这就会导致这里一直被阻塞，导致协程泄露
		// conv.SendToClientChan <- utils.NewTextMessage("Sorry, I didn't catch that. Could you please repeat?", "")
		return err
	}

	log.Println("Received message:", string(message))

	// Parse user's message into chatBody
	var chatBody models.UserChatReq
	if err := json.Unmarshal(message, &chatBody); err != nil {
		log.Println("Failed to decode message:", string(message), err)
		conv.SendToClientChan <- utils.NewTextMessage("Sorry, I didn't understand that. Could you please rephrase?", "")
		return nil
	}

	useridObj, _ := primitive.ObjectIDFromHex(userid)

	// Determine if we need to create a new task
	if chatBody.WApi == "userSaid" {
		if chatBody.Data.TaskID == "" {
			summaryService := service.NewUserSummaryService(useridObj)
			var activeTask task.Task
			// Check if evaluation test has been done before
			hasTest := summaryService.HasEvaTest()
			stuProfile := summaryService.GetStuProfile()
			if hasTest {
				activeTask = task.NewAITask("", stuProfile, 180, nil, useridObj, models.STUDYTASK, conv)
			} else {
				// If not done before, start anew
				activeTask, _ = task.NewEvaTask("小学生", 180, nil, useridObj, conv)
			}
			// Add the new task to TaskQueue; the task processor will pick it up and run Init
			conv.TaskQueue <- activeTask
			return nil
		} else {
			// Get existing task
			activeTask := task.GetTaskByID(chatBody.Data.TaskID)
			if activeTask.GetTaskType() != task.AI && activeTask.GetTaskType() != task.Eva {
				resByte, _ := json.Marshal(serializer.WsResponse("Task ID does not match API route", 1, "aiSaid", nil))
				conv.SendToClientChan <- resByte
				return errors.New("Task ID does not match API route, expected aiSaid")
			}
			conv.ActiveTask = activeTask
		}
	} else if chatBody.WApi == "xObjSubmitReq" {
		if chatBody.Data.TaskID == "" {
			resByte, _ := json.Marshal(serializer.WsResponse("Task ID is missing for xObjSubmitReq", 1, "aiSaid", nil))
			conv.SendToClientChan <- resByte
			return errors.New("Missing task ID for xObjSubmitReq")
		}
		activeTask := task.GetTaskByID(chatBody.Data.TaskID)
		if activeTask.GetTaskType() != task.Question {
			resByte, _ := json.Marshal(serializer.WsResponse("Task ID does not match API route", 1, "aiSaid", nil))
			conv.SendToClientChan <- resByte
			return errors.New("Task ID does not match API route")
		}
		conv.ActiveTask = activeTask
	} else {
		resByte, _ := json.Marshal(serializer.WsResponse("Unknown API route", 1, "aiSaid", nil))
		conv.SendToClientChan <- resByte
		return errors.New("Unknown API route")
	}

	// Update the user's last message time
	conv.ActiveTask.UpdateTaskLastUserSaid()

	doneChan := make(chan string)

	// Run the task with the user's data
	go conv.ActiveTask.Run(doneChan, chatBody.Data)

	// Wait for the task to finish processing
	result := <-doneChan
	if result == "done" {
		// Task is done; switch to the next task
		conv.SwitchTask(useridObj)
	} else if result == "continue" {
		// The task continues; no action needed
		return nil
	} else {
		log.Println("Task failed due to:", result)
		resByte, _ := json.Marshal(serializer.WsResponse(result, 1, "aiSaid", nil))
		conv.SendToClientChan <- resByte
		return errors.New(result)
	}
	return nil
}
```
请你根据这里给出的代码，在不进行任何逻辑上的修改的情况下，帮我重构一下上面代码，让代码的功能实现更优雅