package digital.laboratory.platform.imr.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.feign.RemoteWord2PDFService;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.common.oss.service.OssFile;
import digital.laboratory.platform.imr.dto.ApplyDTO;
import digital.laboratory.platform.imr.dto.QueryApplyDTO;
import digital.laboratory.platform.imr.dto.QueryDTO;
import digital.laboratory.platform.imr.entity.SampleApply;
import digital.laboratory.platform.imr.entity.SampleStorage;
import digital.laboratory.platform.imr.mapper.SampleApplyDetailedMapper;
import digital.laboratory.platform.imr.mapper.SampleStorageMapper;
import digital.laboratory.platform.imr.service.SampleApplyService;
import digital.laboratory.platform.imr.vo.ApplySampleVO;
import digital.laboratory.platform.imr.vo.BaseSampleVO;
import digital.laboratory.platform.imr.vo.SampleApplyVO;
import feign.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.Principal;
import java.util.*;

/**
 * 检材申请实体类
 *
 * @author Zhang Xiaolong created at  2023-03-17
 * @describe 检材申请实体类 前端控制器
 *
 * 这是与表示层的接口, 不应该接业务逻辑写在这里, 业务逻辑应该写在 service 中
 * 这里写什么:
 *     为前端提供数据, 接受前端的数据
 *     为前端提供的数据, 从 service 取得后, 可以做一些适当的加工, 这种加工不是业务层面的, 只能是数据格式上, 为方便前端处理
 *     接受前端的数据, 每一个函数的参数可以先做一些整理后, 再调用 service 中的函数。这里对参数的整理, 应该只是格式上的, 而不能是业务上的
 * 数据层在 mapper 中, 数据层不涉及业务, 只管技术上的 对象<->表 之间的转换
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/sample_apply" )
@Api(value = "sample_apply", tags = "检材申请管理--外带+销毁")
public class SampleApplyController {

    private final  SampleApplyService sampleApplyService;



	private final  OssFile ossFile;

	private final RemoteWord2PDFService remoteWord2PDFService;

	private final SampleStorageMapper storageMapper;


	/**
	 * 提供id查询申请详情
	 */
	@ApiOperation(value = "查询申请详情", notes = "查询申请详情")
	@SysLog("查询申请详情" )
	@GetMapping("/getDetail")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_get')" )
	public R<SampleApplyVO> getDetail(String id) {

		if(id==null){
			throw new RuntimeException("申请id不能为空");
		}

		SampleApplyVO sampleApply = sampleApplyService.getDetail(id);

		return R.ok(sampleApply);
	}

	@ApiOperation(value = "申请人查询销毁申请--分页", notes = "申请人查询申请--分页")
	@SysLog("申请人查询申请--分页" )
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('imr_sample_des_apply')" )
	public R<IPage<SampleApplyVO>> getApplyPage(QueryApplyDTO dto,HttpServletRequest theHttpServletRequest) {

		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		Page<SampleApply> page = new Page<>(dto.getCurrent(),dto.getSize());

		if(dto.getApplyType()==null){
			throw new RuntimeException(String.format("需要传递申请类型参数" ));
		}

		QueryWrapper<SampleApply> wrapper = new QueryWrapper<>();
		wrapper.eq("apply_type",dto.getApplyType());
		if(!dlpUser.getPermissions().contains("imr_inbound_or_outbound")){
			//如果不是检材管理员只能看见自己的
			wrapper.eq("applicant_id",dlpUser.getId());
		}
		wrapper.between(dto.getBeginDate()!=null && dto.getFinishDate()!=null,"application_date",dto.getBeginDate(),dto.getFinishDate());
		if(dto.getStatus()!=null){
			wrapper.eq("application_status",dto.getStatus());
		}else {
			wrapper.ne("application_status",4);
		}
		wrapper.orderByDesc("application_date");//申请时间排序

		IPage<SampleApplyVO> vo = sampleApplyService.getApplyPage(page,wrapper);

		return R.ok(vo,"查询成功");
	}




	@ApiOperation(value = "申请人查询外带申请--分页", notes = "申请人查询申请--分页")
	@SysLog("申请人查询申请--分页" )
	@GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('imr_sample_out_apply')" )
	public R<IPage<SampleApplyVO>> getApplyList(QueryApplyDTO dto,HttpServletRequest theHttpServletRequest) {

		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		Page<SampleApply> page = new Page<>(dto.getCurrent(),dto.getSize());

		if(dto.getApplyType()==null){
			throw new RuntimeException("需要传递申请类型参数");
		}

		QueryWrapper<SampleApply> wrapper = new QueryWrapper<>();
		wrapper.eq("apply_type",dto.getApplyType());
		wrapper.eq("applicant_id",dlpUser.getId());
		wrapper.between(dto.getBeginDate()!=null && dto.getFinishDate()!=null,"application_date",dto.getBeginDate(),dto.getFinishDate());
		if(dto.getStatus()!=null){
			wrapper.eq("application_status",dto.getStatus());
		}else {
			wrapper.ne("application_status",4);
		}
		wrapper.orderByDesc("application_date");//申请时间排序



		IPage<SampleApplyVO> vo = sampleApplyService.getApplyPage(page,wrapper);

		return R.ok(vo,"查询成功");
	}






	/**
	 * 创建并保存检材申请
	 * @param dto
	 * @return R
	 */
	@ApiOperation(value = "创建并保存检材申请", notes = "创建并保存检材申请")
	@SysLog("创建并保存检材申请" )
	@PostMapping("/createAndSave")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_add')" )
	public R<SampleApplyVO> createAndSave(@RequestBody ApplyDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		if(dto.getApplyType()==null){
			throw new RuntimeException("必须提供一个申请类型/外带/销毁");
		}
		if(dto.getSampleId()==null ||dto.getSampleId().size()==0){
			throw new RuntimeException("样本信息不能为空");
		}
		SampleApplyVO applyVO = null;
		if(dto.getId()==null||"".equals(dto.getId())) {
			applyVO = sampleApplyService.createAndSave(dto, dlpUser);
		}else {
			applyVO = sampleApplyService.updateAndSave(dto, dlpUser);
		}

		return R.ok(applyVO,"保存成功");

	}


	/**
	 * 根据当前持有人去查询数据
	 * 问题:1.创建完流转后当前持有人数据显示问题
	 *
	 * 设定查询有两个条件需要满
	 * 1.当前持有人id
	 * 2.当前的样本状态!=4;(不等于流转中)---这个是目前的想法
	 */
	@ApiOperation(value = "创建外带申请--根据当前持有人去查询数据", notes = "根据当前持有人去查询数据")
	@GetMapping("/getSampleInfoByHolder" )
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_get')" )
	public R<IPage<BaseSampleVO>> getSampleInfoByHolder(QueryDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		List<String> sampleIds = Arrays.asList(dto.getSampleIds().split(","));
		int size = sampleIds.size();
		if ("".equals(dto.getSampleIds())){
			size = sampleIds.size()-1;
		}


		if(dto.getTotal()!=0){
			int num = 0;//去重后目前能分的页数

			if((dto.getTotal()-size)%8==0){
				num = (dto.getTotal()-size)/8;
			}else {
				num = (dto.getTotal()-size)/8+1;
			}

			System.out.println(num);

			if(dto.getCurrent()>num){
				//求余数
				int a = dto.getTotal()%8;//求最后一页的剩余条数
				if(a==0){
					a=8;
					if(sampleIds.size()>=a){
						dto.setCurrent(num);
					}
				}else {
					if(sampleIds.size()>=a){
						dto.setCurrent(num);
					}
				}
			}
		}
		Page<SampleStorage> samplePage = new Page<>(dto.getCurrent(),dto.getSize());

		IPage<BaseSampleVO> sampleVOS = storageMapper.getSampleInfoByHolder(samplePage,Wrappers.<SampleStorage>query()
				.notIn(!sampleIds.isEmpty(),"s.id",sampleIds)//去重数组id
				.like(!dto.getName().isEmpty(),"s.name",dto.getName())
				.eq("s.holder",dlpUser.getId())
				.eq("s.status",1)//状态为出库
				.ne("s.status",12)//当前状态不等于申请中

		);
		return R.ok(sampleVOS,"查询成功");
	}



	/**
	 * 根据当前持有人去查询数据
	 * 问题:1.创建完流转后当前持有人数据显示问题
	 *
	 * 设定查询有两个条件需要满足
	 * 1.当前持有人id
	 * 2.当前的样本状态!=4;(不等于流转中)---这个是目前的想法
	 */
	@ApiOperation(value = "当前仓库库存样本--创建销毁申请", notes = "当前仓库库存样本--创建销毁申请")
	@GetMapping("/getSampleInfoByRepository" )
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_get')" )
	public R<IPage<BaseSampleVO>> getSampleInfoByRepository(QueryDTO dto) {

		List<String> sampleIds = Arrays.asList(dto.getSampleIds().split(","));
		int size = sampleIds.size();
		if ("".equals(dto.getSampleIds())){
			size = sampleIds.size()-1;
		}


		if(dto.getTotal()!=0){
			int num = 0;//去重后目前能分的页数

			if((dto.getTotal()-size)%8==0){
				num = (dto.getTotal()-size)/8;
			}else {
				num = (dto.getTotal()-size)/8+1;
			}

			System.out.println(num);

			if(dto.getCurrent()>num){
				//求余数
				int a = dto.getTotal()%8;//求最后一页的剩余条数
				if(a==0){
					a=8;
				}
				if(sampleIds.size()>=a){
					dto.setCurrent(num);
				}
			}
		}

		Page<SampleStorage> samplePage = new Page<>(dto.getCurrent(),dto.getSize());

		IPage<BaseSampleVO> sampleVOS = storageMapper.getDestructionSample(samplePage,Wrappers.<SampleStorage>query()
				.notIn(!sampleIds.isEmpty(),"storage.sample_id",sampleIds)//去重数组id
				.like(!dto.getName().isEmpty(),"storage.name",dto.getName())
				.eq("storage.status",2)//在仓库的
				.eq("storage.early_warning",1)//在仓库已经到销毁时间了的
				.ne("s.status",12 )//当前状态不等于申请中
				.ne("s.status",8)//该样本没有被销毁


		);
		return R.ok(sampleVOS,"查询成功");
	}



	/**
	 * 创建并提交检材申请(创建直接点提交)
	 * @param dto
	 * @return R
	 */
	@ApiOperation(value = "创建并提交检材申请", notes = "创建并提交检材申请")
	@SysLog("创建并提交检材申请" )
	@PostMapping("/createAndSubmit")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_add')" )
	public R<SampleApplyVO> createAndSubmit(@RequestBody ApplyDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		if (dto.getApplyType() == null) {
			throw new RuntimeException(String.format("必须提供一个申请类型/外带/销毁"));
		}
		if (dto.getSampleId().isEmpty()) {
			throw new RuntimeException(String.format("样本信息不能为空"));
		}
		if (dto.getSampleId().size() == 0) {
			throw new RuntimeException(String.format("样本信息不能为空"));
		}
		SampleApplyVO applyVO = null;
		if(dto.getId()==null||"".equals(dto.getId())) {
			applyVO = sampleApplyService.createAndSubmit(dto, dlpUser);
		}else {
			applyVO = sampleApplyService.updateAndSubmit(dto, dlpUser);
		}
		return R.ok(applyVO, "创建成功");
	}


		/**
		 *单个提交申请
		 */
	@ApiOperation(value = "单个提交申请", notes = "单个提交申请")
	@SysLog("单个提交申请" )
	@PutMapping("/submitApplyOne")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
	public R<SampleApplyVO> submitApplyOne(String id){

		if(id==null){
			throw new RuntimeException(String.format("id不能为空"));
		}
		SampleApplyVO vo =  sampleApplyService.submitApplyOne(id);

		return R.ok(vo, "提交成功");
	}

	/**
		 * 批量提交申请
	*/
	@ApiOperation(value = "批量提交申请", notes = "批量提交申请")
	@SysLog("批量提交申请" )
	@PutMapping("/submitApplyList")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
	public R submitApplyList(@RequestBody List<String> ids){
		if (ids.isEmpty()){
			throw new RuntimeException(String.format("请选择提交的申请" ));
		}
		for (String id : ids) {
			sampleApplyService.submitApplyOne(id);
		}
		return R.ok(null,"提交成功");
	}

	/**
		 * 单个撤回withdrawal
		 */

	@ApiOperation(value = "单个撤回", notes = "单个撤回")
	@SysLog("单个撤回" )
	@PutMapping("/withdrawalOne/{id}")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
	public R withdrawalOne(@PathVariable("id") String id){

		if(id==null){
			throw new RuntimeException(String.format("id不能为空"));
		}
		SampleApplyVO vo =  sampleApplyService.withdrawalOne(id);

		return R.ok(vo, "撤回成功");
	}

	/**
		 * 批量撤回
	*/
	@ApiOperation(value = "批量撤回", notes = "批量撤回")
	@SysLog("批量撤回" )
	@PutMapping("/withdrawalList")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
	public R withdrawalList(@RequestBody List<String> ids){

		if (ids.isEmpty()){
			throw new RuntimeException(String.format("请选择撤回的申请" ));
		}
		for (String id:ids) {
			sampleApplyService.withdrawalOne(id);
		}

		return R.ok(null,"撤回成功");

	}


	/**
		 * 单个删除
		 * @param id id
		 * @return R
	*/
	@ApiOperation(value = "单个删除", notes = "单个删除")
	@SysLog("通过id删除检材申请实体类" )
	@DeleteMapping("/deleteApplyOne/{id}" )
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_del')" )
	public R deleteApplyOne(@PathVariable("id") String id, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		if (id.isEmpty()){
			throw new RuntimeException(String.format("删除数据id不存在"));
		}

		sampleApplyService.deleteOne(id);

		return R.ok(null, "删除成功");
	}

	/**
		 * 批量删除
		 * @param ids
		 * @return R
		 */
	@ApiOperation(value = "批量删除", notes = "批量删除")
	@SysLog("批量删除" )
	@DeleteMapping("/deleteApplyList" )
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_del')" )
	public R deleteApplyList(@RequestBody List<String> ids, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();



		if(ids.isEmpty()){
			throw new RuntimeException(String.format("删除数据id不能为空"));
		}
		for (String id:ids) {
			sampleApplyService.deleteOne(id);
		}
		return R.ok(null, "对象删除成功");
	}

	/**
		 * 修改并提交检材申请实体类(修改的设定为直接提交)修改应该叫修改并提交
		 * 1.待提交
		 * 2.审核审批不通过状态?
		 *    2的情况比较特殊,这种已经审批过的修改应该是重新创建一条数据?
		 * @param dto 检材申请实体类
		 * @return R
		 */
    @ApiOperation(value = "修改并提交申请", notes = "修改并提交申请")
    @SysLog("修改检材申请实体类" )
    @PutMapping("/updateAndSubmit")
    @PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
    public R<SampleApplyVO> updateAndSubmit(@RequestBody ApplyDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		if (dto.getId()==null){
			throw new RuntimeException(String.format("申请id不能为空"));
		}

		if(dto.getSampleId().isEmpty()){
			throw new RuntimeException(String.format("选择样本不能为空"));
		}

		SampleApplyVO vo =  sampleApplyService.updateAndSubmit(dto,dlpUser);

		return R.ok(vo,"修改成功");

    }




	@ApiOperation(value = "修改并保存", notes = "修改并保存")
	@SysLog("修改并保存" )
	@PutMapping("/updateAndSave")
	@PreAuthorize("@pms.hasPermission('imr_sample_apply_edit')" )
	public R<SampleApplyVO> updateAndSave(@RequestBody ApplyDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		if (dto.getId()==null){
			throw new RuntimeException(String.format("申请id不能为空"));
		}

		if(dto.getSampleId().isEmpty()){
			throw new RuntimeException(String.format("选择样本不能为空"));
		}

		SampleApplyVO vo =  sampleApplyService.updateAndSave(dto,dlpUser);

		return R.ok(vo,"修改成功");
	}




	/**
	 * 下载鉴定委托书
	 *
	 * @param id
	 *
	 * @return
	 */
	@ApiOperation(value = "下载申请表格", notes = "下载申请表格。如果还没有创建, 立即创建: 根据鉴定申请信息内容的内容创建PDF格式的鉴定委托书, 并保存到 MinIO 存储中")
	@SysLog("创建鉴定委托书")
	@GetMapping("/print/apply")
//	@PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
	public void bizGetPDFSampleApplyTable(String id, HttpServletRequest theHttpServletRequest, HttpServletResponse httpServletResponse) {
		System.out.println("bizApplyWord.................");
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		//查询数据
		SampleApplyVO detail = sampleApplyService.getDetail(id);

		if (detail == null) {
			throw new RuntimeException(String.format("没有找到该申请"));
		}

		if (detail.getApplicationStatus().getStatus()!=4) {
			throw new RuntimeException("申请状态必须在[审批通过]之后才能打印申请表格");
		}

		/*if (!dlpUser.isStaff()) {
			if (!StrUtil.equalsIgnoreCase(ev.getClientOrgId(), dlpUser.getOrgId())) {
				throw new RuntimeException("您只能打印自己所在机构的委托");
			}
		}*/

		String applyFileName = "";

		if(detail.getApplyType()==1){//外带申请
			applyFileName = "携带毒品外出申请表-"+detail.getId();
			//String entrustmentLetterFileName = "鉴定委托书-" + ev.getEntrustmentNo();
		}else {
			applyFileName = "待销毁检材样本报批表-"+detail.getId();
		}
		String pdfFilePath = "document" + "/"+"application" + "/" + detail.getId() + "/" + applyFileName + ".pdf";
		try {
			if (!ossFile.objectExist(pdfFilePath)) {
				GenerateSampleApplyTablePDF(detail,theHttpServletRequest,httpServletResponse);
			}
			ossFile.fileGet(pdfFilePath, httpServletResponse.getOutputStream());
			httpServletResponse.setContentType(applyFileName);
		} catch (Exception e) {
			System.out.println(String.format("minioFile objectExist() Exception. %s", e.getLocalizedMessage()));
			e.printStackTrace();
		}
	}


	private void GenerateSampleApplyTablePDF(SampleApplyVO applyVO , HttpServletRequest theHttpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
		System.out.println("GenerateSampleApplyTablePDF.................");

		//try {
		//---------------
		// 构造对象 Map
		//Map<String, Object> dm = BeanMap.create(ev);    //ClassUtils.objectToMap(ev);
		//Map<String, Object> dm = ClassUtils.objectToMap(applyVO);

		Map<String, Object> dm = new HashMap<>();
		//dm.put("size", 1);//号
		dm.put("applicantName", applyVO.getApplicantName());//申请人
		dm.put("reason", applyVO.getReason());//原因
		dm.put("id", LocalDateTimeUtil.format(applyVO.getApplicationDate(), "yyyy"));//设置为年份
		dm.put("applicationDate", LocalDateTimeUtil.format(applyVO.getApplicationDate(), "yyyy年MM月dd日"));//申请时间
		if(applyVO.getApplyType()==1){
			dm.put("firstAuditorName",applyVO.getFirstAuditorName());//一级审核人
			dm.put("firstAuditDate",LocalDateTimeUtil.format(applyVO.getFirstAuditDate(), "yyyy年MM月dd日"));//一级时间
			dm.put("firstAuditOpinion",applyVO.getFirstAuditOpinion());//一级意见
			dm.put("secondaryAuditName",applyVO.getSecondaryAuditName());//二级人
			dm.put("secondaryAuditDate",LocalDateTimeUtil.format(applyVO.getSecondaryAuditDate(), "yyyy年MM月dd日"));//二级时间
			dm.put("secondaryAuditOpinion",applyVO.getSecondaryAuditOpinion());//二级意见
		}
		dm.put("approverName",applyVO.getApproverName());//审批人
		dm.put("approvalDate",LocalDateTimeUtil.format(applyVO.getApprovalDate(), "yyyy年MM月dd日"));//审批时间
		dm.put("approverOpinion",applyVO.getApproverOpinion());//审批意见
		dm.put("applyQuantity",applyVO.getApplyQuantity());//数量


		String str = "";

		List<String> sampleNos = new ArrayList<>();
		for (ApplySampleVO sampleVO  : applyVO.getSampleVO()) {
			if(sampleVO.getStatus()==1){
				str=str+sampleVO.getSampleNo()+"\n";
			}
		}

		dm.put("sampleNo",str);

		//-----------------------------
		// 生成 word 版本的 鉴定委托书

		String applyFileName = "";

		if (applyVO.getApplyType() == 1) {//外带申请
			applyFileName = "携带毒品外出申请表-" + applyVO.getId();
		} else {
			applyFileName = "待销毁检材样本报批表-" + applyVO.getId();
		}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
		if (applyVO.getApplyType() == 1) {//外带申请
			ossFile.fileGet("template" + "/" + "携带毒品外出申请表模板.docx", bos);
		} else {
			ossFile.fileGet("template" + "/" + "待销毁检材报批申请表模板.docx", bos);
		}
			byte[] templateArray = bos.toByteArray();
			ByteArrayInputStream bis = new ByteArrayInputStream(templateArray);
			bos.close();
			// 现在 bis 是模板的 InputStream
			ConfigureBuilder builder = Configure.builder().buildGramer("${", "}").useSpringEL(false);
			XWPFTemplate template = XWPFTemplate.compile(bis, builder.build()).render(dm);
			bis.close();

			ByteArrayOutputStream fosWord = new ByteArrayOutputStream();
			template.write(fosWord);
			template.close();

			//------------
			ByteArrayInputStream fisWord = new ByteArrayInputStream(fosWord.toByteArray());
			fosWord.close();

			//MockMultipartFile mockMultipartFile = new MockMultipartFile("file", entrustmentLetterFileName + ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", fisWord);
			MockMultipartFile mockMultipartFile = new MockMultipartFile("file", applyFileName + ".docx", "image/jpg", fisWord);
			Response response = remoteWord2PDFService.word2pdf(mockMultipartFile);
			fisWord.close();


			ByteArrayOutputStream outPDF = new ByteArrayOutputStream();
			IoUtil.copy(response.body().asInputStream(), outPDF, IoUtil.DEFAULT_MIDDLE_BUFFER_SIZE);
			ByteArrayInputStream isPDF = new ByteArrayInputStream(outPDF.toByteArray());
			outPDF.close();


			ossFile.fileSave("document" + "/" + "application" + "/" + applyVO.getId() + "/" + applyFileName + ".pdf", isPDF);
			isPDF.close();

			System.out.println("转换为 PDF 结束");

		}
}

