/*
 *    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.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.entity.MonitoringIndicator;
import com.qunzhixinxi.hnqz.admin.entity.SysDeptSub;
import com.qunzhixinxi.hnqz.admin.entity.WmReport;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageSettleNote;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageStatus;
import com.qunzhixinxi.hnqz.admin.entity.WmScoreTaskType;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskContent;
import com.qunzhixinxi.hnqz.admin.entity.dto.CommonEvidenceDTO;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleAmountMonitorInput;
import com.qunzhixinxi.hnqz.admin.entity.output.SettleAmountMonitorOutput;
import com.qunzhixinxi.hnqz.admin.enums.ChannelEnum;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
import com.qunzhixinxi.hnqz.admin.enums.LockEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageFinishStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.ScorePackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.TaskStatusEnum;
import com.qunzhixinxi.hnqz.admin.mapper.WmReportMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmScorePackageMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskContentMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskMapper;
import com.qunzhixinxi.hnqz.admin.service.MonitoringIndicatorService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptSubService;
import com.qunzhixinxi.hnqz.admin.service.SysPublicParamService;
import com.qunzhixinxi.hnqz.admin.service.SysUserService;
import com.qunzhixinxi.hnqz.admin.service.WmDaDistributionService;
import com.qunzhixinxi.hnqz.admin.service.WmDaHospitalService;
import com.qunzhixinxi.hnqz.admin.service.WmDaPharmacyService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageSettleNoteService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageStatusService;
import com.qunzhixinxi.hnqz.admin.service.WmScoreTaskTypeService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskService;
import com.qunzhixinxi.hnqz.admin.util.RegUtils;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.data.datascope.DataScope;
import com.qunzhixinxi.hnqz.common.security.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import com.qunzhixinxi.hnqz.common.taxhelper.enums.InvoiceInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 任务表
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:25
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WmTaskServiceImpl extends ServiceImpl<WmTaskMapper, WmTask> implements WmTaskService {

	private final WmTaskMapper wmTaskMapper;
	private final WmReportMapper wmReportMapper;
	private final SysDeptService sysDeptService;
	private final SysDeptSubService sysDeptSubService;
	private final MonitoringIndicatorService monitoringIndicatorService;
	private final WmScorePackageService wmScorePackageService;
	private final WmScorePackageMapper wmScorePackageMapper;
	private final WmTaskContentMapper wmTaskContentMapper;
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final SysPublicParamService sysPublicParamService;
	private final WmScoreTaskTypeService wmScoreTaskTypeService;
	private final SysUserService userService;
	private final WmScorePackageSettleNoteService wmScorePackageSettleNoteService;
	private WmDaHospitalService wmDaHospitalService;
	private WmDaPharmacyService wmDaPharmacyService;
	private WmDaDistributionService wmDaDistributionService;

	@Autowired
	public void setWmDaHospitalService(WmDaHospitalService wmDaHospitalService) {
		this.wmDaHospitalService = wmDaHospitalService;
	}

	@Autowired
	public void setWmDaPharmacyService(WmDaPharmacyService wmDaPharmacyService) {
		this.wmDaPharmacyService = wmDaPharmacyService;
	}

	@Autowired
	public void setWmDaDistributionService(WmDaDistributionService wmDaDistributionService) {
		this.wmDaDistributionService = wmDaDistributionService;
	}

	@Override
	public List<WmTask> listTask(QueryWrapper wrappers) {
		return wmTaskMapper.selectListByScope(wrappers, new DataScope());
	}

	@Override
	public Page<WmTask> listTaskPage(Page page, QueryWrapper wrappers) {
		return baseMapper.selectPageByScope(page, wrappers, new DataScope());
	}

	@Override
	public Page<WmTask> listTaskPage(Page page, LambdaQueryWrapper<WmTask> wrappers) {
		return baseMapper.selectPageByScope(page, wrappers, new DataScope());
	}

	@Override
	public IPage<WmTask> listTaskByExt(Page page, WmTask wmTask) {
		return baseMapper.selectListByExtEnt(page, wmTask);
	}

	@Override
	public IPage<WmTask> listTaskByExt1(Page page, WmTask wmTask) {
		return baseMapper.selectListByRelationScoreId(page, wmTask);
	}

	@Override
	public List<WmTask> listTaskByExtNoPage(WmTask wmTask) {
		return baseMapper.selectListByExtEntNoPage(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIds(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIds(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIdsForJs(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsForJs(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIdsForJsUser(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsForJsUser(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIdsCount(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsCount(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIdsAndUser(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsAndUser(wmTask);
	}

	public List<Map<String, Object>> getTaskListByPackageIdsZd(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsZd(wmTask);
	}

	public List<WmTask> getTaskListByPackageIdsReturnWmtaskInfo(WmTask wmTask) {
		return wmTaskMapper.getTaskListByPackageIdsReturnWmtaskInfo(wmTask);
	}


	public IPage<Map<String, Object>> getH5PackageList(Page page, WmTask wmTask) {
		IPage<Map<String, Object>> h5PackagePage = wmTaskMapper.getH5PackageList(page, wmTask);
		List<Map<String, Object>> records = h5PackagePage.getRecords();
		if (CollectionUtil.isNotEmpty(records)) {
			records.forEach(map -> {
				// 如果是患者教育，则转换积分值 '分'->'元'
				String type1 = (String) map.get("type1");
				if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(type1)) {
					BigDecimal taskSum = (BigDecimal) map.get("taskSum");
					map.put("taskSum", taskSum.divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP));
				}
			});
		}

		return h5PackagePage;
	}

	public IPage<Map<String, Object>> getH5TaskList(Page page, WmTask wmTask) {
		IPage<Map<String, Object>> h5TaskPage = wmTaskMapper.getH5TaskList(page, wmTask);
		List<Map<String, Object>> records = h5TaskPage.getRecords();
		if (CollectionUtil.isNotEmpty(records)) {
			records.forEach(map -> {
				// 如果是患者教育，则转换积分值 '分'->'元'
				String type1 = (String) map.get("type1");
				if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(type1)) {
					Long taskSum = (Long) map.get("taskSum");
					Long taskCount = (Long) map.get("taskCount");
					map.put("taskSum", String.format("%.2f", taskSum / 100.0));
					map.put("taskCount", String.format("%.2f", taskCount / 100.0));
				}
			});
		}

		return h5TaskPage;
	}

	@Override
	public R selectZbCount(WmTask wmTask) {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			packageId = wmTask.getScorePackageDrugId();
		}
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		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 = wmTaskMapper.selectZbCount(wmTask);
		if (wmTaskList.size() > 0) {
			Integer total = 0;
			Integer sum = 0;
			Integer deptId = 0;
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);
			for (Map<String, Object> map :
					wmTaskList) {
				if (null != map.get("score_count")) {
					total += Integer.parseInt(map.get("score_count") + "");
				}

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

			}
			Map<String, Object> totalMap = new HashMap<>();
			totalMap.put("score_count", total);
			totalMap.put("score", sum);
			totalMap.put("score_package_id", packageId);
			totalMap.put("send_package_dept_id", deptId);
			totalMap.put("report_id", reportId);
			wmTaskList.add(totalMap);
			return R.ok(totalMap);
		}
		return R.ok(wmTaskList);
	}


	@Override
	public R selectByWmTask(WmTask wmTask) {
		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> strs1 = new ArrayList<>();
		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		String name = wmScorePackage.getScorePackageName();
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		Integer total = 0;
		if (sysDept.getLevel() == 3) {
			// 一级CSO
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
//			List<WmTask> taskList = wmTaskMapper.selectByWmTaskId(wmTask);
			for (WmTask wmTask1 : taskList) {
				Integer reportOneApprovalStatus = Integer.valueOf(wmTask1.getReportOneApprovalStatus());
				if (reportOneApprovalStatus == 0) {
					wmTask1.setExtIds(strs1);
					wmTask1.setReportOneApprovalStatus(String.valueOf(0));
					wmTask1.setTaskStatus(String.valueOf(3));
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportOneApprovalStatus(wmTask1);
					SysDept sysDept1 = sysDeptService.getById(wmScorePackage.getSendPackageDeptId());
					String name1 = sysDept1.getName();
					if (wmTaskList.size() > 0) {
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("description", name1);
						wmTaskList.add(totalMap);

						return R.ok(totalMap);
					}
				}
			}
		} else if (sysDept.getLevel() == 4) {
			// 二级CSO
			if (StringUtils.isNotBlank(wmScorePackage.getDrugEntId())) {
				// 通过drugEntId为空，判断是否为药企发来的包，即药企->一级CSO->二级CSO的包
				// 药企->一级CSO->二级CSO的大包，只能由一级CSO提交报告审批，二级CSO在任务中心中，点击生成报告按钮应提示没有权限
				return R.ok(0);
			}
			wmTask.setExtIds(strs1);
			wmTask.setTaskStatus(String.valueOf(3));
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			for (WmTask wmTask1 : taskList) {
				Integer reportSecondApprovalStatus = Integer.valueOf(wmTask1.getReportSecondApprovalStatus());
				if (reportSecondApprovalStatus == 0) {
					wmTask1.setExtIds(strs1);
					wmTask1.setReportSecondApprovalStatus(String.valueOf(0));
					wmTask1.setTaskStatus(String.valueOf(3));
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportSecondApprovalStatus(wmTask1);
					SysDept sysDept1 = sysDeptService.getById(wmScorePackage.getSendPackageDeptId());
					String name1 = sysDept1.getName();
					if (wmTaskList.size() > 0) {
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("description", name1);
						wmTaskList.add(totalMap);

						return R.ok(totalMap);
					}
				}
			}
		} else if (sysDept.getLevel() == 2) {
			// 药企
			wmTask.setExtIds(strs1);
			wmTask.setTaskStatus(String.valueOf(3));
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			for (WmTask wmTask1 : taskList) {
				Integer reportDrugApprovalStatus = Integer.valueOf(wmTask1.getReportDrugApprovalStatus());
				if (reportDrugApprovalStatus == 0) {
					wmTask1.setExtIds(strs1);
					wmTask1.setReportDrugApprovalStatus(String.valueOf(0));
					wmTask1.setTaskStatus(String.valueOf(3));
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportDrugApprovalStatus(wmTask1);
					SysDept sysDept1 = sysDeptService.getById(wmScorePackage.getSendPackageDeptId());
					String name1 = sysDept1.getName();
					if (wmTaskList.size() > 0) {
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("description", name1);
						wmTaskList.add(totalMap);

						return R.ok(totalMap);
					}
				}
			}
		}
		return R.ok(total);
	}

	@Override
	public R selectByWmTaskId(WmTask wmTask) {
		String packageId = wmTask.getScorePackageId();  // 获取积分包ID
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		List<String> strs = new ArrayList<>();
		if (packageId.contains(",")) {
			strs.addAll(Arrays.asList(packageId.split(",")));
		} else {
			strs.add(packageId);
		}
		wmTask.setExtIds(strs);
		wmTask.setTaskStatus(String.valueOf(3));
		List<WmTask> wmTaskList = wmTaskMapper.selectByWmTaskId(wmTask);

		return R.ok(wmTaskList);
	}


	@Override
	public R saveAndUpdateWmTask(WmTask wmTask, WmReport wmReport) {
		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> strs1 = new ArrayList<>();

		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		String name = wmScorePackage.getScorePackageName();
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());


		if (sysDept.getLevel() == 3) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids1 = taskList.stream()
					.filter(task -> "1".equals(task.getReportOneApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportOneApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			if (ids1.size() > 0) {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportOneId() == null) {
						wmTask1.setExtIds(strs1);
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByWmTaskOne(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();
							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
							if (!ids1.isEmpty()) {
								Integer total1 = 0;
								Integer sum1 = 0;
								Integer id = Integer.parseInt(ids1.get(0));
								WmTask wmTask2 = wmTaskMapper.selectById(id);
								Integer id1 = wmTask2.getReportOneId();
								updateWrapper.set(WmTask::getReportOneId, wmTask2.getReportOneId());
								updateWrapper.set(WmTask::getReportOneApprovalStatus, wmTask2.getReportOneApprovalStatus());
								updateWrapper.in(WmTask::getId, ids2);
								WmTaskService.super.update(updateWrapper);
								for (Map<String, Object> map :
										wmTaskList) {
									if (null != map.get("score_count")) {
										total1 += Integer.parseInt(map.get("score_count") + "");
									}

									if (null != map.get("score")) {
										sum1 += Integer.parseInt(map.get("score") + "");
									}
								}
								wmReport.setUpdateTime(LocalDateTime.now());
								wmReport.setTotalScore(sum1 + "");
								wmReport.setTaskNumber(total1 + "");
								wmReport.setId(id1);
								wmReportMapper.updateById(wmReport);
								return R.ok(updateWrapper);
							}
						}
					}
				}
			} else {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportOneId() == null) {
						wmTask1.setExtIds(strs1);
						wmTask1.setReportOneApprovalStatus(String.valueOf(0));
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportOneApprovalStatus(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();
							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);
							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();

							wmReportMapper.insert(wmReport);
							updateWrapper.set(WmTask::getReportOneId, wmReport.getId());
							updateWrapper.set(WmTask::getReportOneApprovalStatus, wmReport.getReportStatus());
							updateWrapper.in(WmTask::getId, ids2);
							WmTaskService.super.update(updateWrapper);
							return R.ok(updateWrapper);
						}
					}
				}

			}

		} else if (sysDept.getLevel() == 4) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids1 = taskList.stream()
					.filter(task -> "1".equals(task.getReportSecondApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportSecondApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			if (ids1.size() > 0) {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportSecondId() == null) {
						wmTask1.setExtIds(strs1);
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByWmTaskSecond(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();

							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
							if (!ids1.isEmpty()) {
								Integer total1 = 0;
								Integer sum1 = 0;
								Integer id = Integer.parseInt(ids1.get(0));
								WmTask wmTask2 = wmTaskMapper.selectById(id);
								Integer id1 = wmTask2.getReportSecondId();
								updateWrapper.set(WmTask::getReportSecondId, wmTask2.getReportSecondId());
								updateWrapper.set(WmTask::getReportSecondApprovalStatus, wmTask2.getReportSecondApprovalStatus());
								updateWrapper.in(WmTask::getId, ids2);
								WmTaskService.super.update(updateWrapper);
								for (Map<String, Object> map :
										wmTaskList) {
									if (null != map.get("score_count")) {
										total1 += Integer.parseInt(map.get("score_count") + "");
									}

									if (null != map.get("score")) {
										sum1 += Integer.parseInt(map.get("score") + "");
									}
								}
								wmReport.setUpdateTime(LocalDateTime.now());
								wmReport.setTotalScore(sum1 + "");
								wmReport.setTaskNumber(total1 + "");
								wmReport.setId(id1);
								wmReportMapper.updateById(wmReport);
								return R.ok(updateWrapper);
							}
						}
					}
				}
			} else {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportOneId() == null) {
						wmTask1.setExtIds(strs1);
						wmTask1.setReportSecondApprovalStatus(String.valueOf(0));
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportSecondApprovalStatus(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();
							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);
							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();

							wmReportMapper.insert(wmReport);
							updateWrapper.set(WmTask::getReportSecondId, wmReport.getId());
							updateWrapper.set(WmTask::getReportSecondApprovalStatus, wmReport.getReportStatus());
							updateWrapper.in(WmTask::getId, ids2);
							WmTaskService.super.update(updateWrapper);
							return R.ok(updateWrapper);
						}
					}
				}

			}

		} else if (sysDept.getLevel() == 2) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids1 = taskList.stream()
					.filter(task -> "1".equals(task.getReportDrugApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportDrugApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());
			if (ids1.size() > 0) {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportDrugId() == null) {
						wmTask1.setExtIds(strs1);
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByWmTaskDrug(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();
							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
							if (!ids1.isEmpty()) {
								Integer total1 = 0;
								Integer sum1 = 0;
								Integer id = Integer.parseInt(ids1.get(0));
								WmTask wmTask2 = wmTaskMapper.selectById(id);
								Integer id1 = wmTask2.getReportDrugId();
								updateWrapper.set(WmTask::getReportDrugId, wmTask2.getReportDrugId());
								updateWrapper.set(WmTask::getReportDrugApprovalStatus, wmTask2.getReportDrugApprovalStatus());
								updateWrapper.in(WmTask::getId, ids2);
								WmTaskService.super.update(updateWrapper);
								for (Map<String, Object> map :
										wmTaskList) {
									if (null != map.get("score_count")) {
										total1 += Integer.parseInt(map.get("score_count") + "");
									}

									if (null != map.get("score")) {
										sum1 += Integer.parseInt(map.get("score") + "");
									}
								}
								wmReport.setUpdateTime(LocalDateTime.now());
								wmReport.setTotalScore(sum1 + "");
								wmReport.setTaskNumber(total1 + "");
								wmReport.setId(id1);
								wmReportMapper.updateById(wmReport);
								return R.ok(updateWrapper);
							}
						}
					}
				}
			} else {
				for (WmTask wmTask1 : taskList) {
					if (wmTask1.getReportOneId() == null) {
						wmTask1.setExtIds(strs1);
						wmTask1.setReportDrugApprovalStatus(String.valueOf(0));
						List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportDrugApprovalStatus(wmTask1);
						String sendDeptId = wmScorePackage.getSendPackageDeptId();
						if (wmTaskList.size() > 0) {
							Integer total = 0;
							Integer sum = 0;
							Integer deptId = SecurityUtils.getUser().getDeptId();
							Date date = new Date();
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
							String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);
							for (Map<String, Object> map :
									wmTaskList) {
								if (null != map.get("score_count")) {
									total += Integer.parseInt(map.get("score_count") + "");
								}

								if (null != map.get("score")) {
									sum += Integer.parseInt(map.get("score") + "");
								}
							}
							Map<String, Object> totalMap = new HashMap<>();
							totalMap.put("score_count", total);
							totalMap.put("score", sum);
							totalMap.put("score_package_name", name);
							totalMap.put("dept_id", deptId);
							totalMap.put("report_id", reportId);
							totalMap.put("send_package_dept_id", sendDeptId);
							Integer packageId4 = Integer.parseInt(packageId);
							WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
							wmReport.setReportNo(reportId);
							wmReport.setScoreId(packageId4);
							wmReport.setTaskNumber(total + "");
							wmReport.setTotalScore(sum + "");
							wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
							wmReport.setApplyDrugEntId(deptId);
							wmReport.setReportStatus(String.valueOf(1));
							wmReport.setCreateTime(LocalDateTime.now());
							wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");
							wmReport.setPackageScore(wmScorePackage1.getScore() + "");
							LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();

							wmReportMapper.insert(wmReport);
							updateWrapper.set(WmTask::getReportDrugId, wmReport.getId());
							updateWrapper.set(WmTask::getReportDrugApprovalStatus, wmReport.getReportStatus());
							updateWrapper.in(WmTask::getId, ids2);
							WmTaskService.super.update(updateWrapper);
							return R.ok(updateWrapper);
						}
					}
				}

			}

		}
		return null;
	}

	@Override
	public R saveAndUpdateWmReport(WmTask wmTask, WmReport wmReport) {
		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> strs1 = new ArrayList<>();

		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		String name = wmScorePackage.getScorePackageName();
		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());


		if (sysDept.getLevel() == 3) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportOneApprovalStatus()) && !"2".equals(task.getReportDrugApprovalOpinion()))
					.map(p -> p.getId())
					.collect(Collectors.toList());

			for (WmTask wmTask1 : taskList) {
				if (wmTask1.getReportOneId() == null) {
					wmTask1.setExtIds(strs1);
					wmTask1.setReportOneApprovalStatus(String.valueOf(0));
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByReportOneApprovalStatus(wmTask1);
					String sendDeptId = wmScorePackage.getSendPackageDeptId();
					if (wmTaskList.size() > 0) {
						Integer total = 0;
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("send_package_dept_id", sendDeptId);
						wmTaskList.add(totalMap);
						Integer packageId4 = Integer.parseInt(packageId);
						WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
						wmReport.setPackageScore(wmScorePackage1.getScore() + "");
						wmReport.setReportNo(reportId);
						wmReport.setScoreId(packageId4);
						wmReport.setTaskNumber(total + "");
						wmReport.setTotalScore(sum + "");
						wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
						wmReport.setApplyDrugEntId(deptId);
						wmReport.setReportStatus(String.valueOf(2));
						wmReport.setCreateTime(LocalDateTime.now());
						wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");

						LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
						wmReportMapper.insert(wmReport);
						updateWrapper.set(WmTask::getReportOneId, wmReport.getId());
						updateWrapper.set(WmTask::getReportOneApprovalStatus, wmReport.getReportStatus());
						updateWrapper.in(WmTask::getId, ids2);
						WmTaskService.super.update(updateWrapper);

						return R.ok(totalMap);
					}
				}
			}
		} else if (sysDept.getLevel() == 4) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportSecondApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());

			for (WmTask wmTask1 : taskList) {
				Integer reportSecondApprovalStatus = Integer.valueOf(wmTask1.getReportSecondApprovalStatus());
				if (reportSecondApprovalStatus == 0 && wmTask1.getReportOneId() == null) {
					wmTask1.setExtIds(strs1);
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByWmTaskSecond(wmTask1);
					String sendDeptId = wmScorePackage.getSendPackageDeptId();
					if (wmTaskList.size() > 0) {
						Integer total = 0;
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("send_package_dept_id", sendDeptId);
						wmTaskList.add(totalMap);
						Integer packageId5 = Integer.parseInt(packageId);
						WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
						wmReport.setPackageScore(wmScorePackage1.getScore() + "");
						wmReport.setReportNo(reportId);
						wmReport.setScoreId(packageId5);
						wmReport.setTaskNumber(total + "");
						wmReport.setTotalScore(sum + "");
						wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
						wmReport.setApplyDrugEntId(deptId);
						wmReport.setReportStatus(String.valueOf(2));
						wmReport.setCreateTime(LocalDateTime.now());
						wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");

						LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
						wmReportMapper.insert(wmReport);
						updateWrapper.set(WmTask::getReportSecondId, wmReport.getId());
						updateWrapper.set(WmTask::getReportSecondApprovalStatus, wmReport.getReportStatus());
						updateWrapper.in(WmTask::getId, ids2);
						WmTaskService.super.update(updateWrapper);
						return R.ok(totalMap);
					}
				}
			}
		} else if (sysDept.getLevel() == 2) {
			if (packageId.contains(",")) {
				strs1.addAll(Arrays.asList(packageId.split(",")));
			} else {
				strs1.add(packageId);
			}
			wmTask.setExtIds(strs1);
			List<WmTask> taskList = new ArrayList<>();
			for (String id : idList) {
				WmTask wmTask1 = new WmTask();
				wmTask1.setTaskStatus(String.valueOf(3));
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
				taskList.addAll(wmTask2);
				strs1.add(id);
			}
			for (String id : idList) {
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageMapper.selectByRelationScoreIdList(id);
				List<String> idList1 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				for (String id1 : idList1) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setTaskStatus(String.valueOf(3));
					wmTask1.setScorePackageId(id1);
					List<WmTask> wmTask2 = wmTaskMapper.selectListByScorePackageId(wmTask1);
					taskList.addAll(wmTask2);
					strs1.add(id1);
				}
			}
			List<String> ids2 = taskList.stream()
					.filter(task -> "0".equals(task.getReportDrugApprovalStatus()))
					.map(p -> p.getId())
					.collect(Collectors.toList());

			for (WmTask wmTask1 : taskList) {
				Integer reportDrugApprovalStatus = Integer.valueOf(wmTask1.getReportDrugApprovalStatus());

				if (reportDrugApprovalStatus == 0 && wmTask1.getReportOneId() == null) {
					wmTask1.setExtIds(strs1);
					List<Map<String, Object>> wmTaskList = wmTaskMapper.selectByWmTaskDrug(wmTask1);
					String sendDeptId = wmScorePackage.getSendPackageDeptId();
					if (wmTaskList.size() > 0) {
						Integer total = 0;
						Integer sum = 0;
						Integer deptId = SecurityUtils.getUser().getDeptId();
						Date date = new Date();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
						String reportId = simpleDateFormat.format(date) + (int) ((Math.random() * 9 + 1) * 1000);

						for (Map<String, Object> map :
								wmTaskList) {
							if (null != map.get("score_count")) {
								total += Integer.parseInt(map.get("score_count") + "");
							}

							if (null != map.get("score")) {
								sum += Integer.parseInt(map.get("score") + "");
							}
						}
						Map<String, Object> totalMap = new HashMap<>();
						totalMap.put("score_count", total);
						totalMap.put("score", sum);
						totalMap.put("score_package_name", name);
						totalMap.put("dept_id", deptId);
						totalMap.put("report_id", reportId);
						totalMap.put("send_package_dept_id", sendDeptId);
						wmTaskList.add(totalMap);
						Integer packageId6 = Integer.parseInt(packageId);
						WmScorePackage wmScorePackage1 = wmScorePackageService.selectByPackage(packageId);
						wmReport.setPackageScore(wmScorePackage1.getScore() + "");
						wmReport.setReportNo(reportId);
						wmReport.setScoreId(packageId6);
						wmReport.setTaskNumber(total + "");
						wmReport.setTotalScore(sum + "");
						wmReport.setDrugEntId(Integer.valueOf(sendDeptId));
						wmReport.setApplyDrugEntId(deptId);
						wmReport.setReportStatus(String.valueOf(2));
						wmReport.setCreateTime(LocalDateTime.now());
						wmReport.setCreatePeople(SecurityUtils.getUser().getId() + "");

						LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
						wmReportMapper.insert(wmReport);
						updateWrapper.set(WmTask::getReportDrugId, wmReport.getId());
						updateWrapper.set(WmTask::getReportDrugApprovalStatus, wmReport.getReportStatus());
						updateWrapper.in(WmTask::getId, ids2);
						WmTaskService.super.update(updateWrapper);
						return R.ok(totalMap);

					}
				}
			}
		}
		return null;
	}

	@Override
	public R selectList(Page page, WmScorePackage wmScorePackage) {
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		QueryWrapper queryWrapper = Wrappers.query();
		wmScorePackage.setRelationScoreId(wmScorePackage.getId());
		List<WmScorePackage> wmScorePackageList = wmScorePackageService.selectLists(wmScorePackage);
		List<WmTask> list = new ArrayList<>();
		if (wmScorePackageList.size() > 0) {
			List<String> ids2 = wmScorePackageList.stream().map(p -> p.getId()).collect(Collectors.toList());
			for (String id : ids2) {
				WmScorePackage wmScorePackage1 = new WmScorePackage();
				wmScorePackage1.setRelationScoreId(id);
				List<WmScorePackage> wmScorePackageList1 = wmScorePackageService.selectLists(wmScorePackage1);
				WmTask wmTask1 = new WmTask();
				wmTask1.setScorePackageId(id);
				List<WmTask> wmTaskList = wmTaskMapper.selectListByIds(wmTask1);
				List<String> ids3 = wmTaskList.stream().map(p -> p.getId()).collect(Collectors.toList());
				List<String> ids4 = wmScorePackageList1.stream().map(p -> p.getId()).collect(Collectors.toList());
				if (wmScorePackageList1.size() > 0) {
					for (String id1 : ids4) {
						WmTask wmTask2 = new WmTask();
						wmTask2.setScorePackageId(id1);
						List<WmTask> wmTaskList1 = wmTaskMapper.selectListByIds(wmTask2);
						List<String> ids5 = wmTaskList1.stream().map(p -> p.getId()).collect(Collectors.toList());
						for (String id2 : ids5) {
							WmTask wmTaskList2 = wmTaskMapper.selectById(id2);
							list.add(wmTaskList2);
						}
					}
				}
				for (String id1 : ids3) {
					WmTask wmTaskList1 = wmTaskMapper.selectById(id1);
					list.add(wmTaskList1);
				}
			}
		} else if (wmScorePackageList.size() == 0) {
			WmTask wmTask = new WmTask();
			wmTask.setScorePackageId(wmScorePackage.getId());
			List<WmTask> wmTaskList1 = wmTaskMapper.selectListByIds(wmTask);
			list.addAll(wmTaskList1);
		}

		Page pageAnswer = super.page(page, queryWrapper);
		pageAnswer.setRecords(list);
		return R.ok(pageAnswer);
	}


	@Override
	public List<Map<String, Object>> getTaskListByIdsCount(WmTask wmTask) {
		return wmTaskMapper.getTaskListByIdsCount(wmTask);
	}

	@Override
	public List<Map<String, Object>> getTaskListByIds(WmTask wmTask) {
		return wmTaskMapper.getTaskListByIds(wmTask);
	}

	@Override
	public List<Map<String, Object>> getTaskListByIdsOld(WmTask wmTask) {
		return wmTaskMapper.getTaskListByIdsOld(wmTask);
	}

	@Override
	public List<Map<String, Object>> getTaskListByIdsJs(WmTask wmTask) {
		return wmTaskMapper.getTaskListByIdsJs(wmTask);
	}

	@Override
	public List<WmTask> getTaskListByIdsReturnWmtaskInfo(WmTask wmTask) {
		return wmTaskMapper.getTaskListByIdsReturnWmtaskInfo(wmTask);
	}

	@Override
	public List<Map<String, Object>> getTaskListByIdsZd(WmTask wmTask) {

		return wmTaskMapper.getTaskListByIdsZd(wmTask);
	}

	@Override
	public List<Map<String, Object>> getTaskListByIdsZdJs(WmTask wmTask) {

		return wmTaskMapper.getTaskListByIdsZdJs(wmTask);
	}

	@Override
	public R getWmTaskList(Page page, WmTask wmTask) {
		WmScorePackage wmScorePackage1 = wmScorePackageService.getById(wmTask.getScorePackageId());
		if (wmScorePackage1.getTypeid().equals("1")) {//药企给一代发的包
			wmTask.setScorePackageDrugId(wmTask.getScorePackageId());
			wmTask.setScorePackageId(null);
		} else if (wmScorePackage1.getTypeid().equals("2")) {//一代给二代发的包
			wmTask.setScorePackageLevel1Id(wmTask.getScorePackageId());
			wmTask.setScorePackageId(null);
		}
		wmTask.setDelFlag("0");
		wmTask.setRealFlag("0");
		return R.ok(wmTaskMapper.getWmTaskList(page, wmTask));
	}

	/**
	 * 任务审核，要针对每一个接单用户，每一个用户的任务全部审核完毕，才算是积分包完成
	 *
	 * @param wmTask
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R approvalTask(WmTask wmTask) {
		//要循环判断，每一个接单用户，所有用户完成，审核通过，才算是积分包完成
		//有没有什么问题，例如，个人包收回，影响积分包的积分值
		String[] ids = wmTask.getId().split(",");
		if (ids.length <= 0) {
			return R.failed("缺少参数！");
		}

		LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper();
		updateWrapper.in(WmTask::getId, ids);
		List<WmTask> wmTaskList = list(updateWrapper);

		String scorePackageId = wmTaskList.get(0).getScorePackageId();
		WmScorePackage wmScorePackage = wmScorePackageService.getById(scorePackageId);

		// 如果是源头积分包，则判断是否审核入库调查信息
		if (StringUtils.isBlank(wmScorePackage.getRelationScoreId())) {
			// 调查信息审核（15、30-医院 16-商业公司 18-药店）
			wmTaskList.forEach(task -> {
				String approvalOpinion = wmTask.getTaskStatus().equals(TaskStatusEnum.APPROVED.val()) ? "1" : "2";
				if ("15".equals(task.getTaskTypeId()) || "30".equals(task.getTaskTypeId())) {
					Map<String, Object> data = (Map<String, Object>) wmDaHospitalService.approvalHospital(task.getId()).getData();
					WmTask _wmTask = (WmTask) data.get("wmTask");
					Map<String, String> paramMap = BeanUtil.toBean(data.get("newinfo"), Map.class);
					paramMap.put("approvalInfo", wmTask.getTaskStatusInfo());
					paramMap.put("approvalOpinion", approvalOpinion);
					paramMap.put("compareResult", _wmTask.getCompareResult());
					paramMap.put("taskId", task.getId());
					wmDaHospitalService.updateByApproval(paramMap);
				} else if ("16".equals(task.getTaskTypeId())) {
					Map<String, Object> data = (Map<String, Object>) wmDaDistributionService.approvalDistribution(task.getId()).getData();
					WmTask _wmTask = (WmTask) data.get("wmTask");
					Map<String, String> paramMap = BeanUtil.toBean(data.get("newinfo"), Map.class);
					paramMap.put("approvalInfo", wmTask.getTaskStatusInfo());
					paramMap.put("approvalOpinion", approvalOpinion);
					paramMap.put("compareResult", _wmTask.getCompareResult());
					paramMap.put("taskId", task.getId());
					wmDaDistributionService.updateByApproval(paramMap);
				} else if ("18".equals(task.getTaskTypeId())) {
					Map<String, Object> data = (Map<String, Object>) wmDaPharmacyService.approvalPharmacy(task.getId()).getData();
					WmTask _wmTask = (WmTask) data.get("_wmTask");
					Map<String, String> paramMap = MapUtil.newHashMap(4);
					paramMap.put("approvalInfo", wmTask.getTaskStatusInfo());
					paramMap.put("approvalOpinion", approvalOpinion);
					paramMap.put("compareResult", _wmTask.getCompareResult());
					paramMap.put("taskId", task.getId());
					wmDaPharmacyService.updateByapproval(paramMap);
				}
			});
		}

		switch (wmTask.getTaskStatus()){
			case "3": // 审核通过

				// 获取用户积分系统上线
				String value = sysPublicParamService.getSysPublicParamKeyToValue("USER_TASK_SUB_SCORE");
				log.warn("系统当前限制积分上限：【{}】", value);
				int limit = StringUtils.isEmpty(value) ? 30000 : Integer.parseInt(value);

				List<WmTask> bathList = new ArrayList<>(wmTaskList.size());

				Map<String, Map<LocalDate, List<WmTask>>> collect = wmTaskList.stream()
						.collect(Collectors.groupingBy(WmTask::getTaskUserId, Collectors.groupingBy(task -> task.getCreateTime()
								.toLocalDate())));
				if (CollectionUtil.isNotEmpty(collect)){
					for (Map.Entry<String,Map<LocalDate, List<WmTask>>> outer : collect.entrySet()){
						String userId = outer.getKey();
						Map<LocalDate, List<WmTask>> outerValue = outer.getValue();
						for (Map.Entry<LocalDate, List<WmTask>> inner : outerValue.entrySet()){
							LocalDate localDate = inner.getKey();
							List<WmTask> taskList = inner.getValue();
							int amount = baseMapper.newGetUserTaskSubScore(userId, LocalDateTime.of(localDate,LocalTime.MIN), LocalDateTime.of(localDate,LocalTime.MAX));
							boolean flag = amount > limit;
							for (WmTask t : taskList) {
								if ((amount += t.getScore()) >= limit) {
									if (flag) {
										t.setScore(0);
									}
									flag = true;
								}
								t.setTaskStatus("3");
								t.setRealFlag("0");
								t.setUpdateTime(LocalDateTime.now());
							}
							bathList.addAll(taskList);
						}
					}
				}

				updateBatchById(bathList);
				break;
			case "4": // 审核不通过
				updateWrapper.set(WmTask::getTaskStatus, wmTask.getTaskStatus());
				updateWrapper.set(WmTask::getRealFlag, "0");
				this.update(updateWrapper);
				break;
		}

		wmTaskList.forEach(task -> {
			WmScorePackageStatus scorePackageStatus = new WmScorePackageStatus();
			scorePackageStatus.setPackageId(wmScorePackage.getId());
			scorePackageStatus.setUserId(task.getTaskUserId());
			scorePackageStatus.setStatus("2");//接单审核通过
			List<WmScorePackageStatus> scorePackageStatusList = wmScorePackageStatusService.list(Wrappers.query(scorePackageStatus));

			if (CollectionUtil.isNotEmpty(scorePackageStatusList)) {
				scorePackageStatus = scorePackageStatusList.get(0);
				wmScorePackageStatusService.updatePackageAndStatus(task, wmScorePackage, scorePackageStatus);
			}
		});

		//判断已审核的任务积分值，或者积分个数是否满了，如果满了，就将所有未审核的任务，更新成审核不通过
		//即，将real_flag=9更新成real_flag=1,将task_status=2更新成task_status=4
		wmScorePackageStatusService.updateScorePackageStatus(scorePackageId);

		return R.ok("审核成功");
	}


	@Override
	public Map<String, Timestamp> getMaxCreateTime(WmTask wmTask) {
		return wmTaskMapper.getMaxCreateTime(wmTask);
	}

	@Override
	public R saveTaskSettle(WmTask wmTask) {
		WmScorePackage wmScorePackage1 = wmScorePackageService.getById(wmTask.getScorePackageId());
		WmTask query = new WmTask();
		query.setScorePackageId(wmScorePackage1.getId());
		query.setTaskUserId(wmTask.getTaskUserId());
		query.setDelFlag("0");
		query.setEnableFlag("0");
		query.setTaskStatus("3");//审核通过
		List<WmTask> wmTasks = wmTaskMapper.selectList(Wrappers.query(query));
		if (CollectionUtils.isNotEmpty(wmTasks) &&
				new BigDecimal(wmScorePackage1.getTaskNum()).compareTo(new BigDecimal(wmTasks.size())) < 1) {
			return R.failed("任务数已满");
		}
		wmTask.setLookintoDate(LocalDateTime.now());
		wmTask.setCreateTime(LocalDateTime.now());

		wmTask.setDeptId(wmScorePackage1.getDeptId() + "");
		wmTask.setDrugEntId(wmScorePackage1.getDrugEntId() + "");
		wmTask.setTaskStatus("3");//审核通过
		wmTask.setDelFlag("0");
		wmTask.setEnableFlag("0");
		wmTask.setTaskFrom("2");
		wmTask.setReportDrugApprovalStatus("0");
		wmTask.setReportOneApprovalStatus("0");
		wmTask.setReportSecondApprovalStatus("0");
		WmTaskContent taskContent = wmTask.getWmTaskContent();
		taskContent.setTemp32(wmScorePackage1.getId());
		wmTaskContentMapper.insert(taskContent);
		wmTask.setTaskContentId(taskContent.getId() + "");
		return R.ok(this.save(wmTask));
	}

	/**
	 * 患者教育-处方上传
	 *
	 * @param wmTask
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveTaskPrescription(WmTask wmTask) {
		// 查询对应的积分包
		WmScorePackage scorePackage = wmScorePackageService.getById(wmTask.getScorePackageId());
		// 校验积分包是不是这个部门下的
		Integer deptId = SecurityUtils.getUser().getDeptId();
		if (!String.valueOf(deptId).equals(scorePackage.getDeptId())) {
			return R.failed("该积分包不属于这个部门");
		}
		// 查询积分包状态，此处只取第一条即可（固定只能一个人领取）
		Wrapper<WmScorePackageStatus> queryWrapper = Wrappers.<WmScorePackageStatus>lambdaQuery()
				.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
				.eq(WmScorePackageStatus::getDelFlag, DelEnum.NOT_DEL.val())
				.eq(WmScorePackageStatus::getEnableFlag, EnableEnum.ENABLE.val());
		List<WmScorePackageStatus> packageStatusList = wmScorePackageStatusService.list(queryWrapper);
		WmScorePackageStatus scorePackageStatus = packageStatusList.get(0);
		if (CollectionUtil.isEmpty(packageStatusList)) {
			if (PackageStatusEnum.APPROVED.val().equals(scorePackageStatus.getStatus())) {
				return R.failed("积分包不是审核通过状态");
			}
			return R.failed("积分包还未被领取");
		}
		WmTask queryTask = new WmTask();
		queryTask.setScorePackageId(scorePackage.getId());
		queryTask.setTaskUserId(scorePackageStatus.getUserId());
		queryTask.setDelFlag(DelEnum.NOT_DEL.val());
		queryTask.setEnableFlag(EnableEnum.ENABLE.val());
		queryTask.setTaskStatus(TaskStatusEnum.APPROVED.val());
		List<WmTask> wmTasks = wmTaskMapper.selectList(Wrappers.query(queryTask));
		// 判断实际任务数（处方上传数）是否超过 积分包设置的任务数
		if (CollectionUtils.isNotEmpty(wmTasks) && scorePackage.getTaskNum() != null) {
			if (scorePackage.getTaskNum() <= wmTasks.size()) {
				return R.failed("任务数已满");
			}
		}
		// 保存task及子对象taskContent
		WmTask task = new WmTask();
		task.setScorePackageId(scorePackage.getId());
		task.setTaskUserId(scorePackageStatus.getUserId());
		task.setDelFlag(DelEnum.NOT_DEL.val());
		task.setEnableFlag(EnableEnum.ENABLE.val());
		task.setTaskStatus(TaskStatusEnum.APPROVED.val());
		wmTask.setDeptId(String.valueOf(scorePackage.getDeptId()));
		wmTask.setDrugEntId(String.valueOf(scorePackage.getDrugEntId()));
		wmTask.setTaskFrom("2");
		LocalDateTime now = LocalDateTime.now();
		task.setCreateTime(now);
		task.setLookintoDate(now);
		task.setTaskStatus(TaskStatusEnum.APPROVED.val());
		task.setDelFlag(DelEnum.NOT_DEL.val());
		task.setEnableFlag(EnableEnum.ENABLE.val());
		// 这里的任务即处方，积分值改为患教服务费
		WmTaskContent taskContent = wmTask.getWmTaskContent();
		if (RegUtils.validateNumber(taskContent.getTemp5())) {
			// 将患教服务费，存入当前task积分
			BigDecimal hcpServiceCharge = new BigDecimal(taskContent.getTemp5()).setScale(2, BigDecimal.ROUND_HALF_EVEN);
			task.setScore(hcpServiceCharge.multiply(new BigDecimal("100")).intValue());
		}
		// 查询taskType
		List<WmScoreTaskType> taskTypeList = wmScoreTaskTypeService.list(Wrappers.<WmScoreTaskType>lambdaQuery()
				.eq(WmScoreTaskType::getScoreId, scorePackage.getId()));
		if (CollectionUtil.isNotEmpty(taskTypeList)) {
			task.setTaskTypeId(taskTypeList.get(0).getTaskTypeId());
		}
		// 保留积分包id
		taskContent.setTemp32(scorePackage.getId());
		wmTaskContentMapper.insert(taskContent);
		task.setTaskContentId(String.valueOf(taskContent.getId()));
		this.save(task);
		// 判断任务是否上传满
		List<WmTask> taskList = wmTaskMapper.selectList(Wrappers.query(queryTask));
		if (scorePackage.getTaskNum() <= taskList.size()) {
			// 任务已上传满，修改积分包状态为已完成待结算
			WmScorePackage updateScorePackage = new WmScorePackage();
			updateScorePackage.setId(scorePackage.getId());
			updateScorePackage.setScorePackageStatus(ScorePackageStatusEnum.TO_BE_SETTLED.val());
			updateScorePackage.setPackageFinishStatus(PackageFinishStatusEnum.COMPLETED.val());
			updateScorePackage.setPackageFinishTime(now);
			wmScorePackageService.updateById(updateScorePackage);
		}

		return R.ok();
	}

	@Override
	public R updateTaskSettle(WmTask wmTask) {
		WmTask wmTask1 = this.getById(wmTask.getId());
		WmTaskContent taskContent = wmTask.getWmTaskContent();
		if (taskContent != null) {
			taskContent.setId(Integer.valueOf(wmTask1.getTaskContentId()));
			wmTaskContentMapper.updateById(taskContent);
		}
		return R.ok(this.updateById(wmTask));
	}

	public IPage<Map<String, Object>> selectSettleTask(Page page, WmTask wmTask) {
		return wmTaskMapper.selectSettleTask(page, wmTask);
	}

	@Override
	public Boolean checkUserTaskSubScore(String userId) {
		LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
		int total = wmTaskMapper.getUserTaskSubScore(userId, startTime, endTime);
		// 获取用户积分系统上线
		String value = sysPublicParamService.getSysPublicParamKeyToValue("USER_TASK_SUB_SCORE");
		log.warn("系统当前限制积分上限：【{}】", value);
		return total >= (StringUtils.isEmpty(value) ? 30000 : Integer.parseInt(value));
	}

	@Override
	public Boolean newCheckUserTaskSubScore(String userId, LocalDate createDate) {
		LocalDateTime startTime = LocalDateTime.of(createDate, LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(createDate, LocalTime.MAX);
		int total = wmTaskMapper.newGetUserTaskSubScore(userId, startTime, endTime);
		// 获取用户积分系统上线
		String value = sysPublicParamService.getSysPublicParamKeyToValue("USER_TASK_SUB_SCORE");
		log.warn("系统当前限制积分上限：【{}】", value);
		return total >= (StringUtils.isEmpty(value) ? 30000 : Integer.parseInt(value));
	}


	@Override
	public R getTaskInfo(String taskId) {
		WmTask task = this.getById(taskId);
		if (task == null) {
			return R.failed("未查询到任务信息");
		}
		WmTaskContent content = wmTaskContentMapper.selectById(task.getTaskContentId());
		if (content == null) {
			return R.failed("未查询到任务详情");
		}
		task.setWmTaskContent(content);
		return R.ok(task);
	}

	/**
	 * 查询调查信息审核数据
	 *
	 * @param taskId 任务id
	 * @return
	 */
	@Override
	public R<?> getSurveryTaskInfo(String taskId) {
		WmTask task = this.getById(taskId);
		R<?> result = null;
		// 15、30-医院 16-商业公司 18-药店
		if ("15".equals(task.getTaskTypeId()) || "30".equals(task.getTaskTypeId())) {
			result = wmDaHospitalService.approvalHospital(taskId);
			if (result.getCode() == 0) {
				Map<String, Object> data = (Map<String, Object>) result.getData();
				data.remove("info");
				data.remove("newinfo");
			}
		} else if ("16".equals(task.getTaskTypeId())) {
			result = wmDaDistributionService.approvalDistribution(taskId);
			if (result.getCode() == 0) {
				Map<String, Object> data = (Map<String, Object>) result.getData();
				data.remove("info");
				data.remove("newinfo");
			}
		} else if ("18".equals(task.getTaskTypeId())) {
			result = wmDaPharmacyService.approvalPharmacy(taskId);
			if (result.getCode() == 0) {
				Map<String, Object> data = (Map<String, Object>) result.getData();
				data.put("wmTask", data.get("_wmTask"));
				data.put("compareList", new ArrayList<>());
				data.remove("_wmTask");
				data.remove("info");
				data.remove("newinfo");
				data.remove("compareResult");
			}
		} else {
			result = R.failed("未查询到任务信息");
		}

		return result;
	}

	/**
	 * 患者教育-处方列表
	 *
	 * @param scorePackageId 积分包id
	 * @param prescriptionNo 处方单编号
	 * @return 处方列表
	 */
	@Override
	public IPage<WmTaskContent> listTaskPrescription(Page page, String scorePackageId, String prescriptionNo) {
		WmScorePackage scorePackage = wmScorePackageService.getById(scorePackageId);
		IPage<WmTask> prescriptionPage = wmTaskMapper.listTaskPrescriptionPage(page, scorePackageId, prescriptionNo);
		// 将数据子对象WmTaskContent分离出来，作为列表返回
		List<WmTaskContent> taskContentList = new ArrayList<>();
		List<WmTask> taskList = prescriptionPage.getRecords();
		if (CollectionUtil.isNotEmpty(taskList)) {
			taskList.stream().forEach(task -> {
				WmTaskContent wmTaskContent = task.getWmTaskContent();
				// WmTaskContent的id存的实际为wmTask的id
				wmTaskContent.setId(Integer.valueOf(task.getId()));
				// 如果是系统对接，则将药品temp10字段格式化
				if (scorePackage != null && "1".equals(scorePackage.getSourceType()) && StringUtils.isNotBlank(wmTaskContent
						.getTemp10())) {
					JSONArray drugJsonArr = JSON.parseArray(wmTaskContent.getTemp10());
					StringBuilder drugStr = new StringBuilder();
					for (int i = 0; i < drugJsonArr.size(); i++) {
						JSONObject jsonObj = drugJsonArr.getJSONObject(i);
						String oneDrug = jsonObj.getString("drug_name") + " " + jsonObj.getString("num");
						if (i % 2 == 0) {
							oneDrug = String.format("%-12s", oneDrug);
							drugStr.append(oneDrug);
						} else {
							drugStr.append(oneDrug + "\r\n");
						}
					}
					wmTaskContent.setTemp10(drugStr.toString());
				}
				taskContentList.add(task.getWmTaskContent());
			});
		}
		Page<WmTaskContent> taskContentPage = new Page<>();
		taskContentPage.setRecords(taskContentList);
		taskContentPage.setCurrent(prescriptionPage.getCurrent());
		taskContentPage.setSize(prescriptionPage.getCurrent());
		taskContentPage.setTotal(prescriptionPage.getTotal());
		taskContentPage.setPages(prescriptionPage.getPages());
		return taskContentPage;
	}

	/**
	 * 患者教育-处方列表
	 *
	 * @param scorePackageId 积分包id
	 * @param prescriptionNo 处方单编号
	 * @return 处方列表
	 */
	@Override
	public List<WmTask> listTaskPrescription(String scorePackageId, String prescriptionNo) {
		WmScorePackage scorePackage = wmScorePackageService.getById(scorePackageId);
		List<WmTask> taskList = wmTaskMapper.listTaskPrescription(scorePackageId, prescriptionNo);
		if (CollectionUtil.isNotEmpty(taskList)) {
			taskList.stream().forEach(task -> {
				WmTaskContent wmTaskContent = task.getWmTaskContent();
				// 如果是系统对接，则将药品temp10字段格式化
				if (scorePackage != null && "1".equals(scorePackage.getSourceType())
						&& JSONUtil.isJsonArray(wmTaskContent.getTemp10())) {
					JSONArray drugJsonArr = JSON.parseArray(wmTaskContent.getTemp10());
					StringBuilder drugStr = new StringBuilder();
					drugStr.append("\n");
					for (int i = 0; i < drugJsonArr.size(); i++) {
						JSONObject jsonObj = drugJsonArr.getJSONObject(i);
						String oneDrug = jsonObj.getString("drug_name") + " " + jsonObj.getString("num");
						if (i % 2 == 0) {
							oneDrug = String.format("%-12s", oneDrug);
							drugStr.append(oneDrug);
						} else {
							drugStr.append(oneDrug + "\n");
						}
					}
					wmTaskContent.setTemp10(drugStr.toString());
				}
			});
		}
		return taskList;
	}

	/**
	 * 患者教育-处方删除
	 *
	 * @param id 实际为WmTaskContent的id
	 * @return 是否成功状态
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteTaskPrescription(Integer id) {
		WmTask wmTask = this.getById(id);
		int taskTotal = wmTaskMapper.deleteById(id);
		int contentTotal = wmTaskContentMapper.deleteById(wmTask.getTaskContentId());
		return contentTotal > 0 && taskTotal > 0;
	}

	/**
	 * 证据链批量上传
	 *
	 * @param commonEvidenceDTOMap 通用证据链DTO map
	 * @param packageName          当前积分包名称
	 * @return 错误证据链编号
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> taskBatchImport(Map<String, List<CommonEvidenceDTO>> commonEvidenceDTOMap,
											   String packageName) {

		// 变量
		Map<String, String> errorMap = new HashMap<>();
		List<CommonEvidenceDTO> currentList = new ArrayList<>();

		// 获取操作员
		HnqzUser creator = SecurityUtils.getUser();

		// 业务值校验
		for (Map.Entry<String, List<CommonEvidenceDTO>> entry : commonEvidenceDTOMap.entrySet()) {
			checkoutCommonEvidenceDTOInfo(errorMap, entry.getValue(), currentList, entry.getKey(), creator, packageName);
		}

		// 上传结果
		if (errorMap.size() == 0) {
			submitEvidence(currentList);
		}

		return errorMap;
	}

	/**
	 * 检查证据链DTO
	 *
	 * @param errorMap           错误信息
	 * @param currentList        接受正确数据List
	 * @param sourceList         元数据
	 * @param packageName        积分包名称
	 * @param checkedPackageName 校验名称
	 * @param creator            创建人
	 */
	private void checkoutCommonEvidenceDTOInfo(Map<String, String> errorMap, List<CommonEvidenceDTO> sourceList,
											   List<CommonEvidenceDTO> currentList, String packageName,
											   HnqzUser creator, String checkedPackageName) {
		// 获取积分包并校验
		WmScorePackage scorePackage = wmScorePackageService.getOne(Wrappers.<WmScorePackage>lambdaQuery()
				.eq(WmScorePackage::getScorePackageName, packageName)
				.eq(WmScorePackage::getDeptId, creator.getDeptId())
		);

		String info = checkoutScorePackageInfo(scorePackage, checkedPackageName);
		if (StringUtils.isNotEmpty(info)) {
			log.error(info);
			List<String> idList = sourceList.stream().map(CommonEvidenceDTO::getId).collect(Collectors.toList());
			errorMap(errorMap, info, String.join(";", idList));

		} else {
			//校验创建人结算信息税邦云信息是否配置完全
			SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.<SysDeptSub>lambdaQuery()
					.eq(SysDeptSub::getDeptId, creator.getDeptId())
					.eq(SysDeptSub::getSubjectType, SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode())
					.eq(SysDeptSub::getEnableFlag, SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode())
			);
			if (null == sysDeptSub || StringUtils.isBlank(sysDeptSub.getAppId())) {
				List<String> idList = sourceList.stream().map(CommonEvidenceDTO::getId).collect(Collectors.toList());
				errorMap(errorMap, "人员所在机构未配置结算信息", String.join(";", idList));
			}

			// 校验证据链信息，并封装正确的
			List<CommonEvidenceDTO> evidenceDTOS = sourceList;
			int outCapacity = evidenceDTOS.size() - scorePackage.getTaskNum();
			ConcurrentHashMap<SysUser, Integer> indexMap = new ConcurrentHashMap(sourceList.size());
			ConcurrentHashMap<SysUser, BigDecimal> preUserSettleAmountMap = new ConcurrentHashMap(sourceList.size());
			evidenceDTOS.forEach(commonEvidenceDTO -> {
				// 校验结算用户是否存在
				SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery()
						.eq(SysUser::getUsername, commonEvidenceDTO.getUsername())
						.eq(SysUser::getDeptId, creator.getDeptId())
						.eq(SysUser::getRealname, commonEvidenceDTO.getRealName())
						.eq(SysUser::getDelFlag, DelEnum.NOT_DEL.val())
						.eq(SysUser::getLockFlag, LockEnum.UN_LOCK.val()));
				if (user == null) {
					log.error("用户不存在");
					errorMap(errorMap, "用户不存在", commonEvidenceDTO.getId());
					return;
				}

				// 校验任务数
				int index = 1;
				if (indexMap.containsKey(user)) {
					index = indexMap.get(user) + 1;
				}
				indexMap.put(user, index);
				List<WmTask> wmTasks = wmTaskMapper.selectList(Wrappers.<WmTask>lambdaQuery()
						.eq(WmTask::getScorePackageId, scorePackage.getId())
						.eq(WmTask::getTaskUserId, user.getUserId())
						.eq(WmTask::getDelFlag, DelEnum.NOT_DEL.val())
						.eq(WmTask::getEnableFlag, EnableEnum.ENABLE.val())
						// 审核通过
						.eq(WmTask::getTaskStatus, "3")
				);

				if (scorePackage.getTaskNum() - wmTasks.size() < index ){
					log.error("超出设定任务数");
					errorMap(errorMap, "超出设定任务数", commonEvidenceDTO.getId());
					return;
				}


				// 校验用户是否存在领包记录
				WmScorePackageStatus scorePackageStatus =
						wmScorePackageStatusService.getOne(Wrappers.<WmScorePackageStatus>lambdaQuery()
								.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
								.eq(WmScorePackageStatus::getUserId, user.getUserId())

						);
				String errorInfo = checkoutScorePackageStatusInfo(scorePackageStatus);
				if (StringUtils.isNotEmpty(errorInfo)) {
					log.error(errorInfo);
					errorMap(errorMap, errorInfo, commonEvidenceDTO.getId());
					return;
				}

				// 校验结算金额 0.5~2
				double min = new BigDecimal(scorePackage.getScore())
						.divide(new BigDecimal(scorePackage.getTaskNum()),2,RoundingMode.HALF_EVEN)
						.multiply(new BigDecimal("0.5"))
						.setScale(2, RoundingMode.HALF_EVEN)
						.doubleValue();
				double max = new BigDecimal(scorePackage.getScore())
						.divide(new BigDecimal(scorePackage.getTaskNum()),2,RoundingMode.HALF_EVEN)
						.multiply(new BigDecimal("2.0"))
						.setScale(2, RoundingMode.HALF_EVEN)
						.doubleValue();
				double amount = commonEvidenceDTO.getAmount().doubleValue();

				if (amount < min || amount > max) {
					log.error("结算金额不在范围内, min:[{}], max:[{}], amount:[{}]", min, max, amount);
					errorMap(errorMap, "结算金额不在范围内", commonEvidenceDTO.getId());
					return;
				}

				// 校验结算限制
				BigDecimal tmp = commonEvidenceDTO.getAmount();
				if (preUserSettleAmountMap.containsKey(user)) {
					tmp = tmp.add(preUserSettleAmountMap.get(user));
				}
				preUserSettleAmountMap.put(user, tmp);

				errorInfo = checkoutSettleLimit(user, sysDeptSub.getLimitAmount(), tmp);
				if (StringUtils.isNotEmpty(errorInfo)) {
					log.error(errorInfo);
					errorMap(errorMap, errorInfo, commonEvidenceDTO.getId());
					return;
				}

				// 获取发票类目
				InvoiceInfo invoiceInfo = InvoiceInfo.resolveByCategory(commonEvidenceDTO.getInvoiceCategory());

				if (invoiceInfo == null) {
					log.error("发票类目不存在");
					errorMap(errorMap, "发票类目不存在", commonEvidenceDTO.getId());
					return;
				}

				commonEvidenceDTO.setInvoiceType(invoiceInfo.getTypeId());
				// 添加正确的数据
				commonEvidenceDTO.setCreatorId(creator.getId());
				commonEvidenceDTO.setDeptId(creator.getDeptId());
				commonEvidenceDTO.setScorePackage(scorePackage);
				commonEvidenceDTO.setSysUser(user);
				currentList.add(commonEvidenceDTO);
			});
		}
	}

	/**
	 * 校验结算限制
	 *
	 * @param user         被校验者
	 * @param limitAmount  限制金额
	 * @param settleAmount 本次上传证据链累计金额
	 * @return 校验错误信息，如果没有错误返回{@code null}
	 */
	private String checkoutSettleLimit(SysUser user, BigDecimal limitAmount, BigDecimal settleAmount) {

		String info = null;

		SettleAmountMonitorInput monitorInput = SettleAmountMonitorInput.fromIdCard(Collections.singletonList(user
				.getIdCardNumber()), null, SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		List<SettleAmountMonitorOutput> monitorOutputList = sysDeptSubService.getSettleAmountMonitor(monitorInput);

		SettleAmountMonitorInput deptMonitorInput = SettleAmountMonitorInput.fromUserId(Collections.singletonList(String
				.valueOf(user.getUserId())), null, SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		List<SettleAmountMonitorOutput> deptAmountMonitor = sysDeptSubService.getDeptAmountMonitor(deptMonitorInput);

		SettleAmountMonitorOutput monitorOutput = monitorOutputList.stream().filter(item -> item.getIdCardNumber()
				.equals(user.getIdCardNumber())).findFirst().orElse(null);

		SettleAmountMonitorOutput deptMonitorOutput = deptAmountMonitor.stream().filter(item -> item.getUserId()
				.equals(String.valueOf(user.getUserId()))).findFirst().orElse(null);

		MonitoringIndicator monitoringIndicator = monitoringIndicatorService.getBySubType(SubjectTypeEnum.TYPE_SHUIBANGYUN
				.getCode());
		BigDecimal monitoringLimit = monitoringIndicator.getLimitAmount();
		BigDecimal monitorAmount = settleAmount;
		BigDecimal deptMonitorAmount = settleAmount;
		if (null != monitorOutput) {
			monitorAmount = monitorAmount.add(monitorOutput.getTotalAmount());
		}
		if (null != deptMonitorOutput) {
			deptMonitorAmount = deptMonitorAmount.add(deptMonitorOutput.getTotalAmount());
		}
		if (null != limitAmount) {
			if (deptMonitorAmount.compareTo(limitAmount) > 0) {
				info = "超过当月限额";
			}
		}
		if (null != monitoringLimit) {
			if (monitorAmount.compareTo(monitoringLimit) > 0) {
				info = "超过结算渠道限额";
			}
		}
		return info;
	}

	/**
	 * 积分包信息校验
	 *
	 * @param scorePackage       积分包
	 * @param checkedPackageName 校验的积分包名称
	 * @return 校验结果
	 */
	private String checkoutScorePackageInfo(WmScorePackage scorePackage, String checkedPackageName) {
		if (null == scorePackage) {
			log.error("积分包不存在");
			return "积分包不存在";
		}

		// 校验是否禁止多包上传
		if (StringUtils.isNotEmpty(checkedPackageName) && !scorePackage.getScorePackageName()
				.equals(checkedPackageName)) {
			log.error("禁止多包上传");
			return "禁止多包上传";
		}

		if (StringUtils.isEmpty(scorePackage.getProjectNum())) {
			log.error("项目编号为空");
			return "项目编号为空";
		}

		if ("1".equals(scorePackage.getEnableFlag())) {
			log.error("积分包已终止");
			return "积分包已终止";
		}

		if (!"0".equals(scorePackage.getEnableType())) {
			log.error("积分包剩余积分值已收回");
			return "积分包剩余积分值已收回";
		}

		if ("1".equals(scorePackage.getDelFlag())) {
			log.error("积分包已删除");
			return "积分包已删除";
		}
		return null;
	}

	/**
	 * 封装错误信息
	 *
	 * @param errorMap 记录错误信息map
	 * @param key      原因
	 * @param idStr    错误id
	 */
	private void errorMap(Map<String, String> errorMap, String key, String idStr) {
		if (errorMap.containsKey(key)) {
			String val = errorMap.get(key);
			idStr = String.join(";", val, idStr);
		}
		errorMap.put(key, idStr);
	}


	/**
	 * 校验领包记录
	 *
	 * @param scorePackageStatus 领包记录
	 * @return 校验信息
	 */
	private String checkoutScorePackageStatusInfo(WmScorePackageStatus scorePackageStatus) {

		if (scorePackageStatus == null) {
			log.error("领包记录不存在");
			return "领包记录不存在";
		}

		if (!"2".equals(scorePackageStatus.getStatus())) {
			log.error("领包记录记录审核状态不正确:{}", scorePackageStatus.getStatus());
			return "领包记录审核状态不正确";
		}

		if (!"0".equals(scorePackageStatus.getDelFlag())) {
			log.error("领包记录记录已被删除");
			return "领包记录记录已被删除";
		}

		if (!"0".equals(scorePackageStatus.getEnableFlag())) {
			log.error("领包记录记录已被禁用");
			return "领包记录记录已被禁用";
		}

		if ("0".equals(scorePackageStatus.getTaskAddFlag())) {
			log.error("领包记录记录不允许新增任务");
			return "领包记录记录不允许新增任务";
		}

		if (StringUtils.isEmpty(scorePackageStatus.getUserScore())) {
			log.error("领包记录用户积分值不存在");
			return "领包记录用户积分值不存在";
		}

		return null;
	}


	/**
	 * 提交结算
	 *
	 * @param commonEvidenceDTOList 通用证据链列表
	 */
	private void submitEvidence(List<CommonEvidenceDTO> commonEvidenceDTOList) {

		Assert.notEmpty(commonEvidenceDTOList, "证据链不能为空");

		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDateTime now = LocalDateTime.now();

		// 校验证据链列表信息，并记录正确信息
		for (CommonEvidenceDTO evidenceDTO : commonEvidenceDTOList) {

			// 封装合法证据链
			WmTask task = new WmTask();
			// 获取任务类型id
			task.setTaskTypeId(wmScoreTaskTypeService.selectByScoreId(evidenceDTO.getScorePackage()).get(0));
			task.setTaskUsername(evidenceDTO.getUsername());
			task.setScorePackageId(evidenceDTO.getScorePackage().getId());
			task.setTaskUserId(String.valueOf(evidenceDTO.getSysUser().getUserId()));
			task.setDeptId(evidenceDTO.getScorePackage().getDeptId());
			task.setDrugEntId(evidenceDTO.getScorePackage().getDrugEntId());
			task.setLookintoDate(now);
			task.setCreateTime(now);
			task.setTaskStatus("3");
			task.setDelFlag("0");
			task.setEnableFlag("0");
			task.setTaskFrom("2");
			task.setScore(evidenceDTO.getAmount().multiply(BigDecimal.valueOf(100)).intValue());
			// task.setReportDrugApprovalStatus("0");
			// task.setReportOneApprovalStatus("0");
			// task.setReportSecondApprovalStatus("0");

			WmTaskContent taskContent = new WmTaskContent();
			taskContent.setTemp1(evidenceDTO.getWorkstation());
			taskContent.setTemp2(evidenceDTO.getSubjectNum());
			taskContent.setTemp3(evidenceDTO.getScorePackage().getProjectNum());
			taskContent.setTemp4(evidenceDTO.getVisitStage());
			taskContent.setTemp5(evidenceDTO.getAuditStatus());
			taskContent.setTemp6(evidenceDTO.getComment());
			taskContent.setTemp7(df.format(evidenceDTO.getPassingTime()));
			taskContent.setTemp8(df.format(evidenceDTO.getUploadTime()));
			taskContent.setTemp9(null);
			taskContent.setTemp10(evidenceDTO.getTargetUsername());
			taskContent.setTemp11(evidenceDTO.getAuditor());
			taskContent.setTemp12(evidenceDTO.getLogs());
			taskContent.setTemp13(String.valueOf(evidenceDTO.getFile().getId()));
			taskContent.setTemp30(task.getTaskTypeId());
			taskContent.setTemp32(evidenceDTO.getScorePackage().getId());
			wmTaskContentMapper.insert(taskContent);
			task.setWmTaskContent(taskContent);
			task.setTaskContentId(String.valueOf(taskContent.getId()));
			wmTaskMapper.insert(task);

			// 提交结算
			WmScorePackageSettleNote note = new WmScorePackageSettleNote();
			note.setInvoiceType(evidenceDTO.getInvoiceType());
			note.setCategoryName(evidenceDTO.getInvoiceCategory());
			note.setPackageId(evidenceDTO.getScorePackage().getId());
			note.setCreateTime(now);
			note.setIdCardNumber(evidenceDTO.getSysUser().getIdCardNumber());
			note.setSettleAmount(evidenceDTO.getAmount());

			note.setUserId(String.valueOf(evidenceDTO.getSysUser().getUserId()));
			note.setSubType(ChannelEnum.TAX_HELPER.val());
			// 申请结算
			note.setSettleNoteStatus(9);
			note.setSubTime(now);
			String settleNo = UUID.randomUUID().toString().replace("-", "");
			note.setSettleNo(settleNo);
			note.setTaskId(task.getId());
			wmScorePackageSettleNoteService.save(note);
		}
	}

	/**
	 * 查询调查信息审核列表
	 *
	 * @param wmTask
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Override
	public IPage<WmTask> listInfoAudit(Page page, WmTask wmTask, LocalDateTime startDate, LocalDateTime endDate) {
		return wmTaskMapper.listInfoAudit(page, wmTask, startDate, endDate);
	}

	/**
	 * 查询同一家医院一个月做的任务次数
	 *
	 * @param hospitalId 医院id
	 * @return
	 */
	@Override
	public List<WmTask> listCurrentMonthHospitalTask(String hospitalId) {
		return wmTaskMapper.listCurrentMonthHospitalTask(hospitalId);
	}

	/**
	 * 查询会议任务个数
	 *
	 * @param taskTypeList 任务类型列表
	 * @param taskUserId 用户id
	 * @param startTime 会议时间范围-开始
	 * @param endTime 会议时间范围-结束
	 * @return 会议任务个数
	 */
	@Override
	public Long countMeetingTask(List<String> taskTypeList, String taskUserId, LocalDateTime startTime, LocalDateTime endTime) {
		return wmTaskMapper.countMeetingTask(taskTypeList, taskUserId, startTime, endTime);
	}
}
