package dao

import (
	"iot_manager_service/app/file/model"
	"time"
)

// File 文件表
type File struct {
	ID            int        `gorm:"primary_key;type:int" json:"id"`                     //编号
	OriginalName  string     `gorm:"type:varchar(45)" json:"originalName"`               //文件原始名
	EncryptedName string     `gorm:"type:varchar(45)" json:"encryptedName"`              //文件加密名
	SavePath      string     `gorm:"type:varchar(191)" json:"savePath"`                  //保存路径
	CategoryName  string     `gorm:"type:varchar(12)" json:"categoryName"`               //文件类别名
	AuthId        string     `gorm:"type:varchar(12);default:'100'" json:"authId"`       //权限id
	SuffixName    string     `gorm:"type:varchar(12)" json:"suffixName"`                 //文件后缀名
	UploadTime    *time.Time `gorm:"column:upload_time;type:datetime" json:"uploadTime"` //上传时间
	Uploader      int        `gorm:"type:int" json:"uploader"`                           //上传者id
	IsShowed      int        `gorm:"type:int;default:0" json:"isShowed"`                 //是否展示 0=展示,1=不展示
	Icon          string     `gorm:"type:varchar(191)" json:"icon"`                      //文件图标
	Iv            string     `gorm:"type:varchar(191)" json:"iv"`                        //加密文件的偏向量
	IsDeleted     int        `gorm:"type:int;default:0" json:"isDeleted"`                //是否删除 0=未删除,1=删除
}

func (*File) TableName() string {
	return "file"
}

func (f *File) Create() error {
	//if !errors.Is(Db.Model(&f).Where("encrypted_name = ?", f.EncryptedName).First(&f).Error, gorm.ErrRecordNotFound) {
	//	return errors.New("该文件已存在")
	//}
	return Db.Model(&f).Save(&f).Error
}

func (f *File) GetSysUserFiles(uid int, search model.SearchSysUserFiles) (files []File, total int64, err error) {
	//var db *gorm.DB
	db := Db.Table("file").
		Select("file.id,file.*").
		Joins("left join user_file uf on uf.file_id = file.id").
		Where("uf.receiver = ? AND file.is_showed = 0 AND file.is_deleted = 0 AND uf.is_deleted = 0 AND uf.operation_status = '下发' OR uf.operation_status = '转发'", uid). // 根据upload_time字段降序排列
		Group("file.id")

	if search.OriginalName != "" {
		db.Where("original_name like ?", "%"+search.OriginalName+"%")
	}
	if search.SuffixName != "" {
		db.Where("suffix_name = ?", search.SuffixName)
	}
	if search.Sort == 0 {
		db.Order("upload_time DESC")
	} else {
		db.Order("upload_time ASC")
	}
	limit := search.PageSize
	offset := search.PageSize * (search.PageNO - 1)
	db.Count(&total)
	// 执行查询并检查错误
	err = db.Limit(limit).Offset(offset).Scan(&files).Error
	if err != nil {
		return nil, 0, err
	}
	return files, total, err
}

func (f *File) GetFileInfo(fileid, uid int) (model.RespFileInfo, error) {
	var result map[string]interface{}
	query := `SELECT file.original_name, file.auth_id, uf.effective_date FROM 
            file LEFT JOIN user_file uf ON uf.file_id = file.id WHERE uf.file_id = ?  
                        AND uf.receiver = ? ORDER BY uf.effective_date DESC LIMIT 1`
	Db.Raw(query, fileid, uid).Scan(&result)
	authId, _ := result["auth_id"].(string)
	originalName, _ := result["original_name"].(string)
	effectiveDate, _ := result["effective_date"].(time.Time)

	return model.RespFileInfo{AuthId: authId, OriginalName: originalName, EffectiveDate: effectiveDate}, nil
}

func (f *File) GetFile(id string) (*File, error) {
	err := Db.Model(&f).Where("id = ?", id).First(&f).Error
	return f, err
}

func (f *File) GetMyUploadFiles(id int) ([]File, error) {
	var files []File
	err := Db.Model(&f).Where("uploader = ? and is_deleted = 0", id).Order("upload_time desc").Find(&files).Error
	if err != nil {
		return nil, err
	}
	return files, err
}
