package reporter

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"hnyfkj.com.cn/rtu/bxs-sy/baseapp"
	mcu "hnyfkj.com.cn/rtu/bxs-sy/mcu_ctrl_board"
	takephoto "hnyfkj.com.cn/rtu/bxs-sy/mvs_takephoto"
)

func LoopTakePhoto(ctx context.Context) {
	for {
		select {
		case <-mcu.Board.ReqTakePhoCh:
			TakePhotoAndUpToFtp(ctx)
		case <-ctx.Done():
			return
		}
	}
}

func TakePhotoAndUpToFtp(ctx context.Context) (string, error) {
	// 1, 开始执行拍照任务
	mcu.MCBSetCamStateBit(mcu.TakingPhoto)
	defer mcu.MCBSetCamStateBit(mcu.Idle)

	baseapp.Logger.Infof("[%s] 拍照中, 稍后...", MODULE_NAME)
	now := time.Now()
	imgFile := filepath.Join(baseapp.IMG_DIR, fmt.Sprintf("%s.jpg", now.Format("2006-01-02_15-04-05.000")))
	_, err := takephoto.TakePhoto(takephoto.IMG_TYPE_JPG, imgFile, 300 /*秒*/)
	if err != nil {
		baseapp.Logger.Errorf("[%s] 拍照失败: %v!!", MODULE_NAME, err)
		return "", err
	}
	elapsed := time.Since(now).Milliseconds()
	baseapp.Logger.Infof("[%s] 拍照完成, 输出到本地文件: %q, 用时: %d毫秒", MODULE_NAME, imgFile, elapsed)

	// 2, 上传照片到服务器
	fileUploader.uploadLock.Lock() // 上传锁定(多个上传任务并发时, 保证串行执行) 2025-10-17
	defer fileUploader.uploadLock.Unlock()

	mcu.MCBSetCamStateBit(mcu.PhotoUploading)
	now = time.Now()
	baseapp.Logger.Infof("[%s] 正在上传照片文件%q到服务器...", MODULE_NAME, imgFile)

	remoteFile, err := uploadFileToFtp(ctx, imgFile, CfgServers.Img2Ftp.Address, CfgServers.Img2Ftp.Username, CfgServers.Img2Ftp.Password, defaultUploadTimeout)
	if err != nil {
		baseapp.Logger.Errorf("[%s] 照片文件%q上传失败: %v!!", MODULE_NAME, imgFile, err)
	} else {
		os.Remove(imgFile)
		elapsed = time.Since(now).Milliseconds()
		baseapp.Logger.Infof("[%s] 照片文件上传成功, 用时: %d毫秒, 本地文件: %q已删除", MODULE_NAME, elapsed, imgFile)
	}

	return remoteFile, err
}
