/*
 *
 *      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.controller;

import cn.hutool.core.collection.CollUtil;
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.constant.CacheConstants;
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.entity.input.WmPackageExportApiInput;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmScorePackageMapper;
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.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 日志表 前端控制器
 * </p>
 *
 * @author hnqz
 * @since 2017-11-20
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/export")
@Api(value = "export", tags = "导出管理模块")
public class SysExportController {

	private final WmTaskService wmTaskService;

	private final WmScorePackageService wmScorePackageService;

	private final WmScorePackageSettleNoteService wmScorePackageSettleNoteService;

	private final WmScorePackageMapper wmScorePackageMapper;

	private final SysDeptService sysDeptService;

	private final SysDeptMapper sysDeptMapper;

	private final SysUserService sysUserService;

	private final WmDaDrugEntService wmDaDrugEntService;

	private final WmTaskTypeService wmTaskTypeService;

	private final WmTaskRuleService wmTaskRuleService;

	private final WmDaAgentService wmDaAgentService;

	private final WmDaHospitalService wmDaHospitalService;

	private final WmDaDistributionService wmDaDistributionService;

	private final WmTaskContentService wmTaskContentService;

	private final WmTaskContentConfigService wmTaskContentConfigService;

	private final SysFileService sysFileService;

	private final UpmsConfig upmsConfig;

	private final RedisTemplate redisTemplate;

	private final JavaMailSender sender;

	private final SysExportService sysExportService;

	/**
	 * 新增查询列表功能
	 */
	@GetMapping("/selectWmScorePackageList")
	public R selectWmScorePackageList(Page page, WmScorePackage wmScorePackage) {
		try {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
			wmScorePackage.setSendPackageDeptId(sysDept.getDeptId() + "");

			List<String> stringList = new ArrayList<>();
			stringList.add(sysDept.getDeptId() + "");
			stringList.add(sysDept.getParentId() + "");
			wmScorePackage.setDrugsIds(stringList);
			wmScorePackage.setTypeid("4");
			if (sysDept.getLevel() == 4) {
				wmScorePackage.setLevel2Id(sysDept.getLevel3Id() + "");
			} else {
				wmScorePackage.setLevel1Id(sysDept.getLevel2Id() + "");
			}
			return R.ok(wmScorePackageService.selectWmScorePackageList(page, wmScorePackage));

		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 分页查询
	 *
	 * @param page           分页对象
	 * @param wmScorePackage 积分包
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getExportPackageTotalList")
	public R getExportPackageTotalList(Page page, WmScorePackage wmScorePackage) {
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		wmScorePackage.setSendPackageDeptId(sysDept.getDeptId() + "");

		List<String> stringList = new ArrayList<>();
		stringList.add(sysDept.getDeptId() + "");
		stringList.add(sysDept.getParentId() + "");
		wmScorePackage.setDrugsIds(stringList);
		if (sysDept.getLevel() == 4) {
			wmScorePackage.setAgentTypeId("2");
			wmScorePackage.setLevel2Id(sysDept.getLevel3Id() + "");
			wmScorePackage.setUpdateUser(2);
		} else {
			wmScorePackage.setAgentTypeId("1");
			wmScorePackage.setLevel1Id(sysDept.getLevel2Id() + "");
		}
		IPage pageAnswer = wmScorePackageService.getExportPackageTotalList(page, wmScorePackage);
		List<WmScorePackage> list = pageAnswer.getRecords();

		pageAnswer.setRecords(list);
		return R.ok(pageAnswer);
	}


	/**
	 * 分页查询
	 *
	 * @param page           分页对象
	 * @param wmScorePackage 积分包
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getExportPackageZbTotalList")
	public R getExportPackageZbTotalList(Page page, WmScorePackage wmScorePackage) {
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		wmScorePackage.setSendPackageDeptId(sysDept.getDeptId() + "");

		List<String> stringList = new ArrayList<>();
		stringList.add(sysDept.getDeptId() + "");
		stringList.add(sysDept.getParentId() + "");
		wmScorePackage.setDrugsIds(stringList);
		wmScorePackage.setTypeid("4");
		if (sysDept.getLevel() == 4) {
			wmScorePackage.setLevel2Id(sysDept.getLevel3Id() + "");
		} else {
			wmScorePackage.setLevel1Id(sysDept.getLevel2Id() + "");
		}
		IPage pageAnswer = wmScorePackageService.getExportPackageTotalList(page, wmScorePackage);
		List<WmScorePackage> list = pageAnswer.getRecords();

		pageAnswer.setRecords(list);
		return R.ok(pageAnswer);
	}

	@GetMapping("/exportNb")
	public R exportNb(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		List<WmScorePackage> wmScorePackageList = wmScorePackageMapper.selectByRelationScoreIdList(packageId);
		List<String> idList = wmScorePackageList.stream().map(p ->p.getId()).collect(Collectors.toList());
		idList.add(packageId);
		List<String> list = new ArrayList<>();
			if (packageId.contains(",")) {
				list.addAll(Arrays.asList(packageId.split(",")));
			} else {
				list.add(packageId);
			}
		list.addAll(idList);

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

		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());


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


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

		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

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


		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.selectByDeptId(Integer.parseInt(wmScorePackage.getSendPackageDeptId()));

		WmDaAgent wmDaAgent = wmDaAgentService.selectByDeptId(Integer.parseInt(wmScorePackage.getSendPackageDeptId()));
		WmDaAgent wmDaAgent1 = wmDaAgentService.selectByDeptId(Integer.parseInt(wmScorePackage.getDeptId()));

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

			xlsTask.setDeptName(sysDept.getName());

			if (sysDept.getLevel() == 2) {
				xlsTask.setAgentDeptName(wmDaAgent.getGsmc());
				xlsTask.setDrugEntName(wmDaDrugEnt.getEntname());
			}
			if (sysDept.getLevel() == 3) {
				if(wmDaDrugEnt!=null){
				xlsTask.setDrugEntName(wmDaDrugEnt.getEntname());
				}
			}else if(sysDept.getLevel() == 4) {
				if(wmDaAgent!=null) {
					xlsTask.setDrugEntName(wmDaAgent.getGsmc());
				}
			}


			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") + "_" + wmDaDrugEnt.getEntname() + "_" + 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);

		WmTask queryDetail = new WmTask();
		queryDetail.setExtIds(list);

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

		List<WmTask> wmTaskDetialList = wmTaskService.getTaskListByPackageIdsReturnWmtaskInfo(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());

				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.getTaskListByPackageIdsCount(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("ztTable", wmTaskCount);
		}

		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.getTaskListByPackageIdsZd(wmTask);
		String minDateStr = null;
		String maxDateStr = null;
		String minyearStr = null;
		String maxyearStr = 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);
					minyearStr = stringMap.get("mindate").toString().substring(0, 4);
					maxyearStr = stringMap.get("maxdate").toString().substring(0, 4);


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

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


		String ruleDate = wmScorePackage.getBelongDate();

		try {
			if (Integer.parseInt(minyearStr) > Integer.parseInt(ruleDate.substring(0, 4))) {
				excelMap.put("rule_year", minyearStr);
			} else {
				excelMap.put("rule_year", ruleDate.substring(0, 4));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}


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

		excelMap.put("rule_month", monthStr);

		Calendar now = Calendar.getInstance();
		excelMap.put("year", now.get(Calendar.YEAR) + "");
		Integer month = now.get(Calendar.MONTH) + 1;
		if (month < 10) {
			excelMap.put("month", "0" + (now.get(Calendar.MONTH) + 1) + "");
		} else {
			excelMap.put("month", (now.get(Calendar.MONTH) + 1) + "");
		}
		Integer day = now.get(Calendar.DAY_OF_MONTH);
		if (day < 10) {
			excelMap.put("day", "0" + now.get(Calendar.DAY_OF_MONTH) + "");
		} else {
			excelMap.put("day", now.get(Calendar.DAY_OF_MONTH) + "");
		}

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

		File f = ExportReport.main_bulidTemplate1(excelMap, 1,null);
		FileInputStream input = new FileInputStream(f);

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


	@GetMapping("/exportNbInfo")
	public R exportNbInfo(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		List<WmScorePackage> wmScorePackageList = wmScorePackageMapper.selectByRelationScoreIdList(packageId);
		List<String> idList = wmScorePackageList.stream().map(p ->p.getId()).collect(Collectors.toList());
		idList.add(packageId);
		List<String> list = new ArrayList<>();
		if (packageId.contains(",")) {
			list.addAll(Arrays.asList(packageId.split(",")));
		} else {
			list.add(packageId);
		}
		list.addAll(idList);

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

		wmTask.setExtIds(list);


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

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

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

		List<WmTask> wmTaskList = wmTaskService.getTaskListByPackageIdsReturnWmtaskInfo(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 HH:mm:ss");
				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("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);
			}


		}

		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		File f = ExportReport.main_bulidTemplate2(infoList, upmsConfig.getBasePath());
		FileInputStream input = new FileInputStream(f);


		String name = "学术推广服务任务明细(" + packageId + ")";
		String suffix = ".doc";



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

	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 wmTask 任务表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/infoExportNbqybgInfo")
	//@PreAuthorize("@pms.hasPermission('admin_wmtask_view')" )
	public R infoExportNbqybgInfo(WmTask wmTask) throws IOException {
		wmTask.setDelFlag("0");
		wmTask.setEnableFlag("0");

		List<String> stringListDrug = new ArrayList<>();
		if (null != wmTask.getDrugEntId() && !"".equals(wmTask.getDrugEntId())) {
			stringListDrug.add(wmTask.getDrugEntId());
		} else {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
			if (null != sysDept) {
				WmDaAgent wmDaAgent = wmDaAgentService.getById(sysDept.getLevel2Id());
				if (null != wmDaAgent && null != wmDaAgent.getExtDrugEnt() && !"".equals(wmDaAgent.getExtDrugEnt())) {
					String extDrugEnt = wmDaAgent.getExtDrugEnt();
					String ext[] = extDrugEnt.split(",");
					for (String args : ext) {
						if (!(sysDept.getLevel1Id() + "").equals(args)) {
							stringListDrug.add(args);
						}
					}
				}
			}

			if (stringListDrug.size() == 0) {
				stringListDrug.add("-1");
			}

			wmTask.setExtIds(stringListDrug);

		}

		List<WmTask> wmTaskList = wmTaskService.listTaskByExtNoPage(wmTask);


		List<Map<String, Object>> infoList = new ArrayList<>();
		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(String.valueOf(31));

			Integer num = 1;
			for (WmTask wmTask1 : wmTaskList) {
				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 HH:mm:ss");
				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);
			}


		}

		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		File f = ExportReport.main_bulidTemplate2(infoList, upmsConfig.getBasePath());

		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile("学术推广服务任务明细", "众包代表业绩报告明细.doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}

	@GetMapping("/exportZb")
	public R exportZb(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

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

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


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

		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(SecurityUtils.getUser().getDrugEntId());


		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.getTaskListByPackageIds(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.setTaskType(wmt.get("base_id") + "");
				xlsTask.setUsername(wmt.get("realname") + "");
				xlsTask.setScore(Integer.parseInt(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") + "") + 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, wmt.get("score"));
					userMap.put(buildKey + "_total", Integer.parseInt(wmt.get("score_count") + ""));
				}
			}


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

			WmTask queryDetail = new WmTask();
			queryDetail.setExtIds(list1);

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

			List<WmTask> wmTaskDetialList = wmTaskService.getTaskListByPackageIdsReturnWmtaskInfo(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 HH:mm:ss");
					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("score", wmTask1.getScore());

					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("settleAmount",settleAmount.toString());
			}

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

		}

		Calendar now = Calendar.getInstance();
		excelMap.put("year", now.get(Calendar.YEAR) + "");
		Integer month = now.get(Calendar.MONTH) + 1;
		if (month < 10) {
			excelMap.put("month", "0" + (now.get(Calendar.MONTH) + 1) + "");
		} else {
			excelMap.put("month", (now.get(Calendar.MONTH) + 1) + "");
		}
		Integer day = now.get(Calendar.DAY_OF_MONTH);
		if (day < 10) {
			excelMap.put("day", "0" + now.get(Calendar.DAY_OF_MONTH) + "");
		} else {
			excelMap.put("day", now.get(Calendar.DAY_OF_MONTH) + "");
		}

		List<Map<String, Object>> wmTaskCount = wmTaskService.getTaskListByPackageIdsCount(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("ztTable", wmTaskCount);
		}

		// 计算所有所有提交任务积分
		List<WmTask> tasks = wmTaskService.list(Wrappers.<WmTask>lambdaQuery()
				.in(WmTask::getScorePackageId, wmTask.getExtIds()));

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


		String agentId = "";
		if (sysDept.getLevel() == 3) {
			agentId = sysDept.getLevel2Id() + "";

		} else {
			agentId = sysDept.getLevel3Id() + "";
		}

		WmDaAgent wmDaAgent = wmDaAgentService.getById(agentId);
		if (null != wmDaAgent) {
			excelMap.put("wt_ent", wmDaAgent.getGsmc());
		} else {
			excelMap.put("wt_ent", "");
		}

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


		List<Map<String, Object>> wmTaskZd = wmTaskService.getTaskListByPackageIdsZd(wmTask);
		String minDateStr = null;
		String maxDateStr = null;
		String minyearStr = null;
		String maxyearStr = 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);
					minyearStr = stringMap.get("mindate").toString().substring(0, 4);
					maxyearStr = stringMap.get("maxdate").toString().substring(0, 4);

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

				String ruleIds = stringMap.get("task_rule_id") + "";
				List<String> list = new ArrayList<>();
				if (ruleIds.contains(",")) {
					list.addAll(Arrays.asList(ruleIds.split(",")));
				} else {
					list.add(ruleIds);
				}

				List<WmTaskRule> wmTaskRuleList = wmTaskRuleService.listByIds(list);
				if (wmTaskRuleList.size() > 0) {
					if (wmTaskRuleList.size() == 1) {
						WmTaskRule wmTaskRule = wmTaskRuleList.get(0);
						String ruleDate = wmTaskRule.getRuleMonth();


						try {
							if (Integer.parseInt(minyearStr) > Integer.parseInt(ruleDate.substring(0, 4))) {
								excelMap.put("rule_year", minyearStr);
							} else {
								excelMap.put("rule_year", ruleDate.substring(0, 4));
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}

						//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 {
								if (maxyearStr.equals(minyearStr)) {
									monthStr = minDateStr + "月至" + maxDateStr;
								} else {
									monthStr = minDateStr + "月至" + maxyearStr + "年" + maxDateStr;
								}
							}
						} else if (null != minDateStr) {
							monthStr = minDateStr;
						} else if (null != maxDateStr) {
							monthStr = maxDateStr;
						}

						excelMap.put("rule_month", monthStr);
					}
				}


			}
		}

		File f = ExportReport.main_bulidTemplate1(excelMap, 2,null);
		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile("众包代表业绩报告(" + packageId + ")", "众包代表业绩报告(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);

	}

	@GetMapping("/exportZbInfo")
	public R exportZbInfo(WmTask wmTask) {

		R r = R.ok();
		try {
			r = sysExportService.exportZbInfo(wmTask);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
		return r;
	}


	//	@Inner(false)
	@GetMapping("/exportZbInfoFormWei")
	public R exportZbInfoFormWei(WmPackageExportApiInput input) {

		if (StringUtils.isNotEmpty(input.getEmail())) {
			HnqzUser user = SecurityUtils.getUser();
			redisTemplate.opsForValue().set(CacheConstants.EMAIL_KEY + user.getPlatId(), input.getEmail());
		} else {
			return R.failed("请输入邮箱");
		}

		if (StringUtils.isEmpty(input.getId())) {
			return R.failed("导出积分包ID不能为空");
		}

		R r = R.ok();
		try {
			r = sysExportService.exportZbInfoFormWei(input);

			if (r.getCode() == 0) {
				log.info("文件生成成功");
			} else {
				return r;
			}
			Map<String, String> resultMap = (Map<String, String>) r.getData();

			MimeMessage mail = sender.createMimeMessage();
			try {

				MimeMessageHelper helper = new MimeMessageHelper(mail, true);

				helper.setFrom(upmsConfig.getFormMail());
				helper.setTo(input.getEmail());

				helper.setSubject("要易云平台学术推广员业绩报告");
//				helper.setSubject(resultMap.get("fileName"));

//				helper.setText("众包代表业绩报告明细" + resultMap.get("url1"),
//						"报告已生成请<a href=" + resultMap.get("url1") + ">点击下载</a >");
				helper.setText("要易云平台学术推广员业绩报告","尊敬的学术推广员：" +
						"<br/>&nbsp;&nbsp;&nbsp;&nbsp;感谢您使用要易平台，下载学术推广汇总报告请<a href=" + resultMap.get("url") + ">点击链接</a >；" +
						"<br/>&nbsp;&nbsp;&nbsp;&nbsp;下载学术推广报告明细请<a href=" + resultMap.get("url1") + ">点击链接</a >");
				/**
				 * 附件
				 */
//				helper.addAttachment("众包代表业绩报告明细", multipartFile);

				sender.send(mail);
			} catch (MessagingException ex) {
				log.error("邮件发送失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
		return r;
	}


	@GetMapping("/infoExportJsInfo")
	public R infoExportJsInfo(WmTask wmTask) throws IOException {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}

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

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


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

		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(SecurityUtils.getUser().getDrugEntId());


		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.getTaskListByPackageIdsForJs(wmTask);
		if (wmTaskList.size() > 0) {
			excelMap.put("jsTable", wmTaskList);
		}

		List<Map<String, Object>> wmTaskCount = wmTaskService.getTaskListByPackageIdsForJsUser(wmTask);
		if (wmTaskCount.size() > 0) {
			excelMap.put("jsUserTable", wmTaskCount);
		}

		List<Map<String, Object>> wmTaskZd = wmTaskService.getTaskListByPackageIdsZd(wmTask);

		if (null != wmTaskZd) {
			if (wmTaskZd.size() > 0) {
				Map<String, Object> stringMap = wmTaskZd.get(0);
				if (null == stringMap) {
					R.failed("导出的积分包不存在已审核的任务");
				}
				excelMap.put("service_date", stringMap.get("mindate") + "至" + stringMap.get("maxdate"));
				excelMap.put("report_users", stringMap.get("realname") + "");

				String ruleIds = stringMap.get("task_rule_id") + "";
				List<String> list = new ArrayList<>();
				if (ruleIds.contains(",")) {
					list.addAll(Arrays.asList(ruleIds.split(",")));
				} else {
					list.add(ruleIds);
				}

				List<WmTaskRule> wmTaskRuleList = wmTaskRuleService.listByIds(list);
				if (wmTaskRuleList.size() > 0) {
					if (wmTaskRuleList.size() == 1) {
						WmTaskRule wmTaskRule = wmTaskRuleList.get(0);
						String ruleDate = wmTaskRule.getRuleMonth();

						excelMap.put("rule_year", ruleDate.substring(0, 4));
						excelMap.put("rule_month", ruleDate.substring(5, 7));
					}
				}
			}
		}

		File f = ExportReport.main_bulidTemplate3(excelMap);
		FileInputStream input = new FileInputStream(f);

		MultipartFile multipartFile = new MockMultipartFile("众包代表业绩报告-结算表(" + packageId + ")", "众包代表业绩报告-结算表(" + packageId + ").doc", "text/plain", IOUtils.toByteArray(input));
		return sysFileService.uploadFileAllUrlRealName(multipartFile);
	}
}
