package com.yifu.cloud.plus.v1.batch.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.batch.entity.TAttaInfo;
import com.yifu.cloud.plus.v1.batch.service.FileUploadService;
import com.yifu.cloud.plus.v1.batch.service.TAttaInfoService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fang
 * 文件上传接口
 */
@RestController
@RequestMapping("/fileUpload")
@Tag(name = "文件上传接口")
@Slf4j
public class FileUploadController {

    @Autowired
    private OSSUtil ossUtil;

	@Autowired
	private TAttaInfoService tAttaInfoService;

	@Autowired
	private FileUploadService fileUploadService;

	/**
	 * @Author fxj
	 * @Description
	 * @Date 13:49 2022/6/17
	 * @Param
	 * @return
	**/
	@Operation(description = "OSS文件上传接口" +
			"@ApiImplicitParam(name = \"file\", value = \"Form文件上传\", required = true, dataType = \"__file\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"filePath\", value = \"文件上传路径\", required = false, dataType = \"String\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"type\", value = \"关系类型 1 任务表附件 2 zip附件 3反馈表附件\", required = true, dataType = \"int\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"domain\", value = \"实体id（传入就插入对应关系,用于编辑）\", required = false, paramType = \"form\")\n" +
			"\t")
	@PostMapping(value = "/ossUploadFile")
	public R<T> uploadImg(@RequestBody MultipartFile file, String filePath, String type, String domain) throws IOException {
		return fileUploadService.uploadAsso(file,filePath,type,domain, CommonConstants.ZERO_STRING);
	}

	/**
	 * @Author hgw
	 * @Description 改编自ossUploadFile接口，改变了回传信息——专为预入职微信端使用——忽略了token，其余人慎用
	 * @Date 13:49 2022/6/17
	 * @Param relationTypeSub 预入职其他附件的子类型
	 * @return
	**/
	@Operation(description = "OSS文件上传接口" +
			"@ApiImplicitParam(name = \"file\", value = \"Form文件上传\", required = true, dataType = \"__file\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"filePath\", value = \"文件上传路径\", required = false, dataType = \"String\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"type\", value = \"关系类型 1 任务表附件 2 zip附件 3反馈表附件\", required = true, dataType = \"int\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"domain\", value = \"实体id（传入就插入对应关系,用于编辑）\", required = false, paramType = \"form\")\n" +
			"\t")
	@PostMapping(value = "/uploadFileReturnAtta")
	public R<T> uploadFileReturnAtta(@RequestBody MultipartFile file, String filePath, String type, String domainId) throws IOException {
		return fileUploadService.uploadAsso(file,filePath,type,domainId,CommonConstants.ONE_STRING);
	}

	/**
	 * @Author fxj
	 * @Description
	 * @Date 13:51 2022/6/17
	 * @Param
	 * @return
	**/
	@Operation(description = "附件删除")
	@PostMapping("/ossFileDelete/deleteByIds")
	public R<Boolean> ossFileDelete(@RequestBody List<String> Ids) {
		if (Common.isNotNull(Ids)) {
			try {
				for (String id : Ids) {
					TAttaInfo attaInfo = tAttaInfoService.getById(id);
					if (null == attaInfo) {
						return R.failed("无对应附件信息");
					}
					if (tAttaInfoService.removeById(id)) {
						ossUtil.deleteObject("yf-hr-efile-source", attaInfo.getAttaSrc());
						return R.ok(null, "删除成功！");
					}
				}

			} catch (Exception e) {
				log.error("附件删除异常：" + e.getMessage());
				return R.failed("附件删除异常！");
			}
		}
		return R.ok(null,"删除失败！");
	}

	/**
	 * 获取附件下载地址
	 *
	 * @param id
	 * @return
	 * @Author fxj
	 * @Date 2019-08-16
	 * @param id  domainId
	 **/
	@Operation(description = "附件预览下载地址 资源类型 0 存量 1 新签 2续签 3减员")
	@GetMapping("/ossFileUrl/{id}")
	public R<List<TAttaInfo>> ossFileUrl(@PathVariable String id) {
		List<TAttaInfo> attas = tAttaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId,id));
		if (Common.isEmpty(attas)) {
			return new R<>(attas);
		}
		for (TAttaInfo  atta:attas){
			URL url = ossUtil.getObjectUrl("yf-hr-efile-source", atta.getAttaSrc());
			atta.setAttaUrl(url.toString().replace("http","https"));
		}
		return new R<>(attas);
	}

	/**
	 * 获取附件下载地址
	 *
	 * @param id
	 * @return
	 * @Author fxj
	 * @Date 2019-08-16
	 * @param id  domainId
	 **/
	@Operation(description = "附件预览下载地址 根据ID和附件类型")
	@PostMapping("/overrideOssFileUrl")
	public R<List<TAttaInfo>> ossFileUrl(@RequestParam String id,@RequestParam String type) {
		List<TAttaInfo> attas = tAttaInfoService.list(Wrappers.<TAttaInfo>query().lambda()
				.eq(TAttaInfo::getDomainId,id)
				.eq(TAttaInfo::getRelationType,type));
		if (Common.isEmpty(attas)) {
			return new R<>(attas);
		}
		for (TAttaInfo atta:attas){
			URL url = ossUtil.getObjectUrl("yf-hr-efile-source", atta.getAttaSrc());
			atta.setAttaUrl(url.toString().replace("http","https"));
		}
		return new R<>(attas);
	}

	/**
	 * 电子档案单个新增-附件上传接口
	 * 前端先调用此接口上传文件到阿里云OSS，如果文件名重复则自动添加后缀
	 *
	 * @param file 文件
	 * @param filePath 文件路径
	 * @param type 关系类型 4 人员文件
	 * @return R<TAttaInfo> 返回附件信息，包含附件ID
	 * @Author huych
	 * @Date 2025-12-31
	 */
	@Operation(description = "电子档案单个新增-附件上传接口，上传文件到OSS并返回附件ID")
	@PostMapping(value = "/uploadArchiveFile")
	public R<TAttaInfo> uploadArchiveFile(@RequestBody MultipartFile file, String filePath, String type) throws IOException {
		if (file == null || file.isEmpty()) {
			return R.failed("文件不能为空");
		}

		String fileName = file.getOriginalFilename();
		if (fileName == null || Common.isEmpty(fileName)) {
			return R.failed("文件名不能为空");
		}

		if (fileName.length() > 100) {
			return R.failed("文件名不能超过100个字符");
		}

		// 默认关系类型为4（人员文件）
		if (Common.isEmpty(type)) {
			type = CommonConstants.FOUR_STRING;
		}

		// 构建OSS文件路径，如果文件名重复则添加后缀
		Map<String, String> keyMap = buildUniqueFilePath(filePath, fileName);
		String key = keyMap.get("key");
		fileName = keyMap.get("name");
		// 校验文件类型
		if (!Common.checkFile(key)) {
			return R.failed("非法上传类型：" + fileName);
		}

		try {
			// 上传文件到OSS
			boolean uploadSuccess = ossUtil.uploadFileByStream(file.getInputStream(), key, "yf-hr-efile-source");
			if (!uploadSuccess) {
				return R.failed("文件上传失败");
			}

			// 创建附件信息记录，domainId暂时为空，后续调用uploadSingleArchive接口时更新
			TAttaInfo attaInfo = new TAttaInfo();
			attaInfo.setAttaName(fileName);
			attaInfo.setAttaSrc(key);
			attaInfo.setAttaSize(file.getSize());

			// 提取文件扩展名
			int lastDotIndex = key.lastIndexOf('.');
			if (lastDotIndex >= 0) {
				attaInfo.setAttaType(key.substring(lastDotIndex));
			}

			attaInfo.setRelationType(type);
			attaInfo.setDomainId(CommonConstants.ZERO_STRING); // 临时设置为"0"，后续更新
			attaInfo.setTaskId(CommonConstants.ZERO_STRING);// 临时设置为"0"，后续更新
			attaInfo.setStatus(CommonConstants.ZERO_STRING); // 0可用

			// 保存附件信息到数据库
			tAttaInfoService.save(attaInfo);

			// 获取附件URL
			URL url = ossUtil.getObjectUrl("yf-hr-efile-source", attaInfo.getAttaSrc());
			attaInfo.setAttaUrl(url.toString().replace("http", "https"));

			return R.ok(attaInfo, "文件上传成功");

		} catch (Exception e) {
			log.error("附件上传异常：", e);
			// 上传失败，删除OSS文件
			try {
				ossUtil.deleteObject("yf-hr-efile-source", key);
			} catch (Exception ex) {
				log.error("删除OSS文件失败：", ex);
			}
			return R.failed("上传异常：" + e.getMessage());
		}
	}

	/**
	 * 构建唯一的文件路径，如果文件名重复则添加后缀
	 *
	 * @param filePath 文件路径
	 * @param fileName 文件名
	 * @return 唯一的文件路径
	 */
	private Map<String, String> buildUniqueFilePath(String filePath, String fileName) {

		Map<String, String> fileMap = new HashMap<>();
		// 检查文件是否存在
		if (!fileUploadService.checkFileExists(filePath+ "/" + fileName)) {
			fileMap.put("key",filePath+ "/" + fileName);
			fileMap.put("name",fileName);
			return fileMap;
		}

		// 文件存在，添加后缀
		int lastDotIndex = fileName.lastIndexOf('.');
		String nameWithoutExt;
		String extension;

		if (lastDotIndex > 0) {
			nameWithoutExt = fileName.substring(0, lastDotIndex);
			extension = fileName.substring(lastDotIndex);
		} else {
			nameWithoutExt = fileName;
			extension = "";
		}
		fileMap.put("key",filePath + "/" + nameWithoutExt + "_" + System.currentTimeMillis() + extension);
		fileMap.put("name",nameWithoutExt + "_" + System.currentTimeMillis() + extension);
		return fileMap;
	}
}
