import { ResultVo } from '@/model/vo';
import { HPSFIR_CONTROLLER_METHOD_E, Controller, RequestMapping, HpsfirControllerFile, InFile, HpsfirControllerError } from 'hpsfir-controller';
import { AutoWrite } from 'hpsfir-ioc';
import { Log, Logger } from 'hpsfir-log';
import path from 'path';
import fs from 'fs';
import { BaseSnowflakeService } from 'hpsfir-managebase';

@Controller('/upload', { tag: { name: 'Upload', description: '上传' } })
export class UploadController {


  @Log(Symbol(UploadController.name))
  private logger!: Logger;

  @AutoWrite()
  private baseSnowflakeService!: BaseSnowflakeService;


  @RequestMapping('/file', {
    title: '上传文件',
    description: '上传文件',
    method: HPSFIR_CONTROLLER_METHOD_E.POST,
  })
  async files(@InFile() files: HpsfirControllerFile[]): Promise<ResultVo<string[]>> {
    try {
      const urls: string[] = [];
      for (const file of files) {
        const filenameSplit = file.originalFilename?.split('.') || [];
        const suffix = filenameSplit.length >= 2 ? `.${filenameSplit[filenameSplit.length - 1]}` : '';
        const relativePublic = path.posix.join('/upload', `${this.baseSnowflakeService.generateId()}${suffix}`);
        const url = relativePublic;
        await fs.promises.copyFile(file.filepath, path.join(process.env.RESOURCE_PATH!, '/public', relativePublic));
        await fs.promises.unlink(file.filepath);
        urls.push(url);
      }
      return new ResultVo(true, '上传成功', urls);
    } catch (error) {
      if (error instanceof HpsfirControllerError) {
        throw error;
      }
      this.logger.error('上传文件失败', error);
      const err = new HpsfirControllerError(500);
      throw err;
    }
  }


}
