package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
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.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class SysExportServiceImpl implements SysExportService {

	private final WmTaskTypeService wmTaskTypeService;

	private final SysDeptService sysDeptService;

	private final WmTaskService wmTaskService;

	private final WmTaskRuleService wmTaskRuleService;

	private final WmDaAgentService wmDaAgentService;

	private final SysUserService sysUserService;

	private final WmTaskContentService wmTaskContentService;

	private final WmDaDrugEntService wmDaDrugEntService;

	private final WmTaskContentConfigService wmTaskContentConfigService;

	private final WmScorePackageService wmScorePackageService;

	private final SysFileService sysFileService;

	private final UpmsConfig upmsConfig;

	@Override
	public R exportZbInfoFormWei(WmPackageExportApiInput input) throws IOException {

		Map<String,String> resultMap = new HashMap<>();

		String packageId = input.getId();  // 获取积分包ID
		/**
		 * 1 导出汇总报告
		 */
		Map<String, Object> excelMap = new HashMap<>();

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

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

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

		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("totalscorePackageScore", totalScorePackage);

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

		}

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

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


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


			}
		}

		File f = ExportReport.main_bulidTemplate1(excelMap, 2,upmsConfig.getBasePath());
		FileInputStream input1 = new FileInputStream(f);

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

		if(r.getCode() == 0){
			resultMap = (Map<String, String>) r.getData();
		}else {
			log.info("众包代表业绩报告生成失败: {}", packageId);
			return R.failed("众包代表业绩报告生成失败");
		}


		/**
		 * 2 导出报告详情
		 */
		List<Map<String, Object>> infoList = new ArrayList<>();

		List<WmTask> wmTaskList2 = wmTaskService.getTaskListByPackageIdsReturnWmtaskInfo(wmTask);
		if (wmTaskList2.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 : wmTaskList2) {
				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 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 f2 = ExportReport.main_bulidTemplate2(infoList,upmsConfig.getBasePath());

		//FileInputStream fileInputStream = new FileInputStream(f2);

//		MultipartFile multipartFile2 = new MockMultipartFile("众包代表业绩报告明细(" + packageId + ")",
//				"众包代表业绩报告明细(" + packageId + ").doc",
//				"text/plain", IOUtils.toByteArray(fileInputStream));
//		R r1 =  sysFileService.uploadFileAllUrlRealName(multipartFile2);
//		if(r1.getCode() == 0){
//			Map<String, String> resultMap1 = (Map<String, String>) r1.getData();
//			resultMap.put("fileName1",resultMap1.get("fileName"));
//			resultMap.put("url1",resultMap1.get("url"));
//		}else {
//			log.info("众包代表业绩报告明细生成失败: {}", packageId);
//			return  R.failed("众包代表业绩报告明细生成失败");
//		}

		return R.ok(resultMap);
	}

	@Override
	public R exportZbInfo(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());
		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.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<>();
				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);
			}

		}

		return null;
//		// 这里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;
		}
	}
}
