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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TAttaInfo;
import com.yifu.cloud.plus.v1.yifu.archives.service.TAttaInfoService;
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 com.yifu.cloud.plus.v1.yifu.common.core.vo.FileVo;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
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.time.LocalDateTime;
import java.util.List;

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

    @Autowired
    private OSSUtil ossUtil;

	@Autowired
	private TAttaInfoService tAttaInfoService;

	/**
	 * @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 = \"关系类型(0员工附件-学历 1 员工附件-伤残 2.员工附件-职业 )\", required = true, dataType = \"int\", paramType = \"form\"),\n" +
			"\t\t\t@ApiImplicitParam(name = \"domain\", value = \"实体id（传入就插入对应关系,用于编辑）\", required = false, paramType = \"form\")\n" +
			"\t")
	/*@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "Form文件上传", required = true, dataType = "__file", paramType = "form"),
			@ApiImplicitParam(name = "filePath", value = "文件上传路径", required = false, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "type", value = "关系类型(0客户附件1联系人附件2跟进记录附件3合同附件4合同归档附件5报价单6招标信息7业务评估)", required = true, dataType = "int", paramType = "form"),
			@ApiImplicitParam(name = "domain", value = "实体id（传入就插入对应关系,用于编辑）", required = false, paramType = "form")
	})*/
	@PostMapping(value = "/ossUploadFile")
	public R<FileVo> uploadImg(@RequestBody MultipartFile file, String filePath, Integer type, String domain) throws IOException {
		if (null == file) {
			return R.failed("文件删除异常，请重新上传！");
		}
		String fileName = file.getOriginalFilename();
		if (Common.isEmpty(fileName)) {
			return R.failed("文件名不能为空！");
		}
		if (fileName.length() > 100) {
			return R.failed("文件名不能超过100个字符！");
		}
		//filePath不传默认存储空间的根目录
		//jpg,jpeg,png,bmp
		String key = "";
		if (Common.isNotNull(filePath)) {
			key = filePath + "/" + System.currentTimeMillis() + fileName;
		} else {
			key = System.currentTimeMillis() + fileName;
		}
		if (!Common.checkFile(key)) {
			return R.failed("非法上传类型！");
		}
		boolean flag = ossUtil.uploadFileByStream(file.getInputStream(), key, null);
		FileVo fileVo;
		TAttaInfo attaInfo;
		URL url;
		if (flag) {
			log.info("文件：" + fileName + "上传至存储空间" + ossUtil.getBucketName() + "成功！");
			attaInfo = initUnitAttaForInsert(fileName, key, file.getSize());
			attaInfo.setRelationType(String.valueOf(type));
			try {
				attaInfo.setDomainId(domain);
				attaInfo = tAttaInfoService.add(attaInfo);
			} catch (Exception e) {
				log.error("OSS文件上传接口异常：" + e.getMessage());
				ossUtil.deleteObject(null, key);
				return R.failed("fail:" + e.getMessage());
			}
			//有实体id则插入关系，用于编辑
			if (Common.isNotNull(domain)) {
				url = ossUtil.getObjectUrl(null, attaInfo.getAttaSrc());
				fileVo = new FileVo(attaInfo.getId(), attaInfo.getAttaName(), url.toString());
				return R.ok(fileVo, "success");
			}
			url = ossUtil.getObjectUrl(null, attaInfo.getAttaSrc());
			fileVo = new FileVo(attaInfo.getId(), attaInfo.getAttaName(), url.toString());
			return R.ok(fileVo, "success");
		} else {
			return R.failed("fail:上传失败");
		}
	}


	/**
	 * @Author fxj
	 * @Description
	 * @Date 13:51 2022/6/17
	 * @Param
	 * @return
	**/
	@Operation(description = "附件删除")
	@SysLog("附件删除")
	@DeleteMapping("/ossFileDelete/{id}")
	public R<Boolean> ossFileDelete(@PathVariable String id) {
		try {
			TAttaInfo attaInfo = tAttaInfoService.getById(id);
			if (null == attaInfo) {
				return R.failed("无对应附件信息");
			}
			if (tAttaInfoService.removeById(id)) {
				ossUtil.deleteObject(null, attaInfo.getAttaSrc());
				return R.ok(null,"删除成功！");
			}

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


	/**
	 * 对象初始化
	 * @param fileName
	 * @param key
	 * @param fileSize
	 * @return
	 */
	private TAttaInfo initUnitAttaForInsert(String fileName, String key, long fileSize) {
		TAttaInfo unitAtta = new TAttaInfo();
		char slash = '/';
		char point = '.';
		if (fileName.lastIndexOf(slash) >= 0) {
			unitAtta.setAttaName(fileName.substring(fileName.lastIndexOf(slash)));
		} else {
			unitAtta.setAttaName(fileName);
		}
		unitAtta.setAttaSize(fileSize);
		unitAtta.setAttaSrc(key);
		if (key.lastIndexOf(point) >= 0) {
			unitAtta.setAttaType(key.substring(key.lastIndexOf(point)));
		}
		unitAtta.setCreateTime(LocalDateTime.now());
		return unitAtta;
	}

	/**
	 * 获取附件下载地址
	 *
	 * @param id
	 * @return
	 * @Author fxj
	 * @Date 2019-08-16
	 * @param id  domainId
	 **/
	@Operation(description = "附件预览下载地址 type:关系类型(0员工附件-学历 1 员工附件-伤残 2.员工附件-职业")
	@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 R.failed("无对应附件信息");
		}
		for (TAttaInfo  atta:attas){
			URL url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
			atta.setAttaUrl(url.toString());
		}
		return new R<>(attas);
	}
}
