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

package uploadfilehander

import (
	"bytes"
	"io"
	"ipsomc/core/gin/resp"
	"ipsomc/module/upgrade"
	"ipsomc/module/uploadfile/uploadfileapi"
	"ipsomc/module/uploadfile/uploadfilemodel"
	"strconv"

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

type UploadFileHan struct {
	upgradeApi    upgrade.Upgrade
	uploadFileApi uploadfileapi.UploadFileApi
}

// 上传升级文件
func (obj *UploadFileHan) UploadUpgradeFileHan(c *gin.Context) {
	dataModel := new(uploadfilemodel.UploadFileParam)

	// 1、从上传文件中提取data参数（JSON字符串）
	projectIdStr := c.Request.FormValue("project_id") //项目编号
	btsIdStr := c.Request.FormValue("bts_id")         //基站编号
	ProjectID, _ := strconv.Atoi(projectIdStr)
	BtsID, _ := strconv.Atoi(btsIdStr)
	if ProjectID <= 0 || BtsID <= 0 {
		resp.RespFail(c, "升级参数有误")
		return
	}
	dataModel.ProjectID = ProjectID
	dataModel.BtsID = BtsID

	////2、从上传文件中提取文件
	file, err := c.FormFile("file")
	if err != nil {
		resp.RespFail(c, "提取数据错误")
		return
	}

	// 打开文件以读取其内容
	f, err := file.Open()
	if err != nil {
		resp.RespFail(c, "打开文件错误")
		return
	}
	defer f.Close()

	// 创建一个缓冲区来存储文件内容
	var buf bytes.Buffer
	_, err = io.Copy(&buf, f)
	if err != nil {
		resp.RespFail(c, "拷贝文件错误")
		return
	}

	fileLen := buf.Len()
	println(fileLen)

	//把数据送到升级模块
	if err := obj.upgradeApi.UpgradeReceiveFile(dataModel, buf.Bytes(), uint32(buf.Len())); err != nil {
		resp.RespFail(c, "远程升级失败")
	}

	resp.RespOk(c)
}

// 获得升级状态
func (obj *UploadFileHan) GetUpgradeStatusHan(c *gin.Context) {
	dataMode := new(uploadfilemodel.UploadFileResp)

	resp.RespData(c, dataMode)
}

// 创建web socket
func (obj *UploadFileHan) CreateWebSocketHan(c *gin.Context) {
	//创建web socket
	if err := obj.uploadFileApi.CreateWebSocketApi(c); err != nil {
		resp.RespFail(c, err.Error())
		return
	}

	//响应成功
	resp.RespOk(c)
}
