package system

import (
	"context"
	"git.i2edu.net/i2/i2-bill-api/model"
	"io"
	"net/http"
	"strconv"

	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"

	"git.i2edu.net/i2/go-zero/core/logx"
)

type SystemFileDownloadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSystemFileDownloadLogic(ctx context.Context, svcCtx *svc.ServiceContext) SystemFileDownloadLogic {
	return SystemFileDownloadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemFileDownloadLogic) SystemFileDownload(w http.ResponseWriter, r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	r.ParseForm()
	id := r.FormValue("id")
	attachment := new(model.I2billSysAttachment)
	_, err := l.svcCtx.DB.ID(id).Get(attachment)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if attachment.Id == "" {
		return &types.Response{200, "", nil}, nil
	}
	oss, err := svc.GetAliYunOssInstance()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	f, err := oss.Download(attachment)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	w.Header().Set("Content-Disposition", "attachment;filename=\""+attachment.Name+"\"")
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Length", strconv.FormatInt(int64(attachment.Size), 10))
	w.WriteHeader(200)
	io.Copy(w, f)
	return nil, nil
}
