/*
 *    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.CollectionUtil;
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.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDeptRelation;
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.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.ding.enums.DingEnum;
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.apache.poi.xssf.extractor.XSSFExportToXml;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 积分包
 *
 * @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;

	@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 sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept sysDept = sysDeptMapper.selectDeptId(sysDept1);
		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.getScorePackagekList(page, wmScorePackage);
		List<WmScorePackage> records = pages.getRecords();
		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();
//				wmScorePackage1.setScore(); TODO 这个怎么转换
				if (StringUtils.isNumeric(userScore)) {
					wmScorePackage1.setUserScore(String.format("%.2f", Integer.parseInt(userScore) / 100.0));
				}
			}

			if (wmScorePackage1.getYshtt() != null && wmScorePackage1.getYshtt() > 100) {
				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);
			}
			//if(wmScorePackage1.getTypeid().equals("3")){
			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)));
			//}
		}
		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");//已完成待结算
			//部分终止，收回剩余积分值，没有审核的任务继续审核
			//先更新任务状态为已审核
			Integer resSum = 0;//收回值
			if (null != scorestatusList && scorestatusList.size() > 0) {
				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;
					if (taskList1 == null || taskList1.size() == 0) {
						if (wmScorePackage.getPackageType1().equals("1") || wmScorePackage.getPackageType1().equals("5")) {//定额
							//这个用户还没有做任务时，积分值设为0
							wmScorePackageStatus.setUserScore("0");
							wmScorePackage.setScore(wmScorePackage.getScore() - Integer.valueOf(wmScorePackageStatus.getUserScore()));
							resSum += Integer.valueOf(wmScorePackageStatus.getUserScore());
						} else {//2，3 定量
							//定量收回任务个数
							//定量收回任务个数
							wmScorePackageStatus.setTaskNum(0);
						}
						//resSum=wmScorePackage.getScore();
						wmScorePackage.setPackageFinishStatus("1");//已完成

					} else {
						if (wmScorePackage.getPackageType1().equals("1") || wmScorePackage.getPackageType1().equals("5")) {//定额
							Integer sum = taskList1.stream().mapToInt(WmTask::getScore).sum();
							res = Integer.valueOf(wmScorePackageStatus.getUserScore()) - sum;
							if (res > 0) {//个人积分包值大于任务积分值
								wmScorePackageStatus.setUserScore(sum + "");
								resSum += res;
							}
						} 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");
					wmScorePackageStatus.setEnableType("2");
					wmScorePackageStatusService.updateById(wmScorePackageStatus);
				}
				//更新积分包的积分总值
				if (resSum > 0) {
					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");//已完成待结算
			}
			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);


	}
}
