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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
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.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.google.common.collect.ImmutableMap;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDeptRelation;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDictItem;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.api.vo.UserVO;
import com.qunzhixinxi.hnqz.admin.api.vo.WmScorePackageVO;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageApiOutput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageSettleInput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageSettleOutput;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.ReportEnum;
import com.qunzhixinxi.hnqz.admin.mapper.*;
import com.qunzhixinxi.hnqz.admin.service.*;
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 lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.qunzhixinxi.hnqz.admin.enums.ReportEnum.REPORT_STATUS_END;

/**
 * 积分包
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:42
 */
@Service
@AllArgsConstructor
public class WmScorePackageServiceImpl extends ServiceImpl<WmScorePackageMapper, WmScorePackage> implements WmScorePackageService {

	private final WmScorePackageMapper wmScorePackageMapper;
	private final SysDeptRelationMapper sysDeptRelationMapper;
	private final WmTaskMapper wmTaskMapper;
	private final SysDeptMapper sysDeptMapper;
	private final SysUserMapper sysUserMapper;
	private final WmScoreTaskTypeMapper wmScoreTaskTypeMapper;
	private final SysDeptService sysDeptService;
	private final WmDaAgentService wmDaAgentService;
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final WmTaskTypeMapper wmTaskTypeMapper;
	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmScorePackageSettleNoteMapper settleNoteMapper;
	private final WmDaDrugEntDrugtableService wmDaDrugEntDrugtableService;
	private final WmReportMapper wmReportMapper;
	private final SysDictItemService sysDictItemService;

	@Override
	public List<WmScorePackage> listWmScorePackageAndTask(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTask(wmScorePackage, new DataScope());
	}

	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskExt(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskExt(wmScorePackage);
	}

	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskExtOld(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskExtOld(wmScorePackage);
	}

	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskExt2(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskExt2(wmScorePackage);
	}


	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskExt2Old(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskExt2Old(wmScorePackage);
	}

	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskLevel1(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskLevel1(wmScorePackage, new DataScope());
	}

	@Override
	public List<WmScorePackage> listWmScorePackageAndTaskLevel3(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.listWmScorePackageAndTaskLevel3(wmScorePackage, new DataScope());
	}

	@Override
	public List<WmScorePackage> pageList(QueryWrapper<WmScorePackage> wrappers) {
		return wmScorePackageMapper.selectListByScope(wrappers, new DataScope());
	}

	@Override
	public String getPackageScoreEntByTaskInfo(WmScorePackage wmScorePackage) {
		String deptId = "";
		String userId = "";

		if (null == SecurityUtils.getUser() || null != SecurityUtils.getUser().getDeptId()) {

			if (null != wmScorePackage.getXxdbId() && wmScorePackage.getXxdbId().length() > 1) {
				userId = wmScorePackage.getXxdbId();
			}

			if (null != wmScorePackage.getZbId() && wmScorePackage.getZbId().length() > 1) {
				userId = wmScorePackage.getZbId();
			}

			SysUser sysUser = sysUserMapper.selectById(wmScorePackage.getXxdbId());
			if (null != sysUser) {
				deptId = sysUser.getDeptId() + "";
			} else {
				sysUser = sysUserMapper.selectById(wmScorePackage.getZbId());
				if (null != sysUser) {
					deptId = sysUser.getDeptId() + "";
				} else {
					return "-1000";
				}
			}


		} else {
			deptId = SecurityUtils.getUser().getDeptId() + "";
		}


		SysDept sysDept = sysDeptMapper.selectById(deptId);
		if (sysDept.getLevel() == 3) {
			return null;
		}
		wmScorePackage.setXxdbId(null);
		wmScorePackage.setZbId(null);

		wmScorePackage.setTypeid("2");
		wmScorePackage.setLevel1Id(sysDept.getLevel2Id() + "");
		wmScorePackage.setAgentTypeId("2");
		wmScorePackage.setDelFlag("0");
		wmScorePackage.setEnableFlag("0");
		List<WmScorePackage> wmScorePackages = super.list(Wrappers.query(wmScorePackage)
				.lambda()
				.isNotNull(WmScorePackage::getLevel2Id)
				.ne(WmScorePackage::getLevel2Id, "")
				.orderByDesc(WmScorePackage::getIsConduct)
				.orderByAsc(WmScorePackage::getReceiveDate));

		if (wmScorePackages.size() > 0) {
			for (int i = 0; i < wmScorePackages.size(); i++) {
				WmTask wmTask = new WmTask();
				wmTask.setScorePackageLevel1Id(wmScorePackages.get(i).getId());

				List<String> taskStatus = new ArrayList<>();
				taskStatus.add("5");
				//TODO 需要确认已审核的逻辑
				List<WmTask> wmTaskList = wmTaskMapper.selectList(Wrappers.query(wmTask)
						.lambda()
						.notIn(WmTask::getTaskStatus, taskStatus));
				int socre = 0;
				for (WmTask wmT :
						wmTaskList) {
					if (null != wmT.getScore()) {
						socre += wmT.getScore();
					}
				}
				if (socre <= wmScorePackages.get(i).getScore()) {
					return wmScorePackages.get(i).getId();
				}
			}

		}
		return null;
	}


	@Override
	public WmScorePackage getPackageScoreByTaskInfo(WmScorePackage wmScorePackage) {
		wmScorePackage.setEnableFlag("0");
		wmScorePackage.setDelFlag("0");
		List<WmScorePackage> wmScorePackages = super.list(Wrappers.query(wmScorePackage).lambda().
				orderByDesc(WmScorePackage::getIsConduct).orderByAsc(WmScorePackage::getReceiveDate));

		if (wmScorePackages.size() > 0) {
			for (int i = 0; i < wmScorePackages.size(); i++) {
				WmTask wmTask = new WmTask();
				/**
				 * 2020-12-21
				 * 只查生效的任务
				 * 0-生效 1-无效  9-待审核
				 */
				wmTask.setRealFlag("0");
				wmTask.setScorePackageId(wmScorePackages.get(i).getId());

				List<String> taskStatus = new ArrayList<>();
				taskStatus.add("5");
				//TODO 需要确认已审核的逻辑
				List<WmTask> wmTaskList = wmTaskMapper.selectList(Wrappers.query(wmTask).lambda()
						.notIn(WmTask::getTaskStatus, taskStatus)
						.orderByAsc(WmTask::getCreateTime)
				);
				int socre = 0;
				for (WmTask wmT :
						wmTaskList) {
					if (null != wmT.getScore()) {
						socre += wmT.getScore();
					}
				}
				if (socre < wmScorePackages.get(i).getScore()) {
					return wmScorePackages.get(i);
				}
			}

		}
		return null;
	}

	@Override
	public List<WmScorePackage> listPage(Page page, WmScorePackage wmScorePackage) {
		return null;
	}

	public IPage<WmScorePackage> getExportPackageTotalList1(Page page, WmScorePackage wmScorePackage) {
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		return wmScorePackageMapper.getExportPackageTotalList1(page, wmScorePackage);
	}

	public IPage<WmScorePackage> getExportPackageTotalList(Page page, WmScorePackage wmScorePackage) {
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		return wmScorePackageMapper.getExportPackageTotalList(page, wmScorePackage);
	}

	public IPage<Map<String, Object>> getPlatTotalData(Page page, WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.getPlatTotalData(page, wmScorePackage);
	}

	@Override
	public IPage<Map<String, Object>> selectWmScorePackageList(Page page, WmScorePackage wmScorePackage) {
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		return wmScorePackageMapper.selectWmScorePackageList(page, wmScorePackage);
	}

	@Override
	public R updateByIdWithType(WmScorePackageVO wmScorePackageVO) {
		WmScorePackage wmScorePackage = new WmScorePackage();

		wmScorePackage.setId(wmScorePackageVO.getId());
		if ("3".equals(wmScorePackageVO.getFormType())) {
			wmScorePackage.setInvoiceCategory(wmScorePackageVO.getInvoiceCategory());
		} else if ("1".equals(wmScorePackageVO.getFormType())) {
			BigDecimal settleAmount = wmScorePackageVO.getScore()
					.multiply(wmScorePackageVO.getDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP);
			wmScorePackage.setDiscount(wmScorePackageVO.getDiscount());
			wmScorePackage.setSettleAmount(settleAmount);
		} else if ("2".equals(wmScorePackageVO.getFormType())) {
			BigDecimal discount = wmScorePackageVO.getSettleAmount()
					.divide(wmScorePackageVO.getScore(), 2, BigDecimal.ROUND_HALF_UP);
			wmScorePackage.setDiscount(discount);
			wmScorePackage.setSettleAmount(wmScorePackageVO.getSettleAmount());
		}

		wmScorePackageMapper.updateById(wmScorePackage);
		return R.ok();
	}

	@Override
	public WmScorePackage selectByPackage(String id) {
		return wmScorePackageMapper.selectByPackage(id);
	}

	@Override
	public List<WmScorePackage> selectLists(WmScorePackage wmScorePackage) {
		wmScorePackage.getRelationScoreId();
		return wmScorePackageMapper.selectLists(wmScorePackage);
	}

	@Override
	public Map<String, Object> selectSettleStatus(WmScorePackage wmScorePackage) {
		wmScorePackage.setRelationScoreId(wmScorePackage.getId());
		List<WmScorePackage> wmScorePackageList = wmScorePackageMapper.selectLists(wmScorePackage);
		Map<String, Object> totalMap = new HashMap<>();
		List<Integer> list = new ArrayList<>();
		if (wmScorePackageList.size() > 0) {
			List<String> ids2 = wmScorePackageList.stream().map(p -> p.getId()).collect(Collectors.toList());
			for (String id : ids2) {
				WmScorePackage wmScorePackage2 = new WmScorePackage();
				wmScorePackage2.setRelationScoreId(id);
				List<WmScorePackage> wmScorePackageList2 = wmScorePackageMapper.selectLists(wmScorePackage2);
				List<String> ids4 = wmScorePackageList2.stream().map(p -> p.getId()).collect(Collectors.toList());
				if (wmScorePackageList2.size() > 0) {
					for (String id2 : ids4) {
						WmScorePackage wmScorePackage1 = new WmScorePackage();
						wmScorePackage1.setId(id2);
						wmScorePackage1.setSettleStatus(1);
						List<Map<String, Object>> wmScorePackageList1 = wmScorePackageMapper.selectListById(wmScorePackage1);
						if (wmScorePackageList1.size() > 0) {
							Integer total = 0;
							Integer total1 = 0;
							for (Map<String, Object> map : wmScorePackageList1) {
								if (null != map.get("score")) {
									total += Integer.parseInt(map.get("score") + "");
								}
								list.add(total);
							}
							for (int i = 0; i < list.size(); i++) {
								total1 += list.get(i);
							}
							totalMap.put("score", total1);
						}
					}
				}
				WmScorePackage wmScorePackage1 = new WmScorePackage();
				wmScorePackage1.setId(id);
				wmScorePackage1.setSettleStatus(1);
				List<Map<String, Object>> wmScorePackageList1 = wmScorePackageMapper.selectListById(wmScorePackage1);
				if (wmScorePackageList1.size() > 0) {
					Integer total = 0;
					Integer total1 = 0;
					for (Map<String, Object> map : wmScorePackageList1) {
						if (null != map.get("score")) {
							total += Integer.parseInt(map.get("score") + "");
						}
						list.add(total);
					}
					for (int i = 0; i < list.size(); i++) {
						total1 += list.get(i);
					}
					totalMap.put("score", total1);
				}
			}
		} else if (wmScorePackageList.size() == 0) {
			WmScorePackage wmScorePackage1 = new WmScorePackage();
			wmScorePackage1.setId(wmScorePackage.getId());
			wmScorePackage1.setSettleStatus(1);
			List<Map<String, Object>> wmScorePackageList1 = wmScorePackageMapper.selectListById(wmScorePackage1);
			if (wmScorePackageList1.size() > 0) {
				Integer total = 0;
				Integer total1 = 0;

				for (Map<String, Object> map : wmScorePackageList1) {
					if (null != map.get("score")) {
						total += Integer.parseInt(map.get("score") + "");
					}
					list.add(total);
				}
				for (int i = 0; i < list.size(); i++) {
					total1 += list.get(i);
				}
				totalMap.put("score", total1);

			}
		}

		return totalMap;
	}

	@Override
	public List<SysDept> selectSendPackageDeptId(WmScorePackage wmScorePackage) {
		SysDeptRelation sysDeptRelation = new SysDeptRelation();
		sysDeptRelation.setDescendant(SecurityUtils.getUser().getDeptId());
		List<SysDeptRelation> sysDeptRelationList = sysDeptRelationMapper.selectByDescendantList(sysDeptRelation);
		List<Integer> ids = sysDeptRelationList.stream().map(p -> p.getAncestor()).collect(Collectors.toList());
		List<SysDept> list = new ArrayList<>();
		for (Integer id : ids) {
			SysDept sysDept = sysDeptService.getById(id);
			list.add(sysDept);
		}
		return list;
	}

	@Override
	public List<WmScorePackage> selectWmScorePackageByCode(Map<String, Object> map) {

		return wmScorePackageMapper.selectWmScorePackageByCode(map);
	}

	@Override
	public WmScorePackage selectWmScorePackage(WmScorePackage wmScorePackage) {
		wmScorePackage = wmScorePackageMapper.selectByScoreId(wmScorePackage.getScoreId());
		if (wmScorePackage.getRelationScoreId() == null || wmScorePackage.getRelationScoreId().equals("")) {
			wmScorePackage.setRelationScoreId("-1");
		}
		WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
		if (wmScorePackage.getRelationScoreId().equals("-1")) {
			wmScoreTaskType.setScoreId(wmScorePackage.getId());
		} else {
			wmScoreTaskType.setScoreId(wmScorePackage.getRelationScoreId());
		}
		List<WmScoreTaskType> taskTypeList = wmScoreTaskTypeMapper.listWmScoreTaskType(wmScoreTaskType);
		Set taskTypeSet = taskTypeList.stream().map(WmScoreTaskType::getTaskTypeId).collect(Collectors.toSet());
		wmScorePackage.setTaskTypeSet(taskTypeSet);
		return wmScorePackage;
	}

	// @Override
	// public IPage<WmScorePackage> selectWmScorePackageLists(Page page, WmScorePackage wmScorePackage) {
	// 	OrderItem orderItem = new OrderItem();
	// 	orderItem.setColumn("create_time");
	// 	orderItem.setAsc(false);
	// 	page.addOrder(orderItem);
	//
	// 	SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
	// 	wmScorePackage.setSendPackageDeptId(String.valueOf(sysDept.getDeptId()));
	// 	return wmScorePackageMapper.selectWmScorePackageLists(page, wmScorePackage);
	// }

	@Override
	public IPage<WmScorePackage> selectWmScorePackageLists(Page page, WmScorePackage wmScorePackage) {
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);

		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		wmScorePackage.setSendPackageDeptId(String.valueOf(sysDept.getDeptId()));
		return wmScorePackageMapper.selectWmScorePackageLists(page, wmScorePackage);
	}

	@Override
	public WmScorePackage selectKfpjf(String scoreId) {
		return wmScorePackageMapper.selectByScoreId(scoreId);
	}

	@Override
	public WmScorePackage selectKfpjfs(String scoreName) {
		return wmScorePackageMapper.selectByScoreIds(scoreName);
	}

	@Override
	public WmScorePackage selectWmScorePackageById(String relationScoreId) {
		return wmScorePackageMapper.selectByRelationScoreId(relationScoreId);
	}

	@Override
	public List<WmScorePackage> selectRelationScoreId(String relationScoreId) {
		return wmScorePackageMapper.selectRelationScoreId(relationScoreId);
	}

	@Override
	public List<WmScorePackage> selectByReRelatedService(WmScorePackage wmScorePackage) {
		return wmScorePackageMapper.selectByReRelatedService(wmScorePackage);
	}

	/**
	 * 查询关联积分包列表
	 *
	 * @param wmScorePackage
	 * @return
	 */
	@Override
	public R getRelationScoreList(WmScorePackage wmScorePackage) {
		SysDept relatedService = new SysDept();
		if (null != wmScorePackage.getRelatedService()) {
			relatedService = sysDeptMapper.selectById(wmScorePackage.getRelatedService());
		}
		//查询分配给当前用户机构的积分包，deptid为当前用户，而且typeid=1或2
		String deptId = SecurityUtils.getUser().getDeptId() + "";
		wmScorePackage.setDeptId(deptId);
		wmScorePackage.setTypeid("0,1,2");
		wmScorePackage.setSendPackageDeptId(wmScorePackage.getRelatedService());
		List<WmScorePackage> packageList = wmScorePackageMapper.getScorePackagekfpjf(wmScorePackage);

		for (WmScorePackage wmScorePackage1 : packageList) {
			List<WmScoreTaskType> taskTypelist = wmScoreTaskTypeMapper.getScoreTaskTypeByScoreId(wmScorePackage1.getId());
			wmScorePackage1.setTaskTypeList1(taskTypelist);
			Set taskTypeSet = taskTypelist.stream().map(WmScoreTaskType::getTaskTypeId).collect(Collectors.toSet());
			wmScorePackage1.setTaskTypeSet(taskTypeSet);
		}

		//一个机构同时是一级cso和二级cso时，可以自己给自己发包
		if (null != relatedService.getLevel() && relatedService.getLevel() == 4) {
			List<SysDept> deptList = sysDeptMapper.getAllParentDept(relatedService);//所有的上级机构
			List<Integer> levels = deptList.stream().map(SysDept::getLevel).collect(Collectors.toList());
			if (levels.contains(2)) {
				relatedService.setLevel(3);
			}
		}

		if (relatedService.getDeptId() != null) {
			if (null != relatedService.getLevel() && relatedService.getLevel() != 4) {
				SysDept sysDept = sysDeptMapper.selectById(deptId);
				if (wmScorePackage.getRelatedService().equals(sysDept.getDeptId() + "")) {
					//if(sysDept.getDeptId().equals(wmScorePackage.getRelatedService())){
					WmScorePackage wmScorePackage1 = new WmScorePackage();
					wmScorePackage1.setId("-1");
					wmScorePackage1.setScorePackageName("无");
					packageList.add(wmScorePackage1);
				}
			}
		} else {
			WmScorePackage wmScorePackage1 = new WmScorePackage();
			wmScorePackage1.setId("-1");
			wmScorePackage1.setScorePackageName("无");
			packageList.add(wmScorePackage1);
		}
		return R.ok(packageList);
	}


	/**
	 * 查询积分规则ruleID
	 *
	 * @param wmDaDrugEnt
	 * @param wmDaAgent
	 * @return
	 */
	public String queryRuleID(WmDaDrugEnt wmDaDrugEnt, WmDaAgent wmDaAgent) {
		LambdaQueryWrapper<WmTaskType> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(WmTaskType::getDelFlag, "0");
		queryWrapper1.eq(WmTaskType::getEnableFlag, "0");
		if (wmDaDrugEnt != null) {
			queryWrapper1.eq(WmTaskType::getDeptId, wmDaDrugEnt.getDeptId());
			queryWrapper1.eq(WmTaskType::getDurgentId, wmDaDrugEnt.getId());
		} else if (wmDaAgent != null) {
			queryWrapper1.eq(WmTaskType::getLevel1Id, wmDaAgent.getId());
			queryWrapper1.eq(WmTaskType::getDeptId, wmDaAgent.getDeptId());
			queryWrapper1.isNull(WmTaskType::getDurgentId);
		}
		List<WmTaskType> typeList = wmTaskTypeMapper.selectList(queryWrapper1);
		if (typeList != null && typeList.size() > 0) {
			List<String> sList = typeList.stream().map(WmTaskType::getRuleId).collect(Collectors.toList());
			if (sList != null && sList.size() > 0) {
				return sList.get(0);
			}
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addWmScorePackage(WmScorePackage wmScorePackage) {
		HnqzUser currentUser = SecurityUtils.getUser();
		//判断名字不能重复
		if (null != wmScorePackage.getScorePackageName() && !"".equals(wmScorePackage.getScorePackageName())) {
			WmScorePackage wmScorePackage1 = new WmScorePackage();
			wmScorePackage1.setDelFlag("0");
			wmScorePackage1.setDeptId(currentUser.getDeptId() + "");
			wmScorePackage1.setScorePackageName(wmScorePackage.getScorePackageName());
			List<WmScorePackage> wmScorePackageList = this.list(Wrappers.query(wmScorePackage1));
			if (wmScorePackageList.size() > 0) {
				return R.failed("积分包名称已存在");
			}
		}
		if (wmScorePackage.getPackageType1().equals("1")) {//定额
			if (!StringUtil.isEmpty(wmScorePackage.getUserScore()) && wmScorePackage.getUserNum() > 0) {
				wmScorePackage.setScore(Integer.valueOf(wmScorePackage.getUserScore()) * wmScorePackage.getUserNum());
			}
		} else {
			if (!StringUtil.isEmpty(wmScorePackage.getUserScore())) {
				if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
					// 如果是患者教育，积分值转换为以'分'为单位保存
					int scoreFen = new BigDecimal(wmScorePackage.getUserScore()).multiply(new BigDecimal("100"))
							.intValue();
					wmScorePackage.setScore(scoreFen);
					wmScorePackage.setUserScore(String.valueOf(scoreFen));
				} else {
					wmScorePackage.setScore(Integer.valueOf(wmScorePackage.getUserScore()));
				}
			}
		}

		WmScorePackage relationScorePackage = new WmScorePackage();//关联积分包
		//判断预积分包值不能大于可分配积分值
		if (!StringUtil.isEmpty(wmScorePackage.getRelationScoreId()) && !wmScorePackage.getRelationScoreId()
				.equals("-1")) {
			WmScorePackage wmScorePackage1 = new WmScorePackage();
			wmScorePackage1.setId(wmScorePackage.getRelationScoreId());
			WmScorePackage wmScorePackage2 = wmScorePackageMapper.selectById(wmScorePackage1.getId());
			Integer kfpjf = 0;
			if (wmScorePackage2 != null) {
				kfpjf = wmScorePackage2.getKfpjf() == null ? 0 : wmScorePackage2.getKfpjf();
				if (kfpjf > 0 && wmScorePackage.getScore() > kfpjf) {
					return R.failed("预积分包值不能大于可分配积分值");
				}
				//更新可分配积分包值
				if (kfpjf >= wmScorePackage.getScore()) {
					relationScorePackage.setId(wmScorePackage.getRelationScoreId());
					relationScorePackage.setKfpjf(kfpjf - wmScorePackage.getScore());
				}
			}
//			List<WmScorePackage> packageList=wmScorePackageMapper.getScorePackagekfpjf(wmScorePackage1);
//			Integer kfpjf=0;
//			if(null!=packageList&&packageList.size()!=0){
//				kfpjf=packageList.get(0).getKfpjf();
//			}

		}

		//关联积分包为空时
		if (wmScorePackage.getRelationScoreId() == null || (wmScorePackage.getRelationScoreId() != null && wmScorePackage
				.getRelationScoreId()
				.equals("-1"))) {

			wmScorePackage.setRelationScoreId(null);
			SysDept dept = new SysDept();
			//关联积分包为空，需要判断是不是是不是药企
			if (wmScorePackage.getRelatedService() == null) {
				dept = sysDeptMapper.selectById(currentUser.getDeptId());
			} else {
				dept = sysDeptMapper.selectById(wmScorePackage.getRelatedService());
			}
			wmScorePackage.setSendPackageDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setDeptId(currentUser.getDeptId() + "");
			if (dept == null) {
				return R.failed("未查询到当前登陆人的");
			} else {
				if (dept.getLevel() == 2) {//药企
					WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getOne(Wrappers.<WmDaDrugEnt>lambdaQuery()
							.eq(WmDaDrugEnt::getDeptId, dept.getDeptId()));
					wmScorePackage.setDrugEntId(wmDaDrugEnt.getId() + "");
					wmScorePackage.setRuleId(this.queryRuleID(wmDaDrugEnt, null));
				} else if (dept.getLevel() == 3 || dept.getLevel() == 4) {//一级cso
					WmDaAgent wmDaAgent = wmDaAgentService.getOne(Wrappers.<WmDaAgent>lambdaQuery()
							.eq(WmDaAgent::getDeptId, dept.getDeptId()));
					wmScorePackage.setRuleId(this.queryRuleID(null, wmDaAgent));

				}
			}
			wmScorePackage.setBelongDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM")) + "");
		} else {
			WmScorePackage relationScore = this.getById(wmScorePackage.getRelationScoreId());
			if (relationScore == null) {
				return R.failed("未查询到关联积分包！");
			}
			wmScorePackage.setDrugEntId(relationScore.getDrugEntId());
			wmScorePackage.setRuleId(relationScore.getRuleId());
			wmScorePackage.setSendPackageDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setBelongDate(relationScore.getBelongDate());
		}
		wmScorePackage.setDelFlag("0");
		wmScorePackage.setEnableFlag("0");
		wmScorePackage.setPackageFinishStatus("0");
		// 数据来源类型（0-手动上传，1-系统对接）
		wmScorePackage.setSourceType("0");

		if ("3".equals(wmScorePackage.getTypeid())) {//全职学术推广员
			wmScorePackage.setIsReceive("1");//不允许接单
			wmScorePackage.setScorePackageStatus("3");//全职学术推广员不需要审核，所有状态直接是进行中
		} else if ("4".equals(wmScorePackage.getTypeid())) {//兼职学术推广员
			wmScorePackage.setIsReceive("0");//允许接单
			wmScorePackage.setScorePackageStatus("1");//已分派待申领
		}
		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
			// 患者教育，固定只能一人领取
			wmScorePackage.setUserNum(1);
		}
		wmScorePackage.setCreateUser(currentUser.getId());
		wmScorePackage.setCreateTime(LocalDateTime.now());
		boolean isAnswer = this.save(wmScorePackage);
		if (isAnswer) {

			//保存接单对象，全职学术推广员，允许选多个
			List<String> userList = wmScorePackage.getUserList();
			if (null != userList && userList.size() > 0) {
				List<WmScorePackageStatus> stuList = new ArrayList<>();
				for (String userId : userList) {
					WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
					wmScorePackageStatus.setUserId(userId);
					wmScorePackageStatus.setStatus("2");
					wmScorePackageStatus.setPackageId(wmScorePackage.getId());
					UserVO user = sysUserMapper.getUserVoById(Integer.valueOf(userId));
					wmScorePackageStatus.setDeptId(user.getDeptId() + "");
					if (wmScorePackage.getPackageType1().equals("1")) {//定额包
						wmScorePackageStatus.setUserScore(wmScorePackage.getScore() + "");
					} else {//定量包
						wmScorePackageStatus.setTaskNum(wmScorePackage.getTaskNum());
					}
					wmScorePackageStatus.setEnableFlag("0");
					wmScorePackageStatus.setDelFlag("0");
					wmScorePackageStatus.setCreateTime(LocalDateTime.now());
					wmScorePackageStatus.setCreateUser(currentUser.getId());
					stuList.add(wmScorePackageStatus);
				}
				wmScorePackageStatusService.saveBatch(stuList);
				wmScorePackage.setUserNum(userList.size());
				this.updateById(wmScorePackage);
			}
			//保存有效任务类型
			List<WmTaskTypeTree> tasktypeList = wmScorePackage.getTaskTypeList();

			if (null != tasktypeList && tasktypeList.size() > 0) {
				for (WmTaskTypeTree type : tasktypeList) {
					WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
					wmScoreTaskType.setScoreId(wmScorePackage.getId());
					wmScoreTaskType.setTaskTypeId(type.getTaskTypeId());
					wmScoreTaskType.setType(type.getType());
					wmScoreTaskTypeMapper.insert(wmScoreTaskType);
					if (null == type.getChildren()) {
						continue;
					}
					if (type.getChildren() != null || type.getChildren().size() > 0) {
						List<WmTaskTypeTree> childtasktypeList = type.getChildren();
						for (WmTaskTypeTree type1 : childtasktypeList) {
							WmScoreTaskType wmScoreTaskType1 = new WmScoreTaskType();
							wmScoreTaskType1.setScoreId(wmScorePackage.getId());
							wmScoreTaskType1.setType(type1.getType());
							wmScoreTaskType1.setTaskTypeId(type1.getTaskTypeId());
							wmScoreTaskTypeMapper.insert(wmScoreTaskType1);
						}
					}
				}
			} else {
				if (wmScorePackage.getPackageType1().equals("5") || wmScorePackage.getPackageType1().equals("4")
						|| wmScorePackage.getPackageType2().equals("2")) {
					//结算包
					WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
					wmScoreTaskType.setScoreId(wmScorePackage.getId());
					wmScoreTaskType.setTaskTypeId(wmScorePackage.getTaskTypeId());
					wmScoreTaskType.setType("2");
					wmScoreTaskTypeMapper.insert(wmScoreTaskType);
				}
			}

			//更新关联积分包可分配积分值
			if (!StringUtil.isEmpty(relationScorePackage.getId())) {
				this.updateById(relationScorePackage);
			}
		}
		return R.ok("新增成功");
	}

	/**
	 * 派工平台--分配积分 列表查询
	 *
	 * @param page
	 * @param wmScorePackage
	 * @return
	 */
	public R getScorePackagePage(Page page, WmScorePackage wmScorePackage) {

		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		wmScorePackage.setSendPackageDeptId(SecurityUtils.getUser().getDeptId() + "");
		if (StringUtil.isEmpty(wmScorePackage.getTypeid())) {
			wmScorePackage.setTypeid("3,4");
		}
		IPage<WmScorePackage> pages = wmScorePackageMapper.getScorePackageList(page, wmScorePackage);
		List<WmScorePackage> records = pages.getRecords();

		List<String> reportWaitingCheckStatus = Arrays.asList("0", "1");


		for (WmScorePackage wmScorePackage1 : records) {

			List<WmScorePackageSettleNote> list = settleNoteMapper.selectList(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, wmScorePackage1.getId()));
			if (CollectionUtil.isNotEmpty(list)) {
				wmScorePackage1.setNotifyDate(list.get(0).getNotifyTime());
			}

			if ("2".equals(wmScorePackage.getPackageType2())) {
				WmScorePackageSettleNote wsquery = new WmScorePackageSettleNote();
				wsquery.setPackageId(wmScorePackage1.getId());
				int wsNum = settleNoteMapper.selectCount(Wrappers.query(wsquery)
						.lambda().in(WmScorePackageSettleNote::getSettleNoteStatus, 2, 9));
				WmScorePackageSettleNote asquery = new WmScorePackageSettleNote();
				asquery.setPackageId(wmScorePackage1.getId());
				asquery.setSettleNoteStatus(1);
				int asNum = settleNoteMapper.selectCount(Wrappers.query(asquery));
				wmScorePackage1.setWsTaskNum(wsNum);
				wmScorePackage1.setAsTaskNum(asNum);
			}
			if (PackageTypeEnum.TYPE1_HCP_PACKAGE.getName().equals(wmScorePackage1.getPackageType1())) {
				// 如果是患者教育，则转换积分值 '分'-> '元'
				Integer score = wmScorePackage1.getScore();
				String userScore = wmScorePackage1.getUserScore();
				if (StringUtils.isNumeric(userScore)) {
					wmScorePackage1.setUserScore(String.format("%.2f", Integer.parseInt(userScore) / 100.0));
				}
			}

			if (wmScorePackage1.getYshtt() != null && wmScorePackage1.getYshtt() > 100) {
				// if (wmScorePackage.getScore().equals(wmScorePackage.getShtg()) && !wmScorePackage.getScore().equals(wmScorePackage.getYsh()) ) {
				wmScorePackage1.setYsh(wmScorePackage1.getScore());
				// }
				wmScorePackage1.setYshtt(100);
			}
			if (wmScorePackage1.getShbtgtt() != null && wmScorePackage1.getShbtgtt() > 100) {
				wmScorePackage1.setShbtgtt(100);
			}
			if (wmScorePackage1.getShtgtt() != null && wmScorePackage1.getShtgtt() > 100) {
				wmScorePackage1.setShtgtt(100);
			}
			List<WmScoreTaskType> taskTypelist = wmScoreTaskTypeMapper.getScoreTaskTypeByScoreId(wmScorePackage1.getId());
			if (taskTypelist != null && taskTypelist.size() > 0) {
				String taskTypes = taskTypelist.stream().map(
						WmScoreTaskType::getTaskTypeName).collect(Collectors.joining(","));
				wmScorePackage1.setTaskTypes(taskTypes);
			}

			WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
			wmScorePackageStatus.setPackageId(wmScorePackage1.getId());
			wmScorePackageStatus.setStatus("2");
			wmScorePackage1.setUserListNum(0);
			List<WmScorePackageStatus> staList = wmScorePackageStatusService.getByPackageId(wmScorePackageStatus);
			if (staList != null && staList.size() > 0) {
				List<String> userList = staList.stream()
						.map(WmScorePackageStatus::getUserId)
						.collect(Collectors.toList());
				wmScorePackage1.setUserList(userList);
				wmScorePackage1.setUserListNum(userList.size());
			}
			wmScorePackageStatus.setStatus("1");
			wmScorePackage1.setYjddsh(wmScorePackageStatusService.count(Wrappers.query(wmScorePackageStatus)));

			// 设置中止状态
			WmScorePackage.PackageStopStatus stopStatus;

			if (wmScorePackage1.getRelationScoreId() == null) {
				stopStatus = WmScorePackage.PackageStopStatus.ALL_IN;
			} else {
				List<WmTask> tasks = wmTaskMapper.selectList(Wrappers.<WmTask>lambdaQuery()
						.eq(WmTask::getScorePackageId, String.valueOf(wmScorePackage1.getId())));

				//统计发包方还未审核的
				long drugNeedToCheckCount = tasks.stream()
						.filter(t -> "3".equals(t.getTaskStatus()) && "2".equals(t.getReportOneApprovalStatus()))
						.count();

				// 统计cso未审核 和审核通过的还未提交到药企的任务数
				long csoNeedToCheckCount = tasks.stream()
						.filter(t -> "2".equals(t.getTaskStatus()) ||
								("3".equals(t.getTaskStatus()) && reportWaitingCheckStatus.contains(t.getReportOneApprovalStatus())))
						.count();

				// 如果有发包方未审核的不能中止
				if (drugNeedToCheckCount != 0L) {
					stopStatus = WmScorePackage.PackageStopStatus.NOTHING;
				} else if (csoNeedToCheckCount != 0L) {
					// 如果有cso未审核的提示信息
					stopStatus = WmScorePackage.PackageStopStatus.REMAIN_MSG;
				} else {
					// 无提示信息
					stopStatus = WmScorePackage.PackageStopStatus.REMAIN;
				}
			}

			wmScorePackage1.setStopStatus(stopStatus);
		}
		return R.ok(pages);
	}


	/**
	 * 终止任务
	 *
	 * @param wmScorePackage
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateEnable(WmScorePackage wmScorePackage) {
		String enableType = wmScorePackage.getEnableType();
		wmScorePackage = this.getById(wmScorePackage.getId());
		if (null == wmScorePackage) {
			return R.ok("未查询到积分包信息！");
		}
		wmScorePackage.setEnableType(enableType);
		wmScorePackage.setPackageStatus(wmScorePackage.getPackageStatus());
		WmTask wmTask = new WmTask();
		wmTask.setScorePackageId(wmScorePackage.getId());
		//wmTask.setRealFlag("0");
		List<WmTask> taskList = wmTaskMapper.selectList(Wrappers.query(wmTask));
		//将所有未接单审核的，改成审核不通过
		wmScorePackageStatusService.update(new WmScorePackageStatus(),
				Wrappers.<WmScorePackageStatus>lambdaUpdate()
						.eq(WmScorePackageStatus::getPackageId, wmScorePackage.getId())
						.eq(WmScorePackageStatus::getStatus, "1")
						.set(WmScorePackageStatus::getStatus, "3")
						.set(WmScorePackageStatus::getTaskAddFlag, "0")
		);
		//查询所有接单审核通过的
		LambdaQueryWrapper<WmScorePackageStatus> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(WmScorePackageStatus::getPackageId, wmScorePackage.getId());
		queryWrapper.eq(WmScorePackageStatus::getDelFlag, "0");
		queryWrapper.in(WmScorePackageStatus::getStatus, "2");
		List<WmScorePackageStatus> scorestatusList = wmScorePackageStatusService.list(queryWrapper);
		//全部终止，终止任务和积分包
		if ("1".equals(enableType)) {
			wmScorePackage.setScorePackageStatus("6");//已终止
			//更新结单
			if (null != scorestatusList && scorestatusList.size() > 0) {
				wmScorePackageStatusService.update(new WmScorePackageStatus(),
						Wrappers.<WmScorePackageStatus>lambdaUpdate()
								.eq(WmScorePackageStatus::getPackageId, wmScorePackage.getId())
								.set(WmScorePackageStatus::getTaskAddFlag, "0")
								.set(WmScorePackageStatus::getEnableFlag, "1")
								.set(WmScorePackageStatus::getEnableType, "1")
				);
			}
			wmScorePackage.setEnableFlag("1");
			this.updateById(wmScorePackage);
			if (null != taskList && taskList.size() > 0) {
				wmTaskMapper.update(
						wmTask, Wrappers.<WmTask>lambdaUpdate()
								.eq(WmTask::getScorePackageId, wmScorePackage.getId())
								.set(WmTask::getEnableFlag, "1"));
			}
			if (wmScorePackage.getPackageType1().equals("1")) {
				updateRelationScore(wmScorePackage.getId(), wmScorePackage.getScore());
			}

		} else if ("2".equals(enableType)) {
			wmScorePackage.setScorePackageStatus("4");//已完成待结算
			//部分终止，收回剩余积分值，没有审核的任务继续审核
			//先更新任务状态为已审核
			int resSum = 0;//收回值
			boolean pickedButNotSubmitted = false;
			if (CollUtil.isNotEmpty(scorestatusList)) {
				wmScorePackage.setUserNum(scorestatusList.size());
				for (WmScorePackageStatus wmScorePackageStatus : scorestatusList) {
					WmTask wmTask1 = new WmTask();
					wmTask1.setEnableFlag("0");
					wmTask1.setScorePackageId(wmScorePackageStatus.getPackageId());
					wmTask1.setTaskUserId(wmScorePackageStatus.getUserId());
					wmTask1.setTaskStatus("1,2,3");
					List<WmTask> taskList1 = wmTaskMapper.selectByTask(wmTask1);
					Integer res = 0;
					boolean all = false;
					if (CollUtil.isEmpty(taskList1)) {
						if (wmScorePackage.getPackageType1().equals("1") || wmScorePackage.getPackageType1()
								.equals("5")) {//定额
							//这个用户还没有做任务时，积分值设为0
							int userScore = Integer.parseInt(wmScorePackageStatus.getUserScore());
							wmScorePackageStatus.setUserScore("0");
							// wmScorePackage.setScore(wmScorePackage.getScore() - Integer.parseInt(wmScorePackageStatus.getUserScore()));
							resSum += userScore;
							// 已终止
							wmScorePackage.setScorePackageStatus("6");
							pickedButNotSubmitted = true;
						} else {//2，3 定量
							//定量收回任务个数
							//定量收回任务个数
							wmScorePackageStatus.setTaskNum(0);
						}
						wmScorePackage.setPackageFinishStatus("1");//已完成

					} else {
						if (wmScorePackage.getPackageType1().equals("1") || wmScorePackage.getPackageType1()
								.equals("5")) {//定额
							int sum;
							if (wmScorePackage.getRelationScoreId() == null) {
								sum = taskList1.stream().mapToInt(WmTask::getScore).sum();
								res = Integer.parseInt(wmScorePackageStatus.getUserScore()) - sum;
								if (res > 0) {//个人积分包值大于任务积分值
									wmScorePackageStatus.setUserScore(sum + "");
									resSum += res;
								}
							} else {
								int passed = taskList1.stream()
										.filter(task -> ReportEnum.APPROVAL_OPINION_YES.getType()
												.equals(task.getReportDrugApprovalOpinion()))
										.mapToInt(WmTask::getScore)
										.sum();
								if (passed == 0) {
									wmScorePackage.setScorePackageStatus("6");//已终止
									wmScorePackage.setEnableFlag("1");
									taskList1.forEach(task -> {
										task.setEnableFlag("1");
										if (StringUtils.equalsAny(task.getReportOneApprovalStatus(), "0", "1")) {
											task.setTaskStatus("4");
										}
										task.setReportDrugApprovalStatus(REPORT_STATUS_END.getType());
										task.setReportDrugApprovalOpinion(ReportEnum.APPROVAL_OPINION_NO.getType());
										wmTaskMapper.updateById(task);
									});
									all = true;
								}

								if (!all) {
									taskList1.forEach(task -> {
										if (StringUtils.equalsAny(task.getReportOneApprovalStatus(), "0", "1")) {
											task.setTaskStatus("4");
										}
										wmTaskMapper.updateById(task);
									});
								}

								res = sum = passed;
								if (res > 0) {//个人积分包值大于任务积分值
									wmScorePackageStatus.setUserScore(sum + "");
									resSum += (wmScorePackage.getScore() - res);
								} else {
									resSum = wmScorePackage.getScore();
								}
							}


						} else {//2，3 定量
							//定量收回任务个数
							wmScorePackageStatus.setTaskNum(taskList1.size());
						}

						List<String> statusList = taskList1.stream()
								.map(WmTask::getTaskStatus)
								.collect(Collectors.toList());
						if (statusList.contains("2")) {//有未审核通过的任务，积分包状态还是进行中
							wmScorePackage.setScorePackageStatus("3");//进行中
						} else {//没有未审核通过的任务，已完成
							wmScorePackage.setPackageFinishStatus("1");//已完成
						}

					}

					wmScorePackageStatus.setTaskAddFlag("0");
					if (all) {
						wmScorePackageStatus.setEnableType("1");
					} else {
						//更新接单数据
						wmScorePackageStatus.setEnableType("2");
					}
					wmScorePackageStatusService.updateById(wmScorePackageStatus);

				}
				//更新积分包的积分总值
				if (resSum > 0) {
					if (!pickedButNotSubmitted) {
						wmScorePackage.setScore(wmScorePackage.getScore() - resSum);
					}
					if (wmScorePackage.getPackageType1().equals("5")) {
						// 如果是患者教育，则需要更新下个人积分包值
						wmScorePackage.setUserScore(String.valueOf(Integer.parseInt(wmScorePackage.getUserScore()) - resSum));
					}
				}
			} else {//没有人接单审核通过
				//积分包
				wmScorePackage.setUserNum(0);
				wmScorePackage.setTaskNum(0);
				wmScorePackage.setPackageFinishStatus("1");//已完成
				wmScorePackage.setScorePackageStatus("4");//已完成待结算
				//积分包承接对象为0的时候，返回积分包积分且积分包状态改为已终止
				if (StringUtil.isNotEmpty(wmScorePackage.getRelationScoreId())) {
					resSum = wmScorePackage.getScore();
					wmScorePackage.setScorePackageStatus("6");//积分包已终止
				}
			}
			wmScorePackage.setIsReceive("1");//不允许接单
			wmScorePackage.setTaskAddFlag("0");//不允许新增任务
			this.updateById(wmScorePackage);
			if (resSum > 0 && wmScorePackage.getPackageType1().equals("1")) {
				updateRelationScore(wmScorePackage.getId(), resSum);
			}

		}
		return R.ok("终止成功");
	}

	/**
	 * 更新关联积分包可分配积分
	 *
	 * @param Id
	 * @param score
	 */
	public void updateRelationScore(String Id, Integer score) {
		WmScorePackage wmScorePackage = wmScorePackageMapper.selectById(Id);
		if (wmScorePackage != null && wmScorePackage.getRelationScoreId() != null) {
			WmScorePackage relationScore = wmScorePackageMapper.selectById(wmScorePackage.getRelationScoreId());
			if (relationScore != null) {
				relationScore.setKfpjf(relationScore.getKfpjf() + score);
				wmScorePackageMapper.updateById(relationScore);
			}
		}

	}

	@Override
	public R getScorePackagePageById(WmScorePackage wmScorePackage) {
		wmScorePackage = wmScorePackageMapper.getScorePackagePageById(wmScorePackage.getId());
		//wmScorePackage=this.getById(wmScorePackage.getId());
		if (StringUtil.isEmpty(wmScorePackage.getRelationScoreId())) {
			wmScorePackage.setRelationScoreId("-1");
		}
		//查询有效任务类型
		List<WmScoreTaskType> taskTypelist = wmScoreTaskTypeMapper.getScoreTaskTypeByScoreId(wmScorePackage.getId());
		wmScorePackage.setTaskTypeList1(taskTypelist);
		Set taskTypeSet = taskTypelist.stream().map(WmScoreTaskType::getTaskTypeId).collect(Collectors.toSet());
		wmScorePackage.setTaskTypeSet(taskTypeSet);
		wmScorePackage.setTaskTypeId(taskTypelist.get(0).getTaskTypeId());
		if (wmScorePackage.getTypeid().equals("3")) {
			//查询接单对象
			List<WmScorePackageStatus> staList = wmScorePackageStatusService.list(Wrappers.<WmScorePackageStatus>lambdaQuery()
					.eq(WmScorePackageStatus::getPackageId, wmScorePackage.getId())
					.eq(WmScorePackageStatus::getDelFlag, "0"));
			if (staList != null && staList.size() > 0) {
				List<String> userList = staList.stream()
						.map(WmScorePackageStatus::getUserId)
						.collect(Collectors.toList());
				wmScorePackage.setUserList(userList);
			}
		}
		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
			// 如果是患者教育，则转换积分值 '分'-> '元'
			String userScore = wmScorePackage.getUserScore();
			if (StringUtils.isNumeric(userScore)) {
				wmScorePackage.setUserScore(String.format("%.2f", Integer.parseInt(userScore) / 100.0));
			}
		}
		return R.ok(wmScorePackage);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateEasy(WmScorePackage wmScorePackage) {
		if (null != wmScorePackage.getDelFlag() && wmScorePackage.getDelFlag().equals("1")) {
			WmScorePackage relationScorePackage = new WmScorePackage();//关联积分包
			wmScorePackage = wmScorePackageMapper.selectById(wmScorePackage.getId());
			wmScorePackage.setDelFlag("1");

			if (wmScorePackage.getPackageType1().equals("1")) {//定额
				if (!StringUtil.isEmpty(wmScorePackage.getRelationScoreId())) {
					relationScorePackage = this.getById(wmScorePackage.getRelationScoreId());
					relationScorePackage.setKfpjf(relationScorePackage.getKfpjf() + wmScorePackage.getScore());
					this.updateById(relationScorePackage);
				}
			}
			wmScorePackageStatusService.delStatusByPackageId(wmScorePackage.getId());
			wmScoreTaskTypeMapper.delete(Wrappers.<WmScoreTaskType>lambdaQuery()
					.eq(WmScoreTaskType::getScoreId, wmScorePackage.getId()));

		}
		this.updateById(wmScorePackage);
		return R.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateWmScorePackage(WmScorePackage wmScorePackage) {

		if (wmScorePackage.getPackageType1().equals("1")) {//定额
			if (!StringUtil.isEmpty(wmScorePackage.getUserScore()) && wmScorePackage.getUserNum() > 0) {
				wmScorePackage.setScore(Integer.valueOf(wmScorePackage.getUserScore()) * wmScorePackage.getUserNum());
			}
		} else {
			if (!StringUtil.isEmpty(wmScorePackage.getUserScore())) {
				if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
					// 如果是患者教育，积分值转换为以'分'为单位保存
					int scoreFen = new BigDecimal(wmScorePackage.getUserScore()).multiply(new BigDecimal("100"))
							.intValue();
					wmScorePackage.setScore(scoreFen);
					wmScorePackage.setUserScore(String.valueOf(scoreFen));
				} else {
					wmScorePackage.setScore(Integer.valueOf(wmScorePackage.getUserScore()));
				}
			}
		}
		WmScorePackage relationScorePackage = new WmScorePackage();//关联积分包
		//判断预积分包值不能大于可分配积分值
		if (!StringUtil.isEmpty(wmScorePackage.getRelationScoreId()) && !wmScorePackage.getRelationScoreId()
				.equals("-1")) {
			WmScorePackage wmScorePackage1 = new WmScorePackage();
			wmScorePackage1.setId(wmScorePackage.getRelationScoreId());
			WmScorePackage wmScorePackage2 = wmScorePackageMapper.selectById(wmScorePackage1.getId());
			Integer kfpjf = 0;
			if (wmScorePackage2 != null) {
				kfpjf += wmScorePackage2.getKfpjf() == null ? 0 : wmScorePackage2.getKfpjf();
				WmScorePackage wmScorePackageOld = wmScorePackageMapper.selectById(wmScorePackage.getId());
				kfpjf += wmScorePackageOld.getScore();
				if (kfpjf > 0 && wmScorePackage.getScore() > kfpjf) {
					return R.failed("预积分包值不能大于可分配积分值");
				}
				//更新可分配积分包值
				if (kfpjf >= wmScorePackage.getScore()) {
					relationScorePackage.setId(wmScorePackage.getRelationScoreId());
					relationScorePackage.setKfpjf(kfpjf - wmScorePackage.getScore());
				}

			}
			//List<WmScorePackage> packageList=wmScorePackageMapper.getScorePackagekfpjf(wmScorePackage1);
			//Integer kfpjf=0;
//			if(null!=packageList&&packageList.size()!=0){
//				kfpjf=packageList.get(0).getKfpjf();
//			}

		}
		HnqzUser currentUser = SecurityUtils.getUser();
		if (wmScorePackage.getRelationScoreId() == null || (wmScorePackage.getRelationScoreId() != null && wmScorePackage
				.getRelationScoreId()
				.equals("-1"))) {

			wmScorePackage.setRelationScoreId(null);
			SysDept dept = new SysDept();
			//关联积分包为空，需要判断是不是是不是药企
			if (wmScorePackage.getRelatedService() == null) {
				dept = sysDeptMapper.selectById(currentUser.getDeptId());
			} else {
				dept = sysDeptMapper.selectById(wmScorePackage.getRelatedService());
			}
			wmScorePackage.setSendPackageDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setDeptId(currentUser.getDeptId() + "");
			if (dept.getDeptId() == null) {
				return R.failed("未查询到当前登陆人的");
			} else {
				if (dept.getLevel() == 2) {//药企
					WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getOne(Wrappers.<WmDaDrugEnt>lambdaQuery()
							.eq(WmDaDrugEnt::getDeptId, dept.getDeptId()));
					wmScorePackage.setDrugEntId(wmDaDrugEnt.getId() + "");
					wmScorePackage.setRuleId(this.queryRuleID(wmDaDrugEnt, null));
				} else if (dept.getLevel() == 3 || dept.getLevel() == 4) {//一级cso
					WmDaAgent wmDaAgent = wmDaAgentService.getOne(Wrappers.<WmDaAgent>lambdaQuery()
							.eq(WmDaAgent::getDeptId, dept.getDeptId()));
					wmScorePackage.setRuleId(this.queryRuleID(null, wmDaAgent));

				}
			}

			wmScorePackage.setBelongDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM")) + "");
		} else {
			WmScorePackage relationScore = this.getById(wmScorePackage.getRelationScoreId());
			if (relationScore == null) {
				return R.failed("未查询到关联积分包！");
			}
			wmScorePackage.setDrugEntId(relationScore.getDrugEntId());
			wmScorePackage.setRuleId(relationScore.getRuleId());
			wmScorePackage.setSendPackageDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setDeptId(currentUser.getDeptId() + "");
			wmScorePackage.setBelongDate(relationScore.getBelongDate());
		}

		//保存接单对象，全职学术推广员，允许选多个
		wmScorePackageStatusService.delStatusByPackageId(wmScorePackage.getId());
		if (wmScorePackage.getTypeid().equals("3")) {
			List<String> userList = wmScorePackage.getUserList();
			if (null != userList && userList.size() > 0) {
				List<WmScorePackageStatus> stuList = new ArrayList<>();
				for (String userId : userList) {
					WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
					wmScorePackageStatus.setUserId(userId);
					wmScorePackageStatus.setStatus("2");
					wmScorePackageStatus.setPackageId(wmScorePackage.getId());
					UserVO user = sysUserMapper.getUserVoById(Integer.valueOf(userId));
					wmScorePackageStatus.setDeptId(user.getDeptId() + "");
					if (wmScorePackage.getPackageType1().equals("1")) {//定额包
						wmScorePackageStatus.setUserScore(wmScorePackage.getScore() + "");
					} else {//定量包
						wmScorePackageStatus.setTaskNum(wmScorePackage.getTaskNum());
					}
					wmScorePackageStatus.setEnableFlag("0");
					wmScorePackageStatus.setDelFlag("0");
					wmScorePackageStatus.setCreateTime(LocalDateTime.now());
					wmScorePackageStatus.setCreateUser(currentUser.getId());
					stuList.add(wmScorePackageStatus);
				}
				wmScorePackageStatusService.saveBatch(stuList);
				wmScorePackage.setUserNum(userList.size());
			}
		} else {
			if (wmScorePackage.getUserNum() == null) {
				wmScorePackage.setUserNum(1);
			}
		}


		if (wmScorePackage.getPackageType1().equals("5") || wmScorePackage.getPackageType1().equals("4")
				|| wmScorePackage.getPackageType2().equals("2")) {
			wmScoreTaskTypeMapper.delete(Wrappers.<WmScoreTaskType>lambdaQuery()
					.eq(WmScoreTaskType::getScoreId, wmScorePackage.getId()));
			//结算包
			WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
			wmScoreTaskType.setScoreId(wmScorePackage.getId());
			wmScoreTaskType.setTaskTypeId(wmScorePackage.getTaskTypeId());
			wmScoreTaskType.setType("2");
			wmScoreTaskTypeMapper.insert(wmScoreTaskType);
		} else {
			//保存有效任务类型
			List<WmTaskTypeTree> tasktypeList = wmScorePackage.getTaskTypeList();
			if (tasktypeList != null && tasktypeList.size() > 0) {
				wmScoreTaskTypeMapper.delete(Wrappers.<WmScoreTaskType>lambdaQuery()
						.eq(WmScoreTaskType::getScoreId, wmScorePackage.getId()));
				for (WmTaskTypeTree type : tasktypeList) {
					WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
					wmScoreTaskType.setScoreId(wmScorePackage.getId());
					wmScoreTaskType.setType(type.getType());
					wmScoreTaskType.setTaskTypeId(type.getTaskTypeId());
					wmScoreTaskTypeMapper.insert(wmScoreTaskType);
					if (null == type.getChildren()) {
						continue;
					}
					List<WmTaskTypeTree> childtasktypeList = type.getChildren();
					for (WmTaskTypeTree type1 : childtasktypeList) {
						WmScoreTaskType wmScoreTaskType1 = new WmScoreTaskType();
						wmScoreTaskType1.setScoreId(wmScorePackage.getId());
						wmScoreTaskType1.setType(type1.getType());
						wmScoreTaskType1.setTaskTypeId(type1.getTaskTypeId());
						wmScoreTaskTypeMapper.insert(wmScoreTaskType1);
					}


				}
			}
		}
		if (wmScorePackage.getTypeid() != null && wmScorePackage.getTypeid().equals("4")) {//兼职学术推广员
			wmScorePackage.setXxdbId(null);
		}
		if ("3".equals(wmScorePackage.getTypeid())) {//全职学术推广员
			wmScorePackage.setIsReceive("1");//不允许接单
			wmScorePackage.setScorePackageStatus("3");//全职学术推广员不需要审核，所有状态直接是进行中

		} else if ("4".equals(wmScorePackage.getTypeid())) {
			wmScorePackage.setIsReceive("0");//允许接单
			wmScorePackage.setScorePackageStatus("1");//已分派待申领
		}
		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
			// 患者教育，固定只能一人领取
			wmScorePackage.setUserNum(1);
		}
		// 数据来源类型（0-手动上传，1-系统对接）
		wmScorePackage.setSourceType("0");
		wmScorePackage.setUpdateTime(LocalDateTime.now());
		wmScorePackage.setUpdateUser(SecurityUtils.getUser().getId());
		this.updateById(wmScorePackage);
		if (wmScorePackage.getRelationScoreId() == null) {
			this.update(Wrappers.<WmScorePackage>lambdaUpdate()
					.eq(WmScorePackage::getId, wmScorePackage.getId())
					.set(WmScorePackage::getRelationScoreId, null));
		}

		//更新关联积分包可分配积分值
		if (!StringUtil.isEmpty(relationScorePackage.getId())) {
			this.updateById(relationScorePackage);
		}
		return R.ok();
	}

	@Override
	public WmScorePackage selectRelationScoreIdList(WmScorePackage wmScorePackage) {
		WmScorePackage wmScorePackage1 = this.getById(wmScorePackage.getRelationScoreId());
		return wmScorePackage1;
	}

	@Override
	public List<WmScorePackage> listWmScorePackages(WmScorePackage wmScorePackage1) {
		return wmScorePackageMapper.listWmScorePackages(wmScorePackage1);
	}

	@Override
	public IPage<WmScorePackageApiOutput> getPackageListForReceive(Page page, WmScorePackage wmScorePackage) {
//		OrderItem orderItem = new OrderItem();
//		orderItem.setColumn("create_time");
//		orderItem.setAsc(false);
//		page.addOrder(orderItem);
		return wmScorePackageMapper.getPackageListForReceive(page, wmScorePackage);
	}

	/**
	 * 积分包结算列表（分页）
	 *
	 * @param page
	 * @param input
	 * @return
	 */
	@Override
	public IPage<WmScorePackageSettleOutput> listPackageSettleList(Page page, WmScorePackageSettleInput input) {
		IPage<WmScorePackageSettleOutput> settleListPage = wmScorePackageMapper.listPackageSettleList(page, input);
		List<WmScorePackageSettleOutput> settleList = settleListPage.getRecords();
		for (WmScorePackageSettleOutput ouPut : settleList) {
			WmScorePackageStatus statusQuery = new WmScorePackageStatus();
			statusQuery.setPackageId(ouPut.getId());
			statusQuery.setStatus("2");
			List<WmScorePackageStatus> statusList = wmScorePackageStatusService.getByPackageId(statusQuery);
			String userNames = statusList.stream()
					.map(WmScorePackageStatus::getUserId)
					.collect(Collectors.joining(","));
			ouPut.setUserNames(userNames);
			// 查询结算成功时间
			List<WmScorePackageSettleNote> packageSettleNoteList = settleNoteMapper.selectList(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, ouPut.getId()));
			if (CollectionUtil.isNotEmpty(packageSettleNoteList)) {
				WmScorePackageSettleNote settleNote = packageSettleNoteList.get(0);
				LocalDateTime notifyTime = settleNote.getNotifyTime();
				if (notifyTime != null) {
					ouPut.setBelongDate(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(notifyTime));
				}
				if (ouPut.getInvoiceCategory() == null) {
					ouPut.setInvoiceCategory(settleNote.getInvoiceType());
				}

				if (ouPut.getSettleAmount() == null) {
					BigDecimal tmp = new BigDecimal("0");
					for (WmScorePackageSettleNote note : packageSettleNoteList) {
						if (null != note.getSettleAmount()) {
							tmp = tmp.add(note.getSettleAmount());
						}
					}
					ouPut.setSettleAmount(tmp);
				}
				if (StringUtils.isBlank(ouPut.getSettleStatus())) {
					ouPut.setSettleStatus(String.valueOf(settleNote.getSettleNoteStatus()));
				}
			}
			if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(ouPut.getPackageType1())) {
				// 如果是患者教育，则转换积分值 '分'->'元'
				WmScorePackage scorePackage = this.getById(ouPut.getId());
				if (scorePackage != null && StringUtils.isNumeric(scorePackage.getUserScore())) {
					ouPut.setScore(String.format("%.2f", Integer.parseInt(scorePackage.getUserScore()) / 100.0));
				}
			}
		}
		return settleListPage;
	}

	/**
	 * 积分包结算列表
	 *
	 * @param input
	 * @return
	 */
	@Override
	public List<WmScorePackageSettleOutput> listAllPackageSettle(WmScorePackageSettleInput input) {
		List<WmScorePackageSettleOutput> settleList = wmScorePackageMapper.listAllPackageSettle(input);
		for (WmScorePackageSettleOutput ouPut : settleList) {
			WmScorePackageStatus statusQuery = new WmScorePackageStatus();
			statusQuery.setPackageId(ouPut.getId());
			statusQuery.setStatus("2");
			List<WmScorePackageStatus> statusList = wmScorePackageStatusService.getByPackageId(statusQuery);
			String userNames = statusList.stream()
					.map(WmScorePackageStatus::getUserId)
					.collect(Collectors.joining(","));
			ouPut.setUserNames(userNames);
			// 查询结算成功时间
			List<WmScorePackageSettleNote> packageSettleNoteList = settleNoteMapper.selectList(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, ouPut.getId()));
			if (CollectionUtil.isNotEmpty(packageSettleNoteList)) {
				WmScorePackageSettleNote settleNote = packageSettleNoteList.get(0);
				LocalDateTime notifyTime = settleNote.getNotifyTime();
				if (notifyTime != null) {
					ouPut.setBelongDate(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(notifyTime));
				}
				if (ouPut.getInvoiceCategory() == null) {
					ouPut.setInvoiceCategory(settleNote.getInvoiceType());
				}
				if (ouPut.getSettleAmount() == null) {
					BigDecimal tmp = new BigDecimal("0");
					for (WmScorePackageSettleNote note : packageSettleNoteList) {
						if (null != note.getSettleAmount()) {
							tmp = tmp.add(note.getSettleAmount());
						}
					}
					ouPut.setSettleAmount(tmp);
				}
				if (StringUtils.isBlank(ouPut.getSettleStatus())) {
					ouPut.setSettleStatus(String.valueOf(settleNote.getSettleNoteStatus()));
				}
			}
			if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(ouPut.getPackageType1())) {
				// 如果是患者教育，则转换积分值 '分'->'元'
				WmScorePackage scorePackage = this.getById(ouPut.getId());
				if (scorePackage != null && StringUtils.isNumeric(scorePackage.getUserScore())) {
					ouPut.setScore(String.format("%.2f", Integer.parseInt(scorePackage.getUserScore()) / 100.0));
				}
			}
		}
		return settleList;
	}

	/**
	 * 获取当前部门的基于所有积分包的相关信息
	 *
	 * @return 积分包的相关信息
	 */
	@Override
	public Map<String, Object> getDeptScorePackageInfo(Integer deptId) {
		Map<String, Object> result = new HashMap<>();
		Wrapper<WmScorePackage> wrapper = Wrappers.<WmScorePackage>lambdaQuery()
				.eq(WmScorePackage::getDeptId, deptId)
				.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_HCP_PACKAGE.val())
				.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val())
				.eq(WmScorePackage::getDelFlag, DelEnum.NOT_DEL.val())
				.eq(WmScorePackage::getEnableFlag, EnableEnum.ENABLE.val())
				.eq(WmScorePackage::getSourceType, "1")
				.eq(WmScorePackage::getTypeid, 4);
		List<WmScorePackage> scorePackageList = this.list(wrapper);
		if (CollectionUtil.isNotEmpty(scorePackageList)) {
			// 计算已分配的总积分值
			long totalScore = scorePackageList.stream()
					.filter(wmScorePackage -> StringUtils.isNumeric(wmScorePackage.getUserScore()))
					.mapToLong(value -> Integer.parseInt(value.getUserScore()))
					.sum();
			// 计算已结算的总积分值
			List<Integer> idList = scorePackageList.stream()
					.mapToInt(s -> Integer.parseInt(s.getId()))
					.boxed()
					.collect(Collectors.toList());
			List<WmScorePackageSettleNote> noteList = settleNoteMapper.selectList(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.in(WmScorePackageSettleNote::getPackageId, idList)
					.eq(WmScorePackageSettleNote::getSettleNoteStatus, "1"));

			BigDecimal totalSettledScore = new BigDecimal("0");
			if (CollectionUtil.isNotEmpty(noteList)) {
				for (WmScorePackageSettleNote note : noteList) {
					totalSettledScore = totalSettledScore.add(note.getSettleAmount());
				}
			}
			result.put("totalScore", String.format("%.2f", totalScore / 100.0));
			result.put("totalSettledScore", String.format("%.2f", totalSettledScore.doubleValue()));
			// 已结算积分值所占比例（%）
			result.put("settledScoreRate", Math.round(totalSettledScore.doubleValue() * 100 / totalScore));
		}
		return result;
	}

	/**
	 * 根据积分包获取推广的药品
	 *
	 * @param page      分页信息
	 * @param packageId 积分包id
	 * @param drugName  药品名称
	 * @return 药品列表
	 */
	@Override
	public IPage<WmDaDrugEntDrugtable> listDrugsByPackageId(Page page, Integer packageId, String drugName) {

		// 获取积分包
		final WmScorePackage one = getOne(Wrappers.<WmScorePackage>lambdaQuery().eq(WmScorePackage::getId, packageId));

		return wmDaDrugEntDrugtableService.listDrugs(page, Integer.parseInt(one.getRelatedService()), drugName);


	}

	@Override
	public Page<WmScorePackage> selectWmScorePackageLists(Page<WmScorePackage> page, String scorePackageName, String acceptSug, LocalDate allocationDate, LocalDate endLabelDate) {

		Integer deptId = SecurityUtils.getUser().getDeptId();
		return wmScorePackageMapper.newSelectWmScorePackageLists(page, String.valueOf(deptId),
				scorePackageName, acceptSug, allocationDate, endLabelDate);
	}


	@Override
	@Async("doSelectWmScorePackageListsPool")
	public Future<WmScorePackage> finishRate(WmScorePackage wmScorePackage) {
		String packageId = wmScorePackage.getId();
		Set<String> scorePackageIdSet = stepA(packageId);
		List<Map<String, Object>> stepB_1 = stepB_1(scorePackageIdSet);
		List<Map<String, Object>> stepB_2 = stepB_2(packageId);

		List<Map<String, Object>> m = new ArrayList<>(stepB_1.size() + stepB_2.size());
		m.addAll(stepB_1);
		m.addAll(stepB_2);
		Map<String, Integer> result = step3(m);
		WmScorePackage p = step4(result, wmScorePackage);

		return new AsyncResult<>(p);
	}

	@Override
	public R getScorePackagePage(Page<WmScorePackage> page, Integer packageType1, Integer packageType2, String scorePackageName, Integer scorePackageStatus, String typeId) {

		List<String> reportWaitingCheckStatus = Arrays.asList("0", "1");

		Integer sendDeptId = SecurityUtils.getUser().getDeptId();

		LambdaQueryWrapper<WmScorePackage> queryWrapper = Wrappers.<WmScorePackage>lambdaQuery()
				.eq(WmScorePackage::getPackageType1, packageType1)
				.eq(WmScorePackage::getPackageType2, packageType2)
				.like(StrUtil.isNotEmpty(scorePackageName), WmScorePackage::getScorePackageName, scorePackageName)
				.eq(scorePackageStatus != null, WmScorePackage::getScorePackageStatus, scorePackageStatus)
				.eq(WmScorePackage::getSendPackageDeptId, sendDeptId);

		if (StringUtil.isEmpty(typeId)) {
			queryWrapper.in(WmScorePackage::getTypeid, "3", "4");
		} else {
			List<String> split = StrUtil.split(typeId, StrUtil.C_COMMA);
			queryWrapper.in(WmScorePackage::getTypeid, split);
		}

		Page<WmScorePackage> wmScorePackagePage = wmScorePackageMapper.selectPage(page, queryWrapper.orderByDesc(WmScorePackage::getCreateTime));

		List<WmScorePackage> pageRecords = wmScorePackagePage.getRecords();

		for (WmScorePackage scorePackage : pageRecords) {

			// 任务统计
			List<WmTask> taskList = wmTaskMapper.selectList(Wrappers.<WmTask>lambdaQuery()
					.eq(WmTask::getRealFlag, "0")
					.eq(WmTask::getEnableFlag, "0")
					.eq(WmTask::getDelFlag, "0")
					.eq(WmTask::getScorePackageId, scorePackage.getId())
			);

			// 审核通过
			int shtg = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "1") || StrUtil.equals(t.getReportOneApprovalOpinion(), "1"))
					.mapToInt(WmTask::getScore)
					.sum();
			// 审核 不通过
			int shbtg = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "2") || StrUtil.equals(t.getReportOneApprovalOpinion(), "2"))
					.mapToInt(WmTask::getScore)
					.sum();
			// 审核通过数
			long shtgnum = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "1") || StrUtil.equals(t.getReportOneApprovalOpinion(), "1"))
					.count();
			// 审核不通过数
			long shbtgnum = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "2") || StrUtil.equals(t.getReportOneApprovalOpinion(), "2"))
					.count();
			// 平台未审核
			int temp = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getTaskStatus(), "1"))
					.mapToInt(WmTask::getScore)
					.sum();
			// 待审核
			int dsh = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getTaskStatus(), "2"))
					.mapToInt(WmTask::getScore)
					.sum();
			// 已审核
			int ysh = taskList.parallelStream()
					.filter(t -> StrUtil.equals(t.getTaskStatus(), "3"))
					.mapToInt(WmTask::getScore)
					.sum();
			// 已审核数
			long yshnum = taskList.parallelStream().filter(t -> StrUtil.equals(t.getTaskStatus(), "3")).count();
			// 已提交
			int ytj = temp + dsh + ysh;

			// 已审核百分比
			long yshtt = 0;
			// 审核通过百分比
			long shtgtt = 0;
			// 审核不通过百分比
			long shbtgtt = 0;
			if (StrUtil.equals(scorePackage.getPackageType1(), "1")) {
				int score = scorePackage.getScore();
				yshtt = ysh * 100L / score;
				yshtt = yshtt > 100 ? 100 : yshtt;

				shtgtt = shtg * 100L / score;
				shtgtt = shtgtt > 100 ? 100 : shtgtt;

				shbtgtt = shbtg * 100L / score;
				shbtgtt = shbtgtt > 100 ? 100 : shbtgtt;
			} else {
				int score = scorePackage.getUserNum() * scorePackage.getTaskNum();
				yshtt = yshnum * 100 / score;
				shtgtt = shtgnum * 100 / score;
				shbtgtt = shbtgnum * 100 / score;
			}


			// 领取积分包记录
			List<WmScorePackageStatus> scorePackageStatusList = wmScorePackageStatusService.list(Wrappers.<WmScorePackageStatus>lambdaQuery()
					.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
			);

			List<WmScorePackageStatus> packageStatusList = scorePackageStatusList.stream()
					.filter(s -> StrUtil.equals(s.getEnableFlag(), "0") && StrUtil.equals(s.getDelFlag(), "0"))
					.collect(Collectors.toList());


			List<WmScorePackageStatus> staList = scorePackageStatusList.stream()
					.filter(record -> StrUtil.equals(record.getStatus(), "2"))
					.collect(Collectors.toList());
			;

			if (CollUtil.isNotEmpty(staList)) {
				List<String> userIdList = staList.stream()
						.map(WmScorePackageStatus::getUserId)
						.collect(Collectors.toList());

				List<String> userNameList = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery()
						.in(SysUser::getUserId, userIdList))
						.stream()
						.map(SysUser::getRealname)
						.collect(Collectors.toList());
				scorePackage.setUserList(userNameList);
				scorePackage.setUserListNum(userNameList.size());
			} else {
				scorePackage.setUserListNum(0);
			}

			// 已结单
			long yjd = packageStatusList.stream()
					.filter(s -> StrUtil.equalsAny(s.getStatus(), "1", "2"))
					.count();
			// 已结单待审核
			long yjddsh = packageStatusList.stream()
					.filter(s -> StrUtil.equals(s.getStatus(), "1"))
					.count();


			//获取上级包
			WmScorePackage relationScorePackage = wmScorePackageMapper.selectOne(Wrappers.<WmScorePackage>lambdaQuery()
					.eq(WmScorePackage::getId, scorePackage.getRelationScoreId()).last("limit 1"));


			// 类型标签
			SysDictItem package_type1 = sysDictItemService.getOne(Wrappers.<SysDictItem>lambdaQuery()
					.eq(SysDictItem::getType, "package_type1")
					.eq(SysDictItem::getValue, packageType1));
			SysDictItem package_type2 = sysDictItemService.getOne(Wrappers.<SysDictItem>lambdaQuery()
					.eq(SysDictItem::getType, "package_type2")
					.eq(SysDictItem::getValue, packageType2));

			String type1Lable = package_type1.getLabel();
			String type2Lable = package_type2.getLabel();


			// 设置
			// scorePackage.setYsh(yshtt >= 100 ? scorePackage.getScore() : ysh);
			scorePackage.setYjd((int) yjd);
			scorePackage.setYjddsh((int) yjddsh);
			scorePackage.setDsh(dsh);
			scorePackage.setYtj(ytj);
			if (!StrUtil.equals(scorePackage.getScorePackageStatus(), "1") && !StrUtil.equals(scorePackage.getScorePackageStatus(), "6")) {
				scorePackage.setYsh(ysh);
				scorePackage.setShtg(shtg);
				scorePackage.setShbtg(shbtg);
				scorePackage.setShbtgnum((int) shbtgnum);
				scorePackage.setShtgnum((int) shtgnum);
				scorePackage.setShtgtt((int) shtgtt);
				scorePackage.setShbtgtt((int) shbtgtt);
				scorePackage.setYshtt((int) yshtt);
			}
			scorePackage.setIsTask(scorePackage.getId());
			scorePackage.setPackageType1(type1Lable);
			scorePackage.setPackageType2(type2Lable);
			scorePackage.setRelationScoreId(relationScorePackage != null ? relationScorePackage.getScorePackageName() : null);


			// 结算记录
			WmScorePackageSettleNote note = settleNoteMapper.selectOne(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, scorePackage.getId()).last("limit 1"));

			if (note != null) {
				scorePackage.setNotifyDate(note.getNotifyTime());
			}

			if (packageType2 == 2) {

				LambdaQueryWrapper<WmScorePackageSettleNote> wrapper = Wrappers.<WmScorePackageSettleNote>lambdaQuery()
						.eq(WmScorePackageSettleNote::getPackageId, scorePackage.getId());

				int wsNum = settleNoteMapper.selectCount(wrapper.in(WmScorePackageSettleNote::getSettleNoteStatus, 2, 9));
				int asNum = settleNoteMapper.selectCount(wrapper.eq(WmScorePackageSettleNote::getSettleNoteStatus, 1));
				scorePackage.setWsTaskNum(wsNum);
				scorePackage.setAsTaskNum(asNum);

			}

			if (PackageTypeEnum.TYPE1_HCP_PACKAGE.getName().equals(scorePackage.getPackageType1())) {
				// 如果是患者教育，则转换积分值 '分'-> '元'
				Integer score = scorePackage.getScore();
				String userScore = scorePackage.getUserScore();
				if (StringUtils.isNumeric(userScore)) {
					scorePackage.setUserScore(String.format("%.2f", Integer.parseInt(userScore) / 100.0));
				}
			}

			List<WmScoreTaskType> taskTypeList = wmScoreTaskTypeMapper.getScoreTaskTypeByScoreId(scorePackage.getId());
			if (CollUtil.isNotEmpty(taskTypeList)) {
				String taskTypes = taskTypeList.stream().map(
						WmScoreTaskType::getTaskTypeName).collect(Collectors.joining(","));
				scorePackage.setTaskTypes(taskTypes);
			}


			// 设置中止状态
			WmScorePackage.PackageStopStatus stopStatus;

			if (scorePackage.getRelationScoreId() == null) {
				stopStatus = WmScorePackage.PackageStopStatus.ALL_IN;
			} else {

				//统计发包方还未审核的
				long drugNeedToCheckCount = taskList.stream()
						.filter(t -> "3".equals(t.getTaskStatus()) && "2".equals(t.getReportOneApprovalStatus()))
						.count();

				// 统计cso未审核 和审核通过的还未提交到药企的任务数
				long csoNeedToCheckCount = taskList.stream()
						.filter(t -> "2".equals(t.getTaskStatus()) ||
								("3".equals(t.getTaskStatus()) && reportWaitingCheckStatus.contains(t.getReportOneApprovalStatus())))
						.count();

				// 如果有发包方未审核的不能中止
				if (drugNeedToCheckCount != 0L) {
					stopStatus = WmScorePackage.PackageStopStatus.NOTHING;
				} else if (csoNeedToCheckCount != 0L) {
					// 如果有cso未审核的提示信息
					stopStatus = WmScorePackage.PackageStopStatus.REMAIN_MSG;
				} else {
					// 无提示信息
					stopStatus = WmScorePackage.PackageStopStatus.REMAIN;
				}
			}

			scorePackage.setStopStatus(stopStatus);

		}

		return R.ok(wmScorePackagePage);
	}

	@Override
	@Async(value = "doGetScorePackagePagePool")
	public Future<WmScorePackage> buildScorePackage(WmScorePackage scorePackage, Integer packageType1, Integer packageType2) {

		List<String> reportWaitingCheckStatus = Arrays.asList("0", "1");

		// 任务统计
		List<WmTask> taskList = wmTaskMapper.selectList(Wrappers.<WmTask>lambdaQuery()
				.eq(WmTask::getRealFlag, "0")
				.eq(WmTask::getEnableFlag, "0")
				.eq(WmTask::getDelFlag, "0")
				.eq(WmTask::getScorePackageId, scorePackage.getId())
		);

		// 审核通过
		int shtg = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "1") || StrUtil.equals(t.getReportOneApprovalOpinion(), "1"))
				.mapToInt(WmTask::getScore)
				.sum();
		// 审核 不通过
		int shbtg = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "2") || StrUtil.equals(t.getReportOneApprovalOpinion(), "2"))
				.mapToInt(WmTask::getScore)
				.sum();
		// 审核通过数
		long shtgnum = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "1") || StrUtil.equals(t.getReportOneApprovalOpinion(), "1"))
				.count();
		// 审核不通过数
		long shbtgnum = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getReportDrugApprovalOpinion(), "2") || StrUtil.equals(t.getReportOneApprovalOpinion(), "2"))
				.count();
		// 平台未审核
		int temp = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getTaskStatus(), "1"))
				.mapToInt(t -> t.getScore() == null ? 0 : t.getScore())
				.sum();
		// 待审核
		int dsh = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getTaskStatus(), "2"))
				.mapToInt(t -> t.getScore() == null ? 0 : t.getScore())
				.sum();
		// 已审核
		int ysh = taskList.parallelStream()
				.filter(t -> StrUtil.equals(t.getTaskStatus(), "3"))
				.mapToInt(t -> t.getScore() == null ? 0 : t.getScore())
				.sum();
		// 已审核数
		long yshnum = taskList.parallelStream().filter(t -> StrUtil.equals(t.getTaskStatus(), "3")).count();
		// 已提交
		int ytj = temp + dsh + ysh;

		// 已审核百分比
		long yshtt = 0;
		// 审核通过百分比
		long shtgtt = 0;
		// 审核不通过百分比
		long shbtgtt = 0;
		if (StrUtil.equals(scorePackage.getPackageType1(), "1")) {
			int score = scorePackage.getScore();
			if (score != 0) {
				yshtt = ysh * 100L / score;
				yshtt = yshtt > 100 ? 100 : yshtt;

				shtgtt = shtg * 100L / score;
				shtgtt = shtgtt > 100 ? 100 : shtgtt;

				shbtgtt = shbtg * 100L / score;
				shbtgtt = shbtgtt > 100 ? 100 : shbtgtt;
			}
		} else {
			int score = scorePackage.getUserNum() * scorePackage.getTaskNum();
			yshtt = yshnum * 100 / score;
			shtgtt = shtgnum * 100 / score;
			shbtgtt = shbtgnum * 100 / score;
		}


		// 领取积分包记录
		List<WmScorePackageStatus> scorePackageStatusList = wmScorePackageStatusService.list(Wrappers.<WmScorePackageStatus>lambdaQuery()
				.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
		);

		List<WmScorePackageStatus> packageStatusList = scorePackageStatusList.stream()
				.filter(s -> StrUtil.equals(s.getEnableFlag(), "0") && StrUtil.equals(s.getDelFlag(), "0"))
				.collect(Collectors.toList());


		List<WmScorePackageStatus> staList = scorePackageStatusList.stream()
				.filter(record -> StrUtil.equals(record.getStatus(), "2"))
				.collect(Collectors.toList());
		;

		if (CollUtil.isNotEmpty(staList)) {
			List<String> userIdList = staList.stream()
					.map(WmScorePackageStatus::getUserId)
					.collect(Collectors.toList());

			List<String> userNameList = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery()
					.in(SysUser::getUserId, userIdList))
					.stream()
					.map(SysUser::getRealname)
					.collect(Collectors.toList());
			scorePackage.setUserList(userNameList);
			scorePackage.setUserListNum(userNameList.size());
		} else {
			scorePackage.setUserListNum(0);
		}

		// 已结单
		long yjd = packageStatusList.stream()
				.filter(s -> StrUtil.equalsAny(s.getStatus(), "1", "2"))
				.count();
		// 已结单待审核
		long yjddsh = packageStatusList.stream()
				.filter(s -> StrUtil.equals(s.getStatus(), "1"))
				.count();


		//获取上级包
		WmScorePackage relationScorePackage = wmScorePackageMapper.selectOne(Wrappers.<WmScorePackage>lambdaQuery()
				.eq(WmScorePackage::getId, scorePackage.getRelationScoreId()).last("limit 1"));


		// 类型标签
		SysDictItem package_type1 = sysDictItemService.getOne(Wrappers.<SysDictItem>lambdaQuery()
				.eq(SysDictItem::getType, "package_type1")
				.eq(SysDictItem::getValue, packageType1));
		SysDictItem package_type2 = sysDictItemService.getOne(Wrappers.<SysDictItem>lambdaQuery()
				.eq(SysDictItem::getType, "package_type2")
				.eq(SysDictItem::getValue, packageType2));

		String type1Lable = package_type1.getLabel();
		String type2Lable = package_type2.getLabel();


		// 设置
		// scorePackage.setYsh(yshtt >= 100 ? scorePackage.getScore() : ysh);
		scorePackage.setYjd((int) yjd);
		scorePackage.setYjddsh((int) yjddsh);
		scorePackage.setDsh(dsh);
		if (!StrUtil.equalsAny(scorePackage.getScorePackageStatus(), "1", "6")) {
			scorePackage.setYsh(ysh);
			scorePackage.setShtg(shtg);
			scorePackage.setShbtg(shbtg);
			scorePackage.setShbtgnum((int) shbtgnum);
			scorePackage.setShtgnum((int) shtgnum);
			scorePackage.setShtgtt((int) shtgtt);
			scorePackage.setShbtgtt((int) shbtgtt);
			scorePackage.setYshtt((int) yshtt);
		}
		scorePackage.setIsTask(scorePackage.getId());
		scorePackage.setYtj(ytj);
		scorePackage.setPackageType1(type1Lable);
		scorePackage.setPackageType2(type2Lable);
		scorePackage.setRelationScoreId(relationScorePackage != null ? relationScorePackage.getScorePackageName() : null);


		// 结算记录
		WmScorePackageSettleNote note = settleNoteMapper.selectOne(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
				.eq(WmScorePackageSettleNote::getPackageId, scorePackage.getId()).last("limit 1"));

		if (note != null) {
			scorePackage.setNotifyDate(note.getNotifyTime());
		}

		if (packageType2 == 2) {


			int wsNum = settleNoteMapper.selectCount(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, scorePackage.getId())
					.in(WmScorePackageSettleNote::getSettleNoteStatus, 2, 9));
			int asNum = settleNoteMapper.selectCount(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.eq(WmScorePackageSettleNote::getPackageId, scorePackage.getId())
					.eq(WmScorePackageSettleNote::getSettleNoteStatus, 1));
			scorePackage.setWsTaskNum(wsNum);
			scorePackage.setAsTaskNum(asNum);

		}

		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.getName().equals(scorePackage.getPackageType1())) {
			// 如果是患者教育，则转换积分值 '分'-> '元'
			Integer score = scorePackage.getScore();
			String userScore = scorePackage.getUserScore();
			if (StringUtils.isNumeric(userScore)) {
				scorePackage.setUserScore(String.format("%.2f", Integer.parseInt(userScore) / 100.0));
			}
		}

		List<WmScoreTaskType> taskTypeList = wmScoreTaskTypeMapper.getScoreTaskTypeByScoreId(scorePackage.getId());
		if (CollUtil.isNotEmpty(taskTypeList)) {
			String taskTypes = taskTypeList.stream().map(
					WmScoreTaskType::getTaskTypeName).collect(Collectors.joining(","));
			scorePackage.setTaskTypes(taskTypes);
		}


		// 设置中止状态
		WmScorePackage.PackageStopStatus stopStatus;

		if (scorePackage.getRelationScoreId() == null) {
			stopStatus = WmScorePackage.PackageStopStatus.ALL_IN;
		} else {

			//统计发包方还未审核的
			long drugNeedToCheckCount = taskList.stream()
					.filter(t -> "3".equals(t.getTaskStatus()) && "2".equals(t.getReportOneApprovalStatus()))
					.count();

			// 统计cso未审核 和审核通过的还未提交到药企的任务数
			long csoNeedToCheckCount = taskList.stream()
					.filter(t -> "2".equals(t.getTaskStatus()) ||
							("3".equals(t.getTaskStatus()) && reportWaitingCheckStatus.contains(t.getReportOneApprovalStatus())))
					.count();

			// 如果有发包方未审核的不能中止
			if (drugNeedToCheckCount != 0L) {
				stopStatus = WmScorePackage.PackageStopStatus.NOTHING;
			} else if (csoNeedToCheckCount != 0L) {
				// 如果有cso未审核的提示信息
				stopStatus = WmScorePackage.PackageStopStatus.REMAIN_MSG;
			} else {
				// 无提示信息
				stopStatus = WmScorePackage.PackageStopStatus.REMAIN;
			}
		}

		scorePackage.setStopStatus(stopStatus);

		return new AsyncResult<>(scorePackage);
	}


	private Set<String> stepA(String packageId) {

		Set<String> scorePackageIdSet = new HashSet<>();
		scorePackageIdSet.add(packageId);


		List<WmScorePackage> relationScoreList = wmScorePackageMapper.selectList(Wrappers.<WmScorePackage>lambdaQuery()
				.eq(WmScorePackage::getRelationScoreId, packageId));

		Set<String> relationScoreIdSet = relationScoreList.stream().map(WmScorePackage::getId)
				.collect(Collectors.toSet());

		if (CollUtil.isNotEmpty(relationScoreIdSet)) {
			scorePackageIdSet.addAll(relationScoreIdSet);
			List<WmScorePackage> relationRelationScoreIdList = wmScorePackageMapper.selectList(Wrappers.<WmScorePackage>lambdaQuery()
					.in(WmScorePackage::getRelationScoreId, relationScoreIdSet));
			Set<String> relationRelationScoreIdSet = relationRelationScoreIdList.stream()
					.map(WmScorePackage::getScoreId)
					.collect(Collectors.toSet());
			if (CollUtil.isNotEmpty(relationRelationScoreIdSet)) {
				scorePackageIdSet.addAll(relationRelationScoreIdSet);
			}
		}

		return scorePackageIdSet;
	}


	private List<Map<String, Object>> stepB_1(Set<String> scorePackageIdSet) {

		List<Map<String, Object>> mapList = wmTaskMapper.selectMaps(Wrappers.<WmTask>query()
				.select("0 AS payScore", "SUM(IF(task_status = 3, score, 0)) ysh")
				.in("score_package_id", scorePackageIdSet)
				.eq("enable_flag", "0")
				.eq("real_flag", "0")
				.eq("del_flag", "0")
				.groupBy("score_package_id")

		);

		return mapList;

	}

	private List<Map<String, Object>> stepB_2(String scoreId) {


		List<WmReport> wmReportList = wmReportMapper.selectList(Wrappers.<WmReport>lambdaQuery()
				.eq(WmReport::getReportStatus, "6")
				.eq(WmReport::getScoreId, scoreId)
		);

		Set<Integer> reportIdSet = wmReportList.stream().mapToInt(WmReport::getId).boxed().collect(Collectors.toSet());

		if (CollUtil.isNotEmpty(reportIdSet)) {
			List<Map<String, Object>> mapList = wmTaskMapper.selectMaps(Wrappers.<WmTask>query()
					.select("SUM(score) AS payScore", "0 AS ysh")
					.and(i -> i.eq("report_drug_approval_opinion", "1").or().eq("report_one_approval_opinion", 1))
					.and(i -> i.in("report_one_id", reportIdSet)
							.or()
							.in("report_second_id", reportIdSet)
							.or()
							.in("report_drug_id", reportIdSet))

			);
			return mapList;

		} else {
			Map<String, Object> map = ImmutableMap.of("payScore", 0, "ysh", 0);
			return Collections.singletonList(map);
		}


	}


	public Map<String, Integer> step3(List<Map<String, Object>> m) {
		int payScore = 0;
		int ysh = 0;

		for (Map<String, Object> tmp : m) {
			for (Map.Entry<String, Object> entry : tmp.entrySet()) {
				String key = entry.getKey();
				Object value = entry.getValue();
				if (StrUtil.equals(key, "payScore")) {
					if (value instanceof Long) {
						Long val = (Long) entry.getValue();
						payScore += val.intValue();
					} else if (value instanceof Integer) {
						Integer val = (Integer) entry.getValue();
						payScore += val;
					} else if (value instanceof BigDecimal) {
						BigDecimal val = (BigDecimal) entry.getValue();
						payScore += val.intValue();
					}
				} else if (StrUtil.equals(key, "ysh")) {
					if (value instanceof Long) {
						Long val = (Long) entry.getValue();
						ysh += val.intValue();
					} else if (value instanceof Integer) {
						Integer val = (Integer) entry.getValue();
						ysh += val;
					} else if (value instanceof BigDecimal) {
						BigDecimal val = (BigDecimal) entry.getValue();
						ysh += val.intValue();
					}
				}
			}

		}

		return ImmutableMap.of("payScore", payScore, "ysh", ysh);

	}


	public WmScorePackage step4(Map<String, Integer> payScoreAndYsh, WmScorePackage wmScorePackage) {
		int payScore = payScoreAndYsh.get("payScore");
		int ysh = payScoreAndYsh.get("ysh");

		BigDecimal payRate = new BigDecimal(payScore).multiply(BigDecimal.valueOf(100))
				.divide(new BigDecimal(wmScorePackage.getScore()), 2, BigDecimal.ROUND_HALF_UP);
		if (payRate.compareTo(new BigDecimal("100")) >= 0) {
			wmScorePackage.setPayRate(100 + ".00");
		} else {
			wmScorePackage.setPayRate(payRate + "");
		}

		BigDecimal fin = new BigDecimal(ysh).multiply(BigDecimal.valueOf(100))
				.divide(new BigDecimal(wmScorePackage.getScore()), 2, BigDecimal.ROUND_HALF_UP);
		if (fin.compareTo(new BigDecimal("100")) > 0) {
			wmScorePackage.setFinishRate(100 + ".00");
			if ("0".equals(wmScorePackage.getPackageFinishStatus())) {
				wmScorePackage.setPackageFinishStatus("1");
			}
		} else {
			wmScorePackage.setFinishRate(fin + "");
		}

		if (wmScorePackage.getFinishRate().equals("100.00")) {
			if ("0".equals(wmScorePackage.getPackageFinishStatus())) {
				wmScorePackage.setPackageFinishStatus("1");
			}
		}

		wmScorePackage.setPayScore(payScoreAndYsh.get("payScore"));
		wmScorePackage.setYsh(payScoreAndYsh.get("ysh"));

		return wmScorePackage;
	}
}
