package service

import (
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"iot_manager_service/app/file/dao"
	"iot_manager_service/app/file/model"
	userdao "iot_manager_service/app/user/dao"
	"iot_manager_service/util/common"
	"iot_manager_service/util/websocket"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

// 用户管理服务
var FileService = new(fileService)

type fileService struct{}

func (f *fileService) Upload(file dao.File) *common.Errors {
	err := file.Create()
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return common.SuccessResponse("上传成功", nil)

}

func (f *fileService) Distribute(requserfile *model.ReqSysUserFile, uid int) *common.Errors {
	//查询部门下对应的员工
	user := &userdao.SysUser{}
	users, err := user.GetDeptsSysUsers(requserfile.Depts)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	var userfile []dao.SysUserFile
	for _, u := range users {
		userfile = append(userfile, dao.SysUserFile{
			Operator:        uid,
			Receiver:        u.ID,
			FileID:          requserfile.ID,
			EffectiveDate:   requserfile.EfectiveDate,
			OperationStatus: "下发",
		})
	}
	userfiledao := &dao.SysUserFile{}
	err = userfiledao.BatchUFRecords(userfile)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	//下发消息
	for _, u := range users {
		websocket.SendMessage(strconv.Itoa(u.ID), "您有新的文件，请注意查收！")
	}
	return common.SuccessResponse("新增记录成功", nil)
}

func (f *fileService) GetSysUserFiles(id string, search model.SearchSysUserFiles) *common.Errors {
	filedao := &dao.File{}
	uid, _ := strconv.Atoi(id)
	files, total, err := filedao.GetSysUserFiles(uid, search)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return common.SuccessResponse("查询成功", gin.H{"files": files, "total": total})
}

func (f *fileService) GetFile(id string, c *gin.Context) {
	filedao := &dao.File{}
	file, err := filedao.GetFile(id)
	if err != nil {
		panic(err.Error())
	}
	currentDir, _ := os.Getwd()
	parentDir := filepath.Dir(currentDir)
	encryptedData, err := ioutil.ReadFile(parentDir + file.SavePath)
	if err != nil {
		panic(err.Error())
	}
	c.Data(http.StatusOK, "application/octet-stream", encryptedData)
}
func (f *fileService) GetMyUploadFiles(id string) *common.Errors {
	num, _ := strconv.Atoi(id)
	filedao := &dao.File{}
	files, err := filedao.GetMyUploadFiles(num)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return common.SuccessResponse("查询成功", gin.H{"MyUploadFiles": files})

}

// 转发
func (f *fileService) ForwardingFile(uid int, filesid []int, users []int) *common.Errors {
	var userfile []dao.SysUserFile
	currentTime := time.Now()
	//对于转发的文件，三天后过期
	after := currentTime.AddDate(0, 0, 3)
	for _, fid := range filesid {
		for _, u := range users {
			userfile = append(userfile, dao.SysUserFile{
				Operator:        uid,
				Receiver:        u,
				FileID:          fid,
				EffectiveDate:   &after,
				OperationStatus: "转发",
			})
		}
	}
	userfiledao := &dao.SysUserFile{}
	err := userfiledao.BatchUFRecords(userfile)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	for _, u := range users {
		websocket.SendMessage(strconv.Itoa(u), "您有新的文件，请注意查收！")
	}
	return common.SuccessResponse("新增记录成功", nil)
}
