// 文件上传模块
// 秒寻科技
// zt 2024-11-14

package uploadfileapi

import (
	"errors"
	"fmt"
	"ipsomc/public"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// 创建一个websocket实例
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type UploadFileApi struct {
}

// 创建web socket
func (obj *UploadFileApi) CreateWebSocketApi(c *gin.Context) error {
	//将HTTP连接转换成到WebSocket 连接
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return err
	}
	//defer ws.Close()

	// // 启动一个 goroutine 来从通道中读取消息并发送给客户端
	// go func() {
	// 	for {
	// 		//读消息
	// 		if _, _, err := ws.ReadMessage(); err != nil {
	// 			fmt.Println("websocket closed:", err)
	// 			return
	// 		}

	// 		//监听消息通道
	// 		msg, ok := <-public.Gpub_chanWebSocketMsg
	// 		if !ok {
	// 			// 通道已关闭，退出循环
	// 			return
	// 		}

	// 		// 准备要发送的消息
	// 		var response []byte
	// 		if msg.Flag == 2 {
	// 			response = []byte(strconv.Itoa(int(msg.Percent)))
	// 		} else {
	// 			response = []byte("升级失败")
	// 		}

	// 		// 尝试发送消息到客户端
	// 		if err := ws.WriteMessage(websocket.TextMessage, response); err != nil {
	// 			fmt.Println("WriteMessage error:", err)
	// 			return
	// 		}
	// 	}
	// }()

	//发送消息到客户端
	go obj.SendMsgToClient(ws)

	return nil
}

// 发消息给客户端
func (obj *UploadFileApi) SendMsgToClient(ws *websocket.Conn) error {
	var errMsg string = ""
	var flag uint8 = 0
	var exitLoop bool = false

	for {
		//监听消息通道
		select {
		case msg, ok := <-public.Gpub_chanWebSocketMsg:
			if !ok { // 通道已关闭，退出循环
				fmt.Println("通道已关闭")
				errMsg = "通道已关闭"
				exitLoop = true
			}

			// 准备要发送的消息
			var response []byte
			if msg.Flag == 2 {
				response = []byte(strconv.Itoa(int(msg.Percent)))
			} else {
				response = []byte("升级失败")
			}

			// 尝试发送消息到客户端
			if err := ws.WriteMessage(websocket.TextMessage, response); err != nil {
				fmt.Println("WriteMessage error:", err)
				errMsg = "WriteMessage error"
				exitLoop = true
			}

			//升级成功
			if msg.Percent >= 100 {
				flag = 1
				exitLoop = true
			}

			println(msg.Percent)
		case <-time.After(3 * time.Minute): // 超时
			fmt.Println("超时")
			errMsg = "超时"
			exitLoop = true
		}

		//退出循环
		if exitLoop {
			break
		}
	}

	if flag == 1 {
		ws.Close()
		return nil
	} else {
		ws.Close()
		return errors.New(errMsg)
	}
}
