package org.springblade.gateway.common_gateway.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.common_gateway.ocr.OCRType;
import org.springblade.gateway.common_gateway.ocr.builder.OcrBuilder;
import org.springblade.gateway.common_gateway.ocr.entity.OCRBankInfo;
import org.springblade.gateway.common_gateway.ocr.entity.OCRBizilicenseInfo;
import org.springblade.gateway.common_gateway.ocr.entity.OCRIdInfo;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * @author: lianghanqiang
 * @description: ocr
 * @since: 9/17/21 -- 3:18 PM
 */
@RestController
@RequestMapping("ocr")
@Api(tags = "OCR 识别")
@AllArgsConstructor
@Slf4j
public class OcrController {

	/**
	 * 对象存储构建类
	 */
	private final OssBuilder ossBuilder;

	/**
	 * OCR识别身份证
	 *
	 * @return*/
	@ApiOperation("OCR识别身份证")
	@PostMapping("idcard")
	public R<List<Object>> analysisIdcard(@RequestBody MultipartFile image){
		BladeFile bladeFile = uploadImage(image);
		OCRIdInfo ocrIdInfo = OcrBuilder.buildOcrTemplate(OCRType.WECHAT_SHOP).analysisIdcard(bladeFile.getLink());
		return R.data(Arrays.asList(ocrIdInfo,bladeFile));
	}

	/**
	 * OCR识别银行卡
	 * */
	@ApiOperation("OCR识别银行卡")
	@PostMapping("bank")
	public R<List<Object>> analysisBank(@RequestBody MultipartFile image){
		BladeFile bladeFile = uploadImage(image);
		OCRBankInfo ocrBankInfo = OcrBuilder.buildOcrTemplate(OCRType.WECHAT_SHOP).analysisBank(bladeFile.getLink());
		return R.data(Arrays.asList(ocrBankInfo,bladeFile));
	}

	/**
	 * OCR识别营业执照
	 * */
	@ApiOperation("OCR识别营业执照")
	@PostMapping("bizilicense")
	public R<List<Object>> analysisBizilicense(@RequestBody MultipartFile image){
		BladeFile bladeFile = uploadImage(image);
		OCRBizilicenseInfo ocrBizilicenseInfo = OcrBuilder.buildOcrTemplate(OCRType.WECHAT_SHOP).analysisBlizilicense(bladeFile.getLink());
		return R.data(Arrays.asList(ocrBizilicenseInfo,bladeFile));
	}


	/**
	 * 	上传图片
	 * */
	private BladeFile uploadImage(MultipartFile image){
		BladeFile bladeFile ;
		try{
			bladeFile = ossBuilder.template().putFile(image.getOriginalFilename(),image.getInputStream());
		}catch (Exception e){
			log.error(e.getMessage());
			throw new ServiceException("图片上传失败！:"+e.getMessage());
		}
		return bladeFile;
	}

}
