/*
 *
 *      Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: hnqz
 *
 */

package com.qunzhixinxi.hnqz.admin.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.config.UpmsConfig;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.enums.PackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.mapper.WmImportUserMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskContentMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.admin.util.ExportReport;
import com.qunzhixinxi.hnqz.admin.util.Html2ImageByJsWrapper;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * <p>
 * 报告管理 服务实现类
 * </p>
 *
 * @author hnqz
 * @since 2018-01-20
 */
@Service
@AllArgsConstructor
public class ReportExportServiceImpl implements ReportExportService {

	private final WmTaskService wmTaskService;

	private final WmScorePackageService wmScorePackageService;

	private final WmScorePackageStatusService wmScorePackageStatusService;

	private final SysDeptService sysDeptService;

	private final SysUserService sysUserService;

	private final WmDaDrugEntService wmDaDrugEntService;

	private final WmTaskTypeService wmTaskTypeService;

	private final WmTaskRuleService wmTaskRuleService;

	private final WmDaAgentService wmDaAgentService;

	private final WmTaskContentService wmTaskContentService;

	private final WmTaskContentConfigService wmTaskContentConfigService;

	private final SysFileService sysFileService;

	private final WmReportService wmReportService;

	private final UpmsConfig upmsConfig;

	private final WmImportUserMapper wmImportUserMapper;

	private final WmTaskContentMapper wmTaskContentMapper;

	/**
	 * 个人报告导出--分页查询
	 * @param page
	 * @param wmScorePackage
	 * @return
	 */
	public R getExportPackageZbTotalList(Page page, WmScorePackage wmScorePackage) {
		//SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		wmScorePackage.setSendPackageDeptId(SecurityUtils.getUser().getDeptId()+"");
		wmScorePackage.setTypeid("4");
		IPage pageAnswer = wmScorePackageService.getExportPackageTotalList1(page, wmScorePackage);
		return R.ok(pageAnswer);
	}

	/**
	 * 个人报告导出--查看任务列表
	 * @param page
	 * @param wmTask
	 * @return
	 */
	@Override
	public R getExportPackageZbTaskList(Page page, WmTask wmTask) {
		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper<>();
		queryWrapper.eq(WmTask::getScorePackageId,wmTask.getScorePackageId());
		queryWrapper.eq(WmTask::getTaskStatus,"3");
		IPage pages =wmTaskService.page(page,queryWrapper);
		return R.ok(pages);
	}

	/**
	 * 结算报告--导出汇总报告--学术推广服务报告
	 * @param wmTask
	 * @param wmReport
	 * @return
	 * @throws IOException
	 */
	public R exportNb(WmTask wmTask, WmReport wmReport) throws IOException {

		WmTask wmTaskparam=wmTask;
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}

		List<String> list = new ArrayList<>();
		list.add(packageId);

		wmTask.setExtIds(list);

		Map<String, Object> excelMap = new HashMap<>();

		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		if (null == wmScorePackage) {
			return R.failed("获取积分包失败");
		}

		excelMap.put("totalscorePackageScore", wmScorePackage.getScore());
		if(wmScorePackage.getPackageType1().equals("2")||wmScorePackage.getPackageType1().equals("3")){
			excelMap.put("totalscorePackageTaskNum", wmScorePackage.getTaskNum()*wmScorePackage.getUserNum());//积分包值任务个数
		}


		List<Map<String, Object>> wmTaskList = wmTaskService.getTaskListByIds(wmTask);


		List<XlsTask> xlsTaskList = new ArrayList<>();//mxTable
		Integer totalMoney = 0;
//		wmTask.setScorePackageId(null);
//		wmTask.setScorePackageDrugId(null);

		//当前登陆人的机构
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		Map<String, Object> userMap = new HashMap<>();

		//委托公司（结算企业）
		SysDept drugEnt=sysDeptService.getById(wmReport.getDrugEntId());
		//WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(SecurityUtils.getUser().getDrugEntId());

		//报告公司（申请结算企业）
		SysDept applydrugEnt=sysDeptService.getById(wmReport.getApplyDrugEntId());
		//WmDaAgent wmDaAgent = wmDaAgentService.getById(wmScorePackage.getLevel1Id());

		for (Map<String, Object> wmT : wmTaskList) {
			totalMoney += Integer.parseInt(wmT.get("score") + "");
			XlsTask xlsTask = new XlsTask();
			xlsTask.setTaskNum(1);
			xlsTask.setCreateTime(wmT.get("create_time") + "");

			xlsTask.setDeptName(sysDept.getName());

			//level=2是药企
			if (sysDept.getLevel() == 2) {
				xlsTask.setAgentDeptName(applydrugEnt.getName());
			}

			xlsTask.setDrugEntName(drugEnt.getName());


			xlsTask.setScore(Integer.parseInt(wmT.get("score") + ""));

			xlsTask.setUsername(wmT.get("realname") + "");
			xlsTask.setTaskType(wmT.get("base_id") + "");

			xlsTaskList.add(xlsTask);

			String buildKey = wmT.get("realname") + "_" + drugEnt.getName() + "_" + sysDept.getName();
			//人员表格
			if (userMap.containsKey(buildKey)) {
				try {
					userMap.put(buildKey, Integer.parseInt(wmT.get("score") + "") + Integer.parseInt(userMap.get(buildKey) + ""));
					userMap.put(buildKey + "_total", Integer.parseInt(wmT.get("score_count") + "") + Integer.parseInt(userMap.get(buildKey + "_total") + ""));

				} catch (Exception ex) {
				}
			} else {
				userMap.put(buildKey, Integer.parseInt(wmT.get("score") + ""));
				userMap.put(buildKey + "_total", Integer.parseInt(wmT.get("score_count") + ""));
			}
		}

//		List<String> list1 = new ArrayList<>();
//		list1.add(packageId);

		//学术推广服务任务明细表格
		List<WmTask> wmTaskDetialList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
		List<Map<String, Object>> wmTaskDetialMap = new ArrayList<>();

		if (wmTaskDetialList.size() > 0) {
			for (WmTask wmTask1 :
					wmTaskDetialList) {
				Map<String, Object> map = new HashMap<>();
				WmTaskType wmTaskTypeTemp1 = wmTaskTypeService.getById(wmTask1.getTaskTypeId());
				map.put("taskType", wmTaskTypeTemp1.getTaskTypeName());
				DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String strDate2 = dtf2.format(wmTask1.getCreateTime());
				map.put("taskTime", strDate2);
//				map.put("taskUser", sysUserService.getById(wmTask1.getTaskUserId()).getRealname());
				map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
				map.put("taskTypeId", wmTask1.getTaskTypeId());
				map.put("score", wmTask1.getScore());
				map.put("taskNum", 1);

				wmTaskDetialMap.add(map);
			}

		}

		excelMap.put("rwmxTable", wmTaskDetialMap);//学术推广服务任务明细表格

		if (totalMoney > wmScorePackage.getScore()) {
			totalMoney = wmScorePackage.getScore();
		}

		excelMap.put("ryTable", userMap);//人员表格
		excelMap.put("tMoney", totalMoney);

		if (xlsTaskList.size() > 0) {
			excelMap.put("wt_ent", xlsTaskList.get(0).getDrugEntName());//委托公司
			excelMap.put("drugEnt", xlsTaskList.get(0).getDrugEntName());//服务药企
			excelMap.put("mxTable", xlsTaskList);
		}

		List<Map<String, String>> ztTableList = new ArrayList<>();
		Map<String, String> ztMap = new HashMap<>();
		List<Map<String, Object>> wmTaskCount = wmTaskService.getTaskListByIdsCount(wmTask);
		if (wmTaskCount.size() > 0) {
			Integer total = 0;
			Integer sum = 0;
			for (Map<String, Object> map :
					wmTaskCount) {
				if (null != map.get("taskCount")) {
					total += Integer.parseInt(map.get("taskCount") + "");
				}

				if (null != map.get("taskSum")) {
					sum += Integer.parseInt(map.get("taskSum") + "");
				}

			}
			Map<String, Object> totalMap = new HashMap<>();
			totalMap.put("taskTypeName", "合计");
			totalMap.put("taskCount", total);
			totalMap.put("taskSum", sum);
			wmTaskCount.add(totalMap);

			excelMap.put("totalSubmitScore", sum);
			excelMap.put("totalSubmitTaskNum", total);

			excelMap.put("ztTable", wmTaskCount);//学术推广服务整体概况表格
		}

		//WmTaskRule wmTaskRule = wmTaskRuleService.getById(wmScorePackage.getTaskRuleId());
		String entDate = wmScorePackage.getBelongDate() + "-31";
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			format.parse(entDate);
		} catch (Exception ex) {
			entDate = wmScorePackage.getBelongDate() + "-30";
		}
		//excelMap.put("service_date", wmTaskRule.getRuleMonth() + "-01 至 " + entDate);

		List<Map<String, Object>> wmTaskZd = wmTaskService.getTaskListByIdsZd(wmTask);
		String minDateStr = null;
		String maxDateStr = null;
		if (null != wmTaskZd) {
			if (wmTaskZd.size() > 0) {
				Map<String, Object> stringMap = wmTaskZd.get(0);
				if (null == stringMap) {
					return R.failed("未找到审核通过的任务");
				}
				excelMap.put("service_date", stringMap.get("mindate") + "至" + stringMap.get("maxdate"));

				try {
					minDateStr = stringMap.get("mindate").toString().substring(5, 7);
					maxDateStr = stringMap.get("maxdate").toString().substring(5, 7);

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		if (null != applydrugEnt) {
			excelMap.put("report_ent", applydrugEnt.getName());
		} else {
			excelMap.put("report_ent", "");
		}


		String ruleDate = wmScorePackage.getBelongDate();

		excelMap.put("rule_year", ruleDate.substring(0, 4));

		String monthStr = ruleDate.substring(5, 7);
		if (null != minDateStr && null != maxDateStr) {
			if (minDateStr.equals(maxDateStr)) {
				monthStr = minDateStr;
			} else {
				monthStr = minDateStr + "月至" + maxDateStr;
			}
		} else if (null != minDateStr) {
			monthStr = minDateStr;
		} else if (null != maxDateStr) {
			monthStr = maxDateStr;
		}

		excelMap.put("rule_month", monthStr);

		//报告日期
		Map<String, Timestamp> maxMaxTime=wmTaskService.getMaxCreateTime(wmTask);
		System.out.println(maxMaxTime);
		LocalDateTime MaxTime = maxMaxTime.get("MaxTime").toLocalDateTime();
		excelMap.put("year", MaxTime.getYear() + "");
		Integer month =MaxTime.getMonthValue() ;
		if (month < 10) {
			excelMap.put("month", "0" + MaxTime.getMonthValue() + "");
		} else {
			excelMap.put("month", MaxTime.getMonthValue() + "");
		}
		Integer day = MaxTime.getDayOfMonth();
		if (day < 10) {
			excelMap.put("day", "0" + MaxTime.getDayOfMonth() + "");
		} else {
			excelMap.put("day", MaxTime.getDayOfMonth() + "");
		}

		excelMap.put("tMoney", totalMoney);
		excelMap.put("scoreId", wmScorePackage.getScorePackageName());

		List<Map<String, Object>> infoList=exportZbInfo(wmTaskparam);
		if(null!=infoList&&infoList.size()>0){
			excelMap.put("infoList", infoList);
		}else {
			return R.failed("未查询到审核通过的任务");
		}
		//区分全职兼职学术推广员模版
		excelMap.put("userType",wmScorePackage.getTypeid());

		File f =null;
		if(wmScorePackage.getPackageType1().equals("1")){//定额
			 f = ExportReport.main_bulidTemplate1(excelMap, 1,upmsConfig.getBasePath());
		}else {//定量
			 f = ExportReport.main_bulidTemplate2(excelMap, 1,upmsConfig.getBasePath());
		}

		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile("学术推广服务报告(" + packageId + ")", "学术推广服务报告(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}



	/**
	 * 结算报告--导出报告详情
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	public List<Map<String, Object>> exportNbInfo(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID

		if (null == packageId) {
			return null;
		}

		List<Map<String, Object>> infoList = new ArrayList<>();

		List<String> list = new ArrayList<>();
		list.add(packageId);

		wmTask.setExtIds(list);

		Map<String, Object> excelMap = new HashMap<>();

		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		if (null == wmScorePackage) {
			return null;
		}

		List<WmTask> wmTaskList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
		if (wmTaskList.size() > 0) {
			List<String> integerList = new ArrayList<>();
			integerList.add("1");
			integerList.add(2 + "");
			integerList.add(3 + "");
			integerList.add(4 + "");
			integerList.add(5 + "");
			integerList.add(12 + "");
			integerList.add(13 + "");
			integerList.add(14 + "");
			integerList.add(15 + "");
			integerList.add(16 + "");
			integerList.add(17 + "");
			integerList.add(18 + "");

			Integer num = 1;
			for (WmTask wmTask1 : wmTaskList) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Map<String, Object> map = new HashMap<>();
				WmTaskType wmTaskTypeTemp1 = wmTaskTypeService.getById(wmTask1.getTaskTypeId());
				map.put("taskIndex", num++);
				map.put("taskType", wmTaskTypeTemp1.getTaskTypeName());
				DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String strDate2 = dtf2.format(wmTask1.getCreateTime());
				map.put("taskTime", strDate2);
				map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
				map.put("taskTypeId", wmTask1.getTaskTypeId());
				map.put("imgWidth", wmTaskTypeTemp1.getUpdateUser());
				map.put("imgHeight", wmTaskTypeTemp1.getCreateUser());

				if (null != wmTask1.getTaskInfoImg()) {
					map.put("taskBaseImg", wmTask1.getTaskInfoImg());
				} else {
					map.put("taskBaseImg", Html2ImageByJsWrapper.renderHtml2Image(upmsConfig.getApiUrl()
							+ "/h5/#/pages/task/task-detail/index?id=" + wmTask1.getId(), upmsConfig.getServerUrl()));
				}
				if (integerList.contains(wmTask1.getTaskTypeId())) {
					WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask1.getTaskContentId());
					if (null != wmTaskContent) {
						List<String> stringList = new ArrayList<>();
						WmTaskContentConfig queryWmTaskContentConfig = new WmTaskContentConfig();
						queryWmTaskContentConfig.setTaskTypeId(wmTask1.getTaskTypeId());
						queryWmTaskContentConfig.setTaskFiledType("img");
						List<WmTaskContentConfig> wmTaskContentConfigList = wmTaskContentConfigService.list(Wrappers.query(queryWmTaskContentConfig));
						if (wmTaskContentConfigList.size() > 0) {
							for (WmTaskContentConfig wmt : wmTaskContentConfigList) {
								String fileName = wmt.getTaskFiledKey();
								String imgList = getFieldValueByFieldName(fileName, wmTaskContent);
								Collections.addAll(stringList, imgList.split(","));
							}
						}

						if (stringList.size() > 0) {
							map.put("imgList", stringList);
						}

					}
				}

				infoList.add(map);
			}


		}


		return infoList;
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//		File f = ExportReport.main_bulidTemplate2(infoList, upmsConfig.getBasePath());
//		FileInputStream input = new FileInputStream(f);
//
//		MultipartFile multipartFile = new MockMultipartFile("学术推广服务任务明细(" + packageId + ")", "学术推广服务任务明细(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
//		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}

	public String getFieldValueByFieldName(String fieldName, Object object) {
		try {
			Field field = object.getClass().getDeclaredField(fieldName);
			//对private的属性的访问
			field.setAccessible(true);
			return field.get(object) + "";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 患者教育报告
	 * @param packageId
	 * @return
	 * @throws IOException
	 */
	@Override
	public R exportHCP(String packageId) throws IOException {
		WmScorePackage queryScorePackage = new WmScorePackage();
		queryScorePackage.setId(packageId);
		WmScorePackage scorePackage = wmScorePackageService.getById(packageId);
		if (scorePackage == null) {
			return R.failed("没有这个积分包");
		}
		// 查询接单人
		WmScorePackageStatus queryScorePackageStatus = new WmScorePackageStatus();
		queryScorePackageStatus.setPackageId(packageId);
		queryScorePackageStatus.setStatus(PackageStatusEnum.APPROVED.val());
		List<WmScorePackageStatus> staList = wmScorePackageStatusService.getByPackageId(queryScorePackageStatus);
		if (CollectionUtil.isEmpty(staList)) {
			return R.failed("未查询到审核通过的任务");
		}
		// 查询处方（任务）列表
		List<WmTask> taskList = wmTaskService.listTaskPrescription(packageId, null);
		if (CollectionUtil.isEmpty(staList)) {
			return R.failed("未查询到处方");
		}
		// 查询企业信息
		SysDept sysDept = sysDeptService.getById(scorePackage.getDeptId());
		Map<String, Object> excelMap = new HashMap<>();
		// 项目名称-年
		excelMap.put("rule_year", scorePackage.getBelongDate().substring(0, 4));
		// 项目名称-月
		excelMap.put("rule_month", scorePackage.getBelongDate().substring(5));
		LocalDateTime firstDate = taskList.get(0).getCreateTime();
		LocalDateTime lastDate = taskList.get(0).getCreateTime();
		// 项目名称-起止日期（第一次开具处方的日期和最后一次日期）
		excelMap.put("rule_days", firstDate.getDayOfMonth() + "-" + lastDate.getDayOfMonth());
		excelMap.put("service_date", firstDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "至"
				+ lastDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		// 积分包名称
		excelMap.put("scoreId", scorePackage.getScorePackageName());
		// 报告公司
		excelMap.put("report_ent", sysDept.getName());
		// 任务承接人
		if (CollectionUtil.isNotEmpty(staList)) {
			excelMap.put("report_users", staList.get(0).getUserId());
		}
		// 任务完成时间
		if ("1".equals(scorePackage.getPackageFinishStatus())) {
			excelMap.put("year", lastDate.getYear());
			excelMap.put("month", lastDate.getMonthValue());
			excelMap.put("day", lastDate.getDayOfMonth());
		}
		// 积分包值
		if (StringUtils.isNumeric(scorePackage.getUserScore())) {
			excelMap.put("totalscorePackageScore", String.format("%.2f", Integer.parseInt(scorePackage.getUserScore()) / 100.0));
		}
		// 已提交总值
		if (CollectionUtil.isNotEmpty(taskList)) {
			int sum = taskList.stream()
					.filter(wmTask -> wmTask.getScore() != null)
					.mapToInt(WmTask::getScore)
					.sum();
			excelMap.put("totalSubmitScore", String.format("%.2f", sum / 100.0));
		}
		// 表格数据列表
		List<Map<String, Object>> prescriptionTableList = new ArrayList<>();
		// 处方详情列表
		List<Map<String, Object>> prescriptionList = new ArrayList<>();
		Map<String, Object> ztTableObj = null;
		Map<String, Object> prescriptionObj = null;
		double totalHcpServiceCharge = 0.0;
		for (int i = 0; i < taskList.size(); i++) {
			WmTaskContent content = taskList.get(i).getWmTaskContent();
			ztTableObj = new HashMap<>();
			prescriptionObj = new HashMap<>();
			ztTableObj.put("number", i + 1);
			ztTableObj.put("doctorName", content.getTemp1());
			ztTableObj.put("prescriptionNo", content.getTemp3());
			ztTableObj.put("prescriptionTime", content.getTemp4());
			ztTableObj.put("hcpServiceCharge", content.getTemp5());
			prescriptionObj.put("number", i + 1);
			prescriptionObj.put("doctorName", content.getTemp1());
			prescriptionObj.put("prescriptionNo", content.getTemp3());
			prescriptionObj.put("prescriptionTime", content.getTemp4());
			prescriptionObj.put("hcpServiceCharge", content.getTemp5());
			prescriptionObj.put("dosage", content.getTemp8());
			prescriptionObj.put("approveDoctorName", content.getTemp8());
			prescriptionObj.put("shipper", content.getTemp9());
			prescriptionObj.put("drugs", content.getTemp10());
			prescriptionObj.put("usage", content.getTemp11());
			prescriptionObj.put("remark", content.getTemp12());
			prescriptionTableList.add(ztTableObj);
			prescriptionList.add(prescriptionObj);
			totalHcpServiceCharge += Double.parseDouble(content.getTemp5());
		}
		// 表格合计行
		ztTableObj = new HashMap<>();
		ztTableObj.put("number", "合计");
		ztTableObj.put("doctorName", "");
		ztTableObj.put("prescriptionNo", "");
		ztTableObj.put("prescriptionTime", "");
		ztTableObj.put("hcpServiceCharge", totalHcpServiceCharge);
		prescriptionTableList.add(ztTableObj);
		excelMap.put("prescriptionTable", prescriptionTableList);
		excelMap.put("prescriptionList", prescriptionList);

		String fileName = "患教服务报告(" + scorePackage.getScorePackageName() + ")_" + System.currentTimeMillis();
		File f = ExportReport.main_bulidTemplateHCP(excelMap, fileName + ".doc");
		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile(fileName, fileName + ".doc",
				"text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);

	}

	/**
	 * 个人报告导出--众包代表业绩报告
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	public R exportZb(WmTask wmTask) throws IOException {
		WmTask wmTaskparam=wmTask;
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}

		WmScorePackage wmScorePackage1=wmScorePackageService.getById(packageId);

		Map<String, Object> excelMap =exportZbCommon(wmTask);
		if(null==excelMap){
			return R.failed("未查询到审核通过的任务");
		}

		List<Map<String, Object>> infoList=exportZbInfo(wmTaskparam);
		if(null!=infoList&&infoList.size()>0){
			excelMap.put("infoList", infoList);
		}
		//区分全职兼职学术推广员模版
		excelMap.put("userType",wmScorePackage1.getTypeid());
		excelMap.put("scoreId",wmScorePackage1.getScorePackageName());
		File f =null;
		if(wmScorePackage1.getPackageType1().equals("1")){//定额
			 f = ExportReport.main_bulidTemplate1(excelMap, 2,upmsConfig.getBasePath());
		}else {//定量
			 f = ExportReport.main_bulidTemplate2(excelMap, 2,upmsConfig.getBasePath());
		}

		FileInputStream input = new FileInputStream(f);

		if(wmScorePackage1.getTypeid().equals("3")){//全职

		}
		MultipartFile multipartFile = new MockMultipartFile((wmScorePackage1.getTypeid().equals("3")?"全职":"兼职")+"学术信息沟通专员业绩报告(" + packageId + ")", "兼职学术推广员业绩报告(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);

	}


	/**
	 * 个人报告导出-- 结算包--众包代表业绩报告
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	public R exportZbJs(WmTask wmTask) throws IOException {
		WmTask wmTaskparam=wmTask;
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		Map<String, Object> excelMap = new HashMap<>();

		WmScorePackage wmScorePackage1=wmScorePackageService.getById(packageId);

		excelMap =exportZbCommon(wmTask);
		if(null==excelMap){
			return R.failed("未查询到审核通过的任务");
		}

		List<Map<String, Object>> infoList=exportZbInfoJs(wmTaskparam);
		if(null!=infoList&&infoList.size()>0){
			excelMap.put("infoList", infoList);
		}
		//区分全职兼职学术推广员模版
		excelMap.put("userType",wmScorePackage1.getTypeid());
		File f = ExportReport.main_bulidTemplate2(excelMap, 3,upmsConfig.getBasePath());


		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile((wmScorePackage1.getTypeid().equals("3")?"全职":"兼职")+"学术信息沟通专员业绩报告(" + packageId + ")", "兼职学术推广员业绩报告(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);

	}


	/*合并导出--汇总
	 */
	public   Map<String, Object> exportZbCommon(WmTask wmTask){
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

		Map<String, Object> excelMap = new HashMap<>();
		WmScorePackage wmScorePackage1=wmScorePackageService.getById(packageId);
		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(wmScorePackage1.getDrugEntId());
		if(wmDaDrugEnt==null){
			wmDaDrugEnt=new WmDaDrugEnt();
			wmDaDrugEnt.setEntname("无");
		}

		List<String> strs = new ArrayList<>();
		if (packageId.contains(",")) {
			strs.addAll(Arrays.asList(packageId.split(",")));
		} else {
			strs.add(packageId);
		}
		wmTask.setExtIds(strs);


		List<Map<String, Object>> wmTaskList = wmTaskService.getTaskListByIdsOld(wmTask);
		if(wmScorePackage1.getPackageType2().equals("2")){
			wmTaskList = wmTaskService.getTaskListByIdsJs(wmTask);
		}
		if (wmTaskList.size() > 0) {
			List<XlsTask> xlsTaskList = new ArrayList<>();
			Map<String, Object> userMap = new HashMap<>();
			for (Map<String, Object> wmt : wmTaskList) {
				XlsTask xlsTask = new XlsTask();
				xlsTask.setTaskNum(Integer.valueOf(wmt.get("score_count") + ""));
				xlsTask.setTaskType(wmt.get("base_id") + "");
				xlsTask.setUsername(wmt.get("realname") + "");
				xlsTask.setScore(Integer.parseInt((wmt.get("score")==null?"0":wmt.get("score")) + ""));
				xlsTask.setDrugEntName(wmDaDrugEnt.getEntname());
				xlsTask.setDeptName(wmt.get("dept_name") + "");
				xlsTask.setCreateTime(wmt.get("create_time") + "");
				xlsTaskList.add(xlsTask);

				String buildKey = wmt.get("realname") + "_" + wmDaDrugEnt.getEntname() + "_" + wmt.get("dept_name") + "";
				if (userMap.containsKey(buildKey)) {
					try {
						userMap.put(buildKey, Integer.parseInt(wmt.get("score")==null?"0":wmt.get("score") + "") + Integer.parseInt(userMap.get(buildKey)==null?"0":userMap.get(buildKey) + ""));
						userMap.put(buildKey + "_total", Integer.parseInt(wmt.get("score_count") + "") + Integer.parseInt(userMap.get(buildKey + "_total") + ""));

					} catch (Exception ex) {
					}
				} else {
					userMap.put(buildKey, wmt.get("score"));
					userMap.put(buildKey + "_total", Integer.parseInt(wmt.get("score_count") + ""));
				}
			}


			List<WmTask> wmTaskDetialList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
			List<Map<String, Object>> wmTaskDetialMap = new ArrayList<>();

			List<String> listPackageIds = new ArrayList<>();

			if (wmTaskDetialList.size() > 0) {
				for (WmTask wmTask1 :
						wmTaskDetialList) {
					Map<String, Object> map = new HashMap<>();
					WmTaskType wmTaskTypeTemp1 = wmTaskTypeService.getById(wmTask1.getTaskTypeId());
					map.put("taskType", wmTaskTypeTemp1.getTaskTypeName());
					DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
					String strDate2 = dtf2.format(wmTask1.getCreateTime());
					map.put("taskTime", strDate2);
					if(wmScorePackage1.getPackageType2().equals("2")){
						map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
					}else {
						map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
					}

					map.put("taskTypeId", wmTask1.getTaskTypeId());
					map.put("score", wmTask1.getScore());
					map.put("taskNum", 1);
					wmTaskDetialMap.add(map);

					if (listPackageIds.size() == 0) {
						listPackageIds.add(wmTask1.getScorePackageId());
					} else {
						boolean isInscore = true;
						for (String str : listPackageIds) {
							if (str.equals(wmTask1.getScorePackageId())) {
								isInscore = false;
							}
						}

						if (isInscore) {
							listPackageIds.add(wmTask1.getScorePackageId());
						}
					}
				}
			}

			if (listPackageIds.size() > 0) {
				List<WmScorePackage> wmScorePackageList = wmScorePackageService.listByIds(listPackageIds);
				Integer totalScorePackage = 0;
				BigDecimal settleAmount = new BigDecimal("0");
				if (wmScorePackageList.size() > 0) {
					for (WmScorePackage wmScorePackage : wmScorePackageList) {
						totalScorePackage += wmScorePackage.getScore();
						if (wmScorePackage.getSettleStatus() != null && wmScorePackage.getSettleStatus() == 1){
							settleAmount = settleAmount.add(wmScorePackage.getSettleAmount());
						}
					}
				}
				excelMap.put("settleAmount","0".equals(settleAmount.toString()) ? " " : settleAmount);
				excelMap.put("totalscorePackageScore", totalScorePackage);
				if(wmScorePackage1.getPackageType1().equals("2")||wmScorePackage1.getPackageType1().equals("3")){
					if(!wmScorePackage1.getPackageType2().equals("2")){
						excelMap.put("totalscorePackageTaskNum", wmScorePackage1.getTaskNum()*wmScorePackage1.getUserNum());//积分包值任务个数
					}
				}

				List<WmTask> tasks = wmTaskService.list(Wrappers.<WmTask>lambdaQuery()
						.in(WmTask::getScorePackageId, listPackageIds));

				if (CollUtil.isNotEmpty(tasks)){
					int sum = tasks.stream().mapToInt(WmTask::getScore).sum();
					excelMap.put("submitAmount",sum);
				}
			}

			excelMap.put("rwmxTable", wmTaskDetialMap);
			excelMap.put("mxTable", xlsTaskList);
			excelMap.put("ryTable", userMap);

		}

		Map<String, Timestamp> maxMaxTime=wmTaskService.getMaxCreateTime(wmTask);
		System.out.println(maxMaxTime);
		LocalDateTime MaxTime = maxMaxTime.get("MaxTime").toLocalDateTime();
		excelMap.put("year", MaxTime.getYear() + "");
		Integer month =MaxTime.getMonthValue() ;
		if (month < 10) {
			excelMap.put("month", "0" + MaxTime.getMonthValue() + "");
		} else {
			excelMap.put("month", MaxTime.getMonthValue() + "");
		}
		Integer day = MaxTime.getDayOfMonth();
		if (day < 10) {
			excelMap.put("day", "0" + MaxTime.getDayOfMonth() + "");
		} else {
			excelMap.put("day", MaxTime.getDayOfMonth() + "");
		}

		List<Map<String, Object>> wmTaskCount = wmTaskService.getTaskListByIdsCount(wmTask);
		if (wmTaskCount.size() > 0) {
			Integer total = 0;
			Integer sum = 0;
			for (Map<String, Object> map :
					wmTaskCount) {
				if (null != map.get("taskCount")) {
					total += Integer.parseInt(map.get("taskCount") + "");
				}

				if (null != map.get("taskSum")) {
					sum += Integer.parseInt(map.get("taskSum") + "");
				}

			}
			Map<String, Object> totalMap = new HashMap<>();
			totalMap.put("taskTypeName", "合计");
			totalMap.put("taskCount", total);
			totalMap.put("taskSum", sum);
			wmTaskCount.add(totalMap);

			excelMap.put("totalSubmitScore", sum);
			excelMap.put("totalSubmitTaskNum", total);
			excelMap.put("ztTable", wmTaskCount);
		}


		SysDept paramDept=new SysDept();
		paramDept.setDeptId(Integer.valueOf(wmScorePackage1.getSendPackageDeptId()));
		SysDept wmDaAgent = sysDeptService.selectDeptById(paramDept);
		excelMap.put("wt_ent", wmDaAgent.getName());

		excelMap.put("drugEnt", "");


		List<Map<String, Object>> wmTaskZd = wmTaskService.getTaskListByIdsZd(wmTask);
		if(wmScorePackage1.getPackageType2().equals("2")){
			wmTaskZd = wmTaskService.getTaskListByIdsZdJs(wmTask);
		}
		String minDateStr = null;
		String maxDateStr = null;
		if (null != wmTaskZd) {
			if (wmTaskZd.size() > 0) {
				Map<String, Object> stringMap = wmTaskZd.get(0);
				if (null == stringMap) {
					return null;
				}
				excelMap.put("service_date", stringMap.get("mindate") + "至" + stringMap.get("maxdate"));
				try {
					minDateStr = stringMap.get("mindate").toString().substring(5, 7);
					maxDateStr = stringMap.get("maxdate").toString().substring(5, 7);

				} catch (Exception ex) {
					ex.printStackTrace();
				}
				excelMap.put("tMoney", stringMap.get("sumscore") + "");
				excelMap.put("report_users", stringMap.get("realname") + "");


				String ruleDate = wmScorePackage1.getBelongDate();

				excelMap.put("rule_year", ruleDate.substring(0, 4));

				String monthStr = ruleDate.substring(5, 7);
				if (null != minDateStr && null != maxDateStr) {
					if (minDateStr.equals(maxDateStr)) {
						monthStr = minDateStr;
					} else {
						monthStr = minDateStr + "月至" + maxDateStr;
					}
				} else if (null != minDateStr) {
					monthStr = minDateStr;
				} else if (null != maxDateStr) {
					monthStr = maxDateStr;
				}

				excelMap.put("rule_month", monthStr);


			}
		}
		return excelMap;
	}

	/**
	 * 个人报告导出--报告详情
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	public List<Map<String, Object>> exportZbInfo(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

		if (null == packageId) {
			return null;
		}

		Map<String, Object> excelMap = new HashMap<>();


		wmTask.setScorePackageId(null);
		wmTask.setScorePackageDrugId(null);
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		wmTask.setScorePackageId(packageId);

		List<Map<String, Object>> infoList = new ArrayList<>();

		List<String> strs = new ArrayList<>();
		if (packageId.contains(",")) {
			strs.addAll(Arrays.asList(packageId.split(",")));
		} else {
			strs.add(packageId);
		}
		wmTask.setExtIds(strs);

		List<WmTask> wmTaskList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
		if (wmTaskList.size() > 0) {
			List<String> integerList = new ArrayList<>();
			integerList.add("1");
			integerList.add(2 + "");
			integerList.add(3 + "");
			integerList.add(4 + "");
			integerList.add(5 + "");
			integerList.add(12 + "");
			integerList.add(13 + "");
			integerList.add(14 + "");
			integerList.add(15 + "");
			integerList.add(16 + "");
			integerList.add(17 + "");
			integerList.add(18 + "");
			integerList.add(31 + "");

			Integer num = 1;
			for (WmTask wmTask1 : wmTaskList) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Map<String, Object> map = new HashMap<>();
				map.put("taskIndex", num++);
				map.put("taskType", wmTaskTypeService.getById(wmTask1.getTaskTypeId()).getTaskTypeName());
				DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String strDate2 = dtf2.format(wmTask1.getCreateTime());
				map.put("taskTime", strDate2);
				map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
				WmTaskType wmTaskTypeTemp1 = wmTaskTypeService.getById(wmTask1.getTaskTypeId());
				map.put("taskTypeId", wmTask1.getTaskTypeId());
				map.put("imgWidth", wmTaskTypeTemp1.getUpdateUser());
				map.put("imgHeight", wmTaskTypeTemp1.getCreateUser());
				if (null != wmTask1.getTaskInfoImg()) {
					map.put("taskBaseImg", wmTask1.getTaskInfoImg());
				} else {
					map.put("taskBaseImg", Html2ImageByJsWrapper.renderHtml2Image(upmsConfig.getApiUrl()
							+ "/h5/#/pages/task/task-detail/index?id=" + wmTask1.getId(), upmsConfig.getServerUrl()));
				}

				if (integerList.contains(wmTask1.getTaskTypeId())) {
					WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask1.getTaskContentId());
					if (null != wmTaskContent) {
						List<String> stringList = new ArrayList<>();
						WmTaskContentConfig queryWmTaskContentConfig = new WmTaskContentConfig();
						queryWmTaskContentConfig.setTaskTypeId(wmTask1.getTaskTypeId());
						queryWmTaskContentConfig.setTaskFiledType("img");
						List<WmTaskContentConfig> wmTaskContentConfigList = wmTaskContentConfigService.list(Wrappers.query(queryWmTaskContentConfig));
						if (wmTaskContentConfigList.size() > 0) {
							for (WmTaskContentConfig wmt : wmTaskContentConfigList) {
								String fileName = wmt.getTaskFiledKey();
								String imgList = getFieldValueByFieldName(fileName, wmTaskContent);
								Collections.addAll(stringList, imgList.split(","));
							}
						}

						if (stringList.size() > 0) {
							map.put("imgList", stringList);
						}

					}
				}

				infoList.add(map);
			}


		}

		return infoList;

//		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//		File f = ExportReport.main_bulidTemplate2(infoList, upmsConfig.getBasePath());
//
//		FileInputStream input = new FileInputStream(f);
//
//		MultipartFile multipartFile = new MockMultipartFile("兼职学术推广员业绩报告明细(" + packageId + ")", "兼职学术推广员业绩报告明细(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
//		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}


	/**
	 * 结算包--报道导出，合并
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	public List<Map<String, Object>> exportZbInfoJs(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}
		if (null == packageId) {
			return null;
		}
		wmTask.setScorePackageId(null);
		wmTask.setScorePackageDrugId(null);
		wmTask.setScorePackageId(packageId);

		List<Map<String, Object>> infoList = new ArrayList<>();

		List<String> strs = new ArrayList<>();
		if (packageId.contains(",")) {
			strs.addAll(Arrays.asList(packageId.split(",")));
		} else {
			strs.add(packageId);
		}
		wmTask.setExtIds(strs);

		List<WmTask> wmTaskList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
		if (wmTaskList.size() > 0) {
			Integer num = 1;
			for (WmTask wmTask1 : wmTaskList) {
				Map<String, Object> map = new HashMap<>();
				map.put("taskIndex", num++);
				WmTaskType wmTaskType=wmTaskTypeService.getById(wmTask1.getTaskTypeId());
				map.put("taskTypeName", wmTaskType.getTaskTypeName());
				WmTaskContent taskContent=wmTaskContentMapper.selectById(wmTask1.getTaskContentId());
				map.put("temp1", taskContent.getTemp1());//前端系统
				map.put("temp2", taskContent.getTemp2());//项目名称
				map.put("temp3", taskContent.getTemp3());//项目编码
				map.put("temp4", taskContent.getTemp4());//说明

				infoList.add(map);
			}

		}

		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		return infoList;
	}


	/**
	 * 结算报告--导出汇总报告--学术推广服务报告
	 * @param wmTask
	 * @param wmScorePackage
	 * @return
	 * @throws IOException
	 */
	public R exportNba(WmTask wmTask,WmScorePackage wmScorePackage) throws IOException {

		WmTask wmTaskparam=wmTask;
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}

		List<String> list = new ArrayList<>();
		list.add(packageId);

		wmTask.setExtIds(list);

		Map<String, Object> excelMap = new HashMap<>();

		wmScorePackage = wmScorePackageService.getById(packageId);
		if (null == wmScorePackage) {
			return R.failed("获取积分包失败");
		}

		excelMap.put("totalscorePackageScore", wmScorePackage.getScore());
		if(wmScorePackage.getPackageType1().equals("2")||wmScorePackage.getPackageType1().equals("3")){
			excelMap.put("totalscorePackageTaskNum", wmScorePackage.getTaskNum()*wmScorePackage.getUserNum());//积分包值任务个数
		}


		List<Map<String, Object>> wmTaskList = wmTaskService.getTaskListByIdsOld(wmTask);


		List<XlsTask> xlsTaskList = new ArrayList<>();//mxTable
		Integer totalMoney = 0;
//		wmTask.setScorePackageId(null);
//		wmTask.setScorePackageDrugId(null);

		//当前登陆人的机构
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		Map<String, Object> userMap = new HashMap<>();

		//委托公司（结算企业）
		SysDept drugEnt=sysDeptService.getById(wmScorePackage.getSendPackageDeptId());
		//WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(SecurityUtils.getUser().getDrugEntId());

		//报告公司（申请结算企业）
		SysDept applydrugEnt=sysDeptService.getById(wmScorePackage.getDeptId());
		//WmDaAgent wmDaAgent = wmDaAgentService.getById(wmScorePackage.getLevel1Id());

		for (Map<String, Object> wmT : wmTaskList) {
			totalMoney += Integer.parseInt(wmT.get("score") + "");
			XlsTask xlsTask = new XlsTask();
			xlsTask.setTaskNum(1);
			xlsTask.setCreateTime(wmT.get("create_time") + "");

			xlsTask.setDeptName(sysDept.getName());

			//level=2是药企
			if (sysDept.getLevel() == 2) {
				xlsTask.setAgentDeptName(applydrugEnt.getName());
			}

			xlsTask.setDrugEntName(drugEnt.getName());


			xlsTask.setScore(Integer.parseInt(wmT.get("score") + ""));

			xlsTask.setUsername(wmT.get("realname") + "");
			xlsTask.setTaskType(wmT.get("base_id") + "");

			xlsTaskList.add(xlsTask);

			String buildKey = wmT.get("realname") + "_" + drugEnt.getName() + "_" + sysDept.getName();
			//人员表格
			if (userMap.containsKey(buildKey)) {
				try {
					userMap.put(buildKey, Integer.parseInt(wmT.get("score") + "") + Integer.parseInt(userMap.get(buildKey) + ""));
					userMap.put(buildKey + "_total", Integer.parseInt(wmT.get("score_count") + "") + Integer.parseInt(userMap.get(buildKey + "_total") + ""));

				} catch (Exception ex) {
				}
			} else {
				userMap.put(buildKey, Integer.parseInt(wmT.get("score") + ""));
				userMap.put(buildKey + "_total", Integer.parseInt(wmT.get("score_count") + ""));
			}
		}

//		List<String> list1 = new ArrayList<>();
//		list1.add(packageId);

		//学术推广服务任务明细表格
		List<WmTask> wmTaskDetialList = wmTaskService.getTaskListByIdsReturnWmtaskInfo(wmTask);
		List<Map<String, Object>> wmTaskDetialMap = new ArrayList<>();

		if (wmTaskDetialList.size() > 0) {
			for (WmTask wmTask1 :
					wmTaskDetialList) {
				Map<String, Object> map = new HashMap<>();
				WmTaskType wmTaskTypeTemp1 = wmTaskTypeService.getById(wmTask1.getTaskTypeId());
				map.put("taskType", wmTaskTypeTemp1.getTaskTypeName());
				DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String strDate2 = dtf2.format(wmTask1.getCreateTime());
				map.put("taskTime", strDate2);
//				map.put("taskUser", sysUserService.getById(wmTask1.getTaskUserId()).getRealname());
				map.put("taskUser", sysUserService.getByIdIgnore(wmTask1.getTaskUserId()).getRealname());
				map.put("taskTypeId", wmTask1.getTaskTypeId());
				map.put("score", wmTask1.getScore());
				map.put("taskNum", 1);

				wmTaskDetialMap.add(map);
			}

		}

		excelMap.put("rwmxTable", wmTaskDetialMap);//学术推广服务任务明细表格

		if (totalMoney > wmScorePackage.getScore()) {
			totalMoney = wmScorePackage.getScore();
		}

		excelMap.put("ryTable", userMap);//人员表格
		excelMap.put("tMoney", totalMoney);

		if (xlsTaskList.size() > 0) {
			excelMap.put("wt_ent", xlsTaskList.get(0).getDrugEntName());//委托公司
			excelMap.put("drugEnt", xlsTaskList.get(0).getDrugEntName());//服务药企
			excelMap.put("mxTable", xlsTaskList);
		}

		List<Map<String, String>> ztTableList = new ArrayList<>();
		Map<String, String> ztMap = new HashMap<>();
		List<Map<String, Object>> wmTaskCount = wmTaskService.getTaskListByIdsCount(wmTask);
		if (wmTaskCount.size() > 0) {
			Integer total = 0;
			Integer sum = 0;
			for (Map<String, Object> map :
					wmTaskCount) {
				if (null != map.get("taskCount")) {
					total += Integer.parseInt(map.get("taskCount") + "");
				}

				if (null != map.get("taskSum")) {
					sum += Integer.parseInt(map.get("taskSum") + "");
				}

			}
			Map<String, Object> totalMap = new HashMap<>();
			totalMap.put("taskTypeName", "合计");
			totalMap.put("taskCount", total);
			totalMap.put("taskSum", sum);
			wmTaskCount.add(totalMap);

			excelMap.put("totalSubmitScore", sum);
			excelMap.put("totalSubmitTaskNum", total);

			excelMap.put("ztTable", wmTaskCount);//学术推广服务整体概况表格
		}

		//WmTaskRule wmTaskRule = wmTaskRuleService.getById(wmScorePackage.getTaskRuleId());
		String entDate = wmScorePackage.getBelongDate() + "-31";
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			format.parse(entDate);
		} catch (Exception ex) {
			entDate = wmScorePackage.getBelongDate() + "-30";
		}
		//excelMap.put("service_date", wmTaskRule.getRuleMonth() + "-01 至 " + entDate);

		List<Map<String, Object>> wmTaskZd = wmTaskService.getTaskListByIdsZd(wmTask);
		String minDateStr = null;
		String maxDateStr = null;
		if (null != wmTaskZd) {
			if (wmTaskZd.size() > 0) {
				Map<String, Object> stringMap = wmTaskZd.get(0);
				if (null == stringMap) {
					return R.failed("未找到审核通过的任务");
				}
				excelMap.put("service_date", stringMap.get("mindate") + "至" + stringMap.get("maxdate"));

				try {
					minDateStr = stringMap.get("mindate").toString().substring(5, 7);
					maxDateStr = stringMap.get("maxdate").toString().substring(5, 7);

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		if (null != applydrugEnt) {
			excelMap.put("report_ent", applydrugEnt.getName());
		} else {
			excelMap.put("report_ent", "");
		}


		String ruleDate = wmScorePackage.getBelongDate();

		excelMap.put("rule_year", ruleDate.substring(0, 4));

		String monthStr = ruleDate.substring(5, 7);
		if (null != minDateStr && null != maxDateStr) {
			if (minDateStr.equals(maxDateStr)) {
				monthStr = minDateStr;
			} else {
				monthStr = minDateStr + "月至" + maxDateStr;
			}
		} else if (null != minDateStr) {
			monthStr = minDateStr;
		} else if (null != maxDateStr) {
			monthStr = maxDateStr;
		}

		excelMap.put("rule_month", monthStr);

		//报告日期
		Map<String, Timestamp> maxMaxTime=wmTaskService.getMaxCreateTime(wmTask);
		System.out.println(maxMaxTime);
		LocalDateTime MaxTime = maxMaxTime.get("MaxTime").toLocalDateTime();
		excelMap.put("year", MaxTime.getYear() + "");
		Integer month =MaxTime.getMonthValue() ;
		if (month < 10) {
			excelMap.put("month", "0" + MaxTime.getMonthValue() + "");
		} else {
			excelMap.put("month", MaxTime.getMonthValue() + "");
		}
		Integer day = MaxTime.getDayOfMonth();
		if (day < 10) {
			excelMap.put("day", "0" + MaxTime.getDayOfMonth() + "");
		} else {
			excelMap.put("day", MaxTime.getDayOfMonth() + "");
		}

		excelMap.put("tMoney", totalMoney);
		excelMap.put("scoreId", wmScorePackage.getScorePackageName());

		List<Map<String, Object>> infoList=exportZbInfo(wmTaskparam);
		if(null!=infoList&&infoList.size()>0){
			excelMap.put("infoList", infoList);
		}else {
			return R.failed("未查询到审核通过的任务");
		}
		//区分全职兼职学术推广员模版
		excelMap.put("userType",wmScorePackage.getTypeid());

		File f =null;
		if(wmScorePackage.getPackageType1().equals("1")){//定额
			f = ExportReport.main_bulidTemplate1(excelMap, 1,upmsConfig.getBasePath());
		}else {//定量
			f = ExportReport.main_bulidTemplate2(excelMap, 1,upmsConfig.getBasePath());
		}

		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile("学术推广服务报告(" + packageId + ")", "学术推广服务报告(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}

}
