package system

import (
	"context"
	"encoding/json"
	"fmt"
	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"

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

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

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

func (l *SystemFileUploadLogic) SystemFileUpload(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	oss, err := svc.GetAliYunOssInstance()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	res, err := oss.Upload(file, fileHeader)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	resp := make(map[string]interface{})
	resByte, err := json.Marshal(res)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if err := json.Unmarshal(resByte, &resp); err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	resp["full_url"] = strings.TrimLeft(l.svcCtx.Config.AliYunOss.FileUrl, ",") + "/" + strings.TrimRight(res.Url, "/")
	return &types.Response{200, "", resp}, nil
}

func localFileUpload(l SystemFileUploadLogic, r *http.Request) (*types.Response, error) {
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	dir := "asserts/avatar"
	_, err = os.Stat(dir)
	if err != nil && !os.IsExist(err) {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			logx.Error(err.Error())
			return &types.Response{500, err.Error(), nil}, nil
		}
	}
	fileName := fmt.Sprintf("%s/%d%s", dir, userId, filepath.Ext(fileHeader.Filename))
	newFile, err := os.OpenFile(fileName, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0777)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	_, err = io.Copy(newFile, file)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	return &types.Response{200, "", fileName}, nil
}
