package com.yifu.cloud.plus.v1.business.controller.fileupload;

import com.yifu.cloud.plus.v1.business.entity.system.TBusAttaInfo;
import com.yifu.cloud.plus.v1.business.service.system.TBusAttaInfoService;
import com.yifu.cloud.plus.v1.business.vo.BusFileVo;
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 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.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

	 private final OSSUtil ossUtil;

	 private final TBusAttaInfoService busAttaInfoService;


     /**
      * 阿里云处理文件上传
      *
      * @param file     文件
      * @param filePath 如： import   或  import/test/test..../test
      * @return
      * @throws IOException
      */
	 // @ApiImplicitParam(name = "file", value = "Form文件上传", required = true, dataType = "__file", paramType = "form"),
	 // @ApiImplicitParam(name = "filePath", value = "文件上传路径", dataType = "String", paramType = "form"),
	 // @ApiImplicitParam(name = "type", value = "上传类型0结算单；1社保；2公积金；3代发工资；4餐补；5春节大礼包；6证件附件;7假勤信息附件8学信网证明", required = true, dataType = "int", paramType = "form"),
	 // @ApiImplicitParam(name = "domain", value = "实体id（传入就插入对应关系）", paramType = "form")
     @Operation(summary = "OSS文件上传接口", description = "上传文件并保持文件路径到数据库")
     @PostMapping(value = "/ossUploadFile")
     public R<BusFileVo> uploadFile(@RequestBody MultipartFile file, String filePath, Integer type, String domain) throws IOException {
          return busAttaInfoService.uploadFile(file, filePath, type, domain);
     }


     /**
      * 获取附件下载地址
      *
      * @param id
      * @return
      * @Author fxj
      * @Date 2019-08-16
      **/
     @Operation(summary = "附件预览下载地址")
     @GetMapping("/ossFileUrl/{id}")
     public R ossFileUrl(@PathVariable String id) {
          TBusAttaInfo busAtta = busAttaInfoService.getById(id);
          if (null == busAtta) {
               return R.failed("无对应附件信息");
          }
          URL url = ossUtil.getObjectUrl(null, busAtta.getAttaSrc());
          busAtta.setAttaSrc(url.toString());
          return new R<>(busAtta);
     }

	
	//             @ApiImplicitParam(name = "file", value = "Form文件上传", required = true, allowMultiple = true, dataType = "__file", paramType = "form"),
	//             @ApiImplicitParam(name = "filePath", value = "文件上传路径", required = false, dataType = "String", paramType = "form"),
	//             @ApiImplicitParam(name = "type",allowMultiple = true,  value = "上传类型0结算单；1社保；2公积金；3代发工资；4餐补；5春节大礼包；6证件附件;7假勤信息附件8学信网证明", required = true, dataType = "String", paramType = "form"),
	//             @ApiImplicitParam(name = "domain",allowMultiple = true,  value = "实体id（传入就插入对应关系）", paramType = "form")
	@Operation(summary = "OSS多文件上传接口", description = "上传文件并保持文件路径到数据库")
	@PostMapping(value = "/ossUploadFileMultipart", headers = "content-type=multipart/form-data")
	public R<List<R<BusFileVo>>> ossUploadFileMultipart(HttpServletRequest request,
														@RequestParam(value = "filePath", required = false) String filePath,
														@RequestParam(value = "type", required = true)String[] type,
														@RequestParam(value = "domain", required = true)String[] domain,
														@RequestParam(value = "file", required = true)MultipartFile[] file) throws IOException {
		if (Common.isEmpty(file) || Common.isEmpty(type) || Common.isEmpty(domain)){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		if (type.length != domain.length || type.length != file.length || domain.length != file.length){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		List<R<BusFileVo>> fileVos = new ArrayList<>();
		//filePath不传默认存储空间的根目录
		for (int i=0;i<file.length;i++) {
			fileVos.add(busAttaInfoService.uploadFile(file[i], filePath, Integer.parseInt(type[i]), domain[i]));
		}
		return R.ok(fileVos);

	}


     /**
      * 删除数据库记录和OSS文件
      *
      * @param id
      * @return
      * @Author fxj
      * @Date 2019-09-09
      **/
     @Operation(summary = "附件删除")
     @SysLog("附件删除")
     @GetMapping("/ossFileDelete/{id}")
     public R<Boolean> ossFileDelete(@PathVariable String id) {
          try {
               TBusAttaInfo busAtta = busAttaInfoService.getById(id);
               if (null == busAtta) {
                    return R.failed("无对应附件信息");
               }
               if (busAttaInfoService.removeById(id)) {
                    ossUtil.deleteObject(null, busAtta.getAttaSrc());
                    return R.ok();
               }
          } catch (Exception e) {
               log.error("附件删除异常：" + e.getMessage());
               return R.failed("附件删除异常！！");
          }
          return R.failed("删除失败！！");
     }

}
