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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.constant.CacheConstants;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.config.TaxNotifyConfig;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleAmountMonitorInput;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleNoteStatusOutput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageSettleInput;
import com.qunzhixinxi.hnqz.admin.entity.output.SettleAmountMonitorOutput;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysUserMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmPayOffMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.ding.config.DingConfig;
import com.qunzhixinxi.hnqz.common.ding.entity.*;
import com.qunzhixinxi.hnqz.common.ding.enums.DingEnum;
import com.qunzhixinxi.hnqz.common.ding.service.DingService;
import com.qunzhixinxi.hnqz.common.security.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import com.qunzhixinxi.hnqz.common.taxhelper.config.TaxHelperConfig;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperSettlementModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperSettlementRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.response.TaxHelperResponse;
import com.qunzhixinxi.hnqz.common.taxhelper.enums.TaxHelperCertStatus;
import com.qunzhixinxi.hnqz.common.taxhelper.service.TaxHelperService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 结算表
 *
 * @author Liujh
 * @date 2020-12-1
 */
@Slf4j
@Service
@AllArgsConstructor
public class WmPayOffServiceImpl extends ServiceImpl<WmPayOffMapper, WmPayOff> implements WmPayOffService {

	private final WmPayOffMapper wmPayOffMapper;
	private final SysUserMapper sysUserMapper;
	private final DingService dingService;
	private final WmScorePackageService wmScorePackageService;
	private final WmTaskService wmTaskService;
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final WmScorePackageSettleNoteService noteService;
	private final SysDeptService sysDeptService;
	private final SysDeptSubService sysDeptSubService;
	private final RedisTemplate redisTemplate;
	private final WmImportUserService importUserService;
	private final MonitoringIndicatorService monitoringIndicatorService;
	private final WmDaAgentService wmDaAgentService;
	private final WmDaDrugEntService wmDaDrugEntService;
	private final TaxHelperService taxHelperService;
	private final TaxNotifyConfig taxNotifyConfig;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R settleBack(WmScorePackageSettleInput input) {
		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());

		if (wmScorePackage.getSettleStatus() != 2 && wmScorePackage.getSettleStatus() != 9) {
			return R.failed("积分包结算状态异常,不能回退");
		}
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setId(wmScorePackage.getId());
		updateEntity.setScorePackageStatus("4");
		updateEntity.setSettleFlag("0");
		wmScorePackageService.updateById(updateEntity);

		WmScorePackageSettleNote deleteQuery = new WmScorePackageSettleNote();
		deleteQuery.setPackageId(input.getId());
		noteService.remove(Wrappers.query(deleteQuery));

		return R.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveSettleInfo(List<WmScorePackage> wsList) {

		return R.ok();
	}


	@Override
	public R settleById(WmScorePackageSettleInput input) {

		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());

//		if ("2".equals(wmScorePackage.getPackageType2())) {
//			return settleType2Package(wmScorePackage);
//		}

		if (!"1".equals(wmScorePackage.getPackageFinishStatus())) {
			return R.failed("积分包状态异常");
		}

		List<WmScorePackageSettleNote> notes;
		WmScorePackageSettleNote noteQuery = new WmScorePackageSettleNote();
		noteQuery.setPackageId(input.getId());
		notes = noteService.list(Wrappers.query(noteQuery));

		if (CollectionUtils.isEmpty(notes)) {

			WmScorePackageStatus statusQuery = new WmScorePackageStatus();
			statusQuery.setPackageId(wmScorePackage.getId());
			statusQuery.setStatus("2");
			List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(Wrappers.query(statusQuery));
			/**
			 * 根据任务完成情况  生成结算记录
			 */
			if (CollectionUtils.isEmpty(statusList)) {
				return R.failed("积分包状态异常");
			}
			for (WmScorePackageStatus status : statusList) {
				WmScorePackageSettleNote note = new WmScorePackageSettleNote();
				String settleNo = UUID.randomUUID().toString().replace("-", "");
				note.setSettleNo(settleNo);
				note.setPackageStatusId(status.getId() + "");
				note.setPackageId(status.getPackageId());
				if ("1".equals(wmScorePackage.getPackageType1())) {
					note.setSettleAmount(StringUtils.isEmpty(status.getUserScore()) ?
							new BigDecimal(0.00) : new BigDecimal(status.getUserScore()).setScale(2, BigDecimal.ROUND_HALF_UP));
				} else if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
					// 如果是患者教育，则转换积分值 '分'->'元'
					note.setSettleAmount(StringUtils.isEmpty(status.getUserScore()) ?
							new BigDecimal(0.00) :
							new BigDecimal(status.getUserScore()).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_EVEN));
				} else {
					note.setSettleAmount(StringUtils.isEmpty(wmScorePackage.getUserScore()) ?
							new BigDecimal(0.00) : new BigDecimal(wmScorePackage.getUserScore()).setScale(2, BigDecimal.ROUND_HALF_UP));
				}

				note.setDiscount(new BigDecimal(1));
				note.setUserId(status.getUserId());
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_NO.getType());
				SysUser noteUser = sysUserMapper.selectById(status.getUserId());
				note.setRealName(noteUser.getRealname());
				note.setIdCardNumber(noteUser.getIdCardNumber());
				notes.add(note);
			}
//			noteService.saveBatch(notes);
		} else {
//			notes.forEach(item -> item.setRealName(sysUserMapper.selectById(item.getUserId()).getRealname()));
			notes.forEach(item->{
				SysUser user = sysUserMapper.selectById(item.getUserId());
				item.setRealName(user.getRealname());
				item.setIdCardNumber(user.getIdCardNumber());
			});
		}

		Map<String, Object> resultMap = new HashMap<>();
		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
			// 如果是患者教育，则转换积分值 '分'->'元'
			wmScorePackage.setUserScore(new BigDecimal(wmScorePackage.getUserScore())
					.divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString());
		}
		resultMap.put("wsp", wmScorePackage);
		resultMap.put("notes", notes);
		/**
		 * 显示实际完成积分值
		 */
		resultMap.put("finishScore", "0");
		if (PackageTypeEnum.TYPE1_SCOTE_PACKAGE.val().equals(wmScorePackage.getPackageType1())
				|| PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
			WmTask query = new WmTask();
			query.setRealFlag("0");
			query.setScorePackageId(wmScorePackage.getId());
			query.setTaskStatus("3");
			//.lambda().ne(WmTask::getTaskStatus,"4")
			List<WmTask> tasks = wmTaskService.list(Wrappers.query(query));
			BigDecimal total = new BigDecimal(0);
			for (WmTask task : tasks) {
				total = total.add(new BigDecimal(task.getScore()));
			}
			if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wmScorePackage.getPackageType1())) {
				// 如果是患者教育，则转换积分值 '分'->'元'
				resultMap.put("finishScore", total.divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_EVEN));
			} else {
				resultMap.put("finishScore", total.intValue());
			}
		}

		return R.ok(resultMap);
	}

	private R settleType2Package(WmScorePackage wmScorePackage) {

		List<WmScorePackageSettleNote> notes;
		WmScorePackageSettleNote noteQuery = new WmScorePackageSettleNote();
		noteQuery.setPackageId(wmScorePackage.getId());
		notes = noteService.list(Wrappers.query(noteQuery));

		if (CollectionUtils.isNotEmpty(notes)) {
			notes.forEach(item -> item.setRealName(importUserService.getById(item.getUserId()).getImportName()));
		} else {
			WmImportUser userQuery = new WmImportUser();
			userQuery.setScoreId(wmScorePackage.getId());
			userQuery.setDelFlag("0");
			List<WmImportUser> userList = importUserService.list(Wrappers.query(userQuery));

			for (WmImportUser wmImportUser : userList) {
				WmScorePackageSettleNote note = new WmScorePackageSettleNote();
				String settleNo = UUID.randomUUID().toString().replace("-", "");
				note.setSettleNo(settleNo);
				note.setPackageId(wmScorePackage.getId());
				note.setSettleAmount(wmScorePackage.getScore() == null ?
						new BigDecimal(0.00) : new BigDecimal(wmScorePackage.getScore()).setScale(2, BigDecimal.ROUND_HALF_UP));

				note.setDiscount(new BigDecimal(1));
				note.setUserId(wmImportUser.getId() + "");
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_NO.getType());
				note.setRealName(importUserService.getById(wmImportUser.getId()).getImportName());
				notes.add(note);
			}
//			noteService.saveBatch(notes);
		}
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("wsp", wmScorePackage);
		resultMap.put("notes", notes);

		return R.ok(resultMap);
	}

	@Override
	public R settleSubmit(WmScorePackageSettleInput input) {
		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());
		if (!"0".equals(wmScorePackage.getSettleFlag())) {
			return R.failed("结算状态异常，请勿重复结算");
		}
		List<WmScorePackageSettleNote> notes = input.getNotes();

		for (WmScorePackageSettleNote note : notes) {
			SysUser user = sysUserMapper.selectById(note.getUserId());
			if(StringUtils.isEmpty(user.getIdCardNumber())){
				return R.failed(user.getRealname()+"未认证，不能发起结算");
			}
			if("0".equals(input.getSubType())){
				if (!Objects.equals(user.getRljCertStatus(), DingEnum.CER_STATUS_1.getType())) {
					return R.failed(user.getRealname()+"未认证，不能发起结算");
				}
			}
			if("1".equals(input.getSubType())){
				if (!Objects.equals(user.getCertStatus(), TaxHelperCertStatus.CERT.getCode())) {
					return R.failed(user.getRealname()+"人员未认证或未绑卡，不能结算");
				}
			}
		}

		/**
		 * @Modify: start 校验当月结算额度
		 * @Version: 2021.4.16
		 * @Author: ryz
		 * @Date: 2021/4/22
		 */
		List<String> idCard = notes.stream().map(WmScorePackageSettleNote::getIdCardNumber).collect(Collectors.toList());
		List<Integer> ids = notes.stream().filter(item->null != item.getId()).map(WmScorePackageSettleNote::getId).collect(Collectors.toList());
		List<String> userIds = notes.stream().map(WmScorePackageSettleNote::getUserId).collect(Collectors.toList());

		SettleAmountMonitorInput monitorInput = SettleAmountMonitorInput.fromIdCard(idCard, ids,input.getSubType());
		List<SettleAmountMonitorOutput> monitorOutputList = sysDeptSubService.getSettleAmountMonitor(monitorInput);

		SettleAmountMonitorInput deptMonitorInput = SettleAmountMonitorInput.fromUserId(userIds, ids,input.getSubType());
		List<SettleAmountMonitorOutput> deptAmountMonitor = sysDeptSubService.getDeptAmountMonitor(deptMonitorInput);

		SysDeptSub condition = new SysDeptSub();
		condition.setDeptId(SecurityUtils.getUser().getDeptId());
		condition.setSubjectType(input.getSubType());
		condition.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.query(condition));
		if (null == sysDeptSub || StringUtils.isBlank(sysDeptSub.getAppId())) {
			return R.failed("人员所在机构未配置结算信息");
		}

		MonitoringIndicator monitoringIndicator = monitoringIndicatorService.getBySubType(input.getSubType());

		BigDecimal deptLimit = sysDeptSub.getLimitAmount();
		BigDecimal monitoringLimit = monitoringIndicator.getLimitAmount();

		BigDecimal total = new BigDecimal(0);
		LocalDateTime now = LocalDateTime.now();
		for (WmScorePackageSettleNote note : notes) {
			total = total.add(note.getSettleAmount());
			BigDecimal monitorAmount = note.getSettleAmount();
			BigDecimal deptMonitorAmount = note.getSettleAmount();
			SettleAmountMonitorOutput monitorOutput = monitorOutputList.stream().filter(item -> item.getIdCardNumber()
					.equals(note.getIdCardNumber())).findFirst().orElse(null);

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

			if (null != monitorOutput) {
				monitorAmount = monitorAmount.add(monitorOutput.getTotalAmount());
			}
			if (null != deptMonitorOutput) {
				deptMonitorAmount = deptMonitorAmount.add(deptMonitorOutput.getTotalAmount());
			}
			if (null != deptLimit) {
				if (deptMonitorAmount.compareTo(deptLimit) > 0) {
					return R.failed(note.getRealName() + "：超过当月限额");
				}
			}
			if (null != monitoringLimit) {
				if (monitorAmount.compareTo(monitoringLimit) > 0) {
					return R.failed(note.getRealName() + "：超过结算渠道限额");
				}
			}

			note.setUpdateTime(now);
			note.setSubTime(now);
			note.setSubType(input.getSubType());
			note.setInvoiceType(input.getInvoiceCategory());
			note.setCategoryName(input.toCategoryName());
			if(null == note.getId()){
				note.setCreateTime(LocalDateTime.now());
			}
		}
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setInvoiceCategory(input.getInvoiceCategory());
		updateEntity.setSettleAmount(total);
		updateEntity.setId(input.getId());
		updateEntity.setSettleStatus(DingEnum.SETTLE_STATUS_WAIT.getType());
		updateEntity.setScorePackageStatus("5");
		updateEntity.setSettleFlag("1");
		updateEntity.setDescription(input.getDescription());
		updateEntity.setSubType(input.getSubType());
		updateEntity.setSettlementDate(LocalDateTime.now());

		if ("2".equals(wmScorePackage.getPackageType2())) {
			updateEntity.setPackageFinishStatus("1");
			updateEntity.setTaskAddFlag("0");
		}

		wmScorePackageService.updateById(updateEntity);
		noteService.saveOrUpdateBatch(notes);

		return R.ok();
	}

	@Override
	public R settleSave(WmScorePackageSettleInput input) {
//		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());

		List<WmScorePackageSettleNote> notes = input.getNotes();

		for (WmScorePackageSettleNote note : notes) {
			SysUser user = sysUserMapper.selectById(note.getUserId());
			if(StringUtils.isEmpty(user.getIdCardNumber())){
				return R.failed(user.getRealname()+"未认证，不能发起结算");
			}
			if("0".equals(input.getSubType())){
				if (!Objects.equals(user.getRljCertStatus(), DingEnum.CER_STATUS_1.getType())) {
					return R.failed(user.getRealname()+"未认证，不能发起结算");
				}
			}
			if("1".equals(input.getSubType())){
				if (!Objects.equals(user.getCertStatus(), TaxHelperCertStatus.CERT.getCode())) {
					return R.failed(user.getRealname()+"人员未认证或未绑卡，不能结算");
				}
			}
		}
		/**
		 * @Modify: start 校验当月结算额度
		 * @Version: 2021.4.16
		 * @Author: ryz
		 * @Date: 2021/4/22
		 */
		List<String> idCard = notes.stream().map(WmScorePackageSettleNote::getIdCardNumber).collect(Collectors.toList());
		List<Integer> ids = notes.stream().filter(item->null != item.getId()).map(WmScorePackageSettleNote::getId).collect(Collectors.toList());
		List<String> userIds = notes.stream().map(WmScorePackageSettleNote::getUserId).collect(Collectors.toList());

		SettleAmountMonitorInput monitorInput = SettleAmountMonitorInput.fromIdCard(idCard, ids, input.getSubType());
		List<SettleAmountMonitorOutput> monitorOutputList = sysDeptSubService.getSettleAmountMonitor(monitorInput);

		SettleAmountMonitorInput deptMonitorInput = SettleAmountMonitorInput.fromUserId(userIds, ids, input.getSubType());
		List<SettleAmountMonitorOutput> deptAmountMonitor = sysDeptSubService.getDeptAmountMonitor(deptMonitorInput);

		SysDeptSub condition = new SysDeptSub();
		condition.setDeptId(SecurityUtils.getUser().getDeptId());
		condition.setSubjectType(input.getSubType());
		condition.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.query(condition));

		if (null == sysDeptSub || StringUtils.isBlank(sysDeptSub.getAppId())) {
			return R.failed("人员所在机构未配置结算信息");
		}

		MonitoringIndicator monitoringIndicator = monitoringIndicatorService.getBySubType(input.getSubType());

		BigDecimal deptLimit = sysDeptSub.getLimitAmount();
		BigDecimal monitoringLimit = monitoringIndicator.getLimitAmount();

		BigDecimal total = new BigDecimal(0);
		for (WmScorePackageSettleNote note : notes) {
			total = total.add(note.getSettleAmount());
			BigDecimal monitorAmount = note.getSettleAmount();
			BigDecimal deptMonitorAmount = note.getSettleAmount();
			SettleAmountMonitorOutput monitorOutput = monitorOutputList.stream().filter(item -> item.getIdCardNumber()
					.equals(note.getIdCardNumber())).findFirst().orElse(null);

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

			if (null != monitorOutput) {
				monitorAmount = monitorAmount.add(monitorOutput.getTotalAmount());
			}
			if (null != deptMonitorOutput) {
				deptMonitorAmount = deptMonitorAmount.add(deptMonitorOutput.getTotalAmount());
			}
			if (null != deptLimit) {
				if (deptMonitorAmount.compareTo(deptLimit) > 0) {
					return R.failed(note.getRealName() + "：超过当月限额");
				}
			}
			if (null != monitoringLimit) {
				if (monitorAmount.compareTo(monitoringLimit) > 0) {
					return R.failed(note.getRealName() + "：超过结算渠道限额");
				}
			}

			note.setInvoiceType(input.getInvoiceCategory());
			note.setUpdateTime(LocalDateTime.now());
			note.setSubType(input.getSubType());
			note.setInvoiceType(input.getInvoiceCategory());
			note.setCategoryName(input.toCategoryName());
			if(null == note.getId()){
				note.setCreateTime(LocalDateTime.now());
			}

		}
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setInvoiceCategory(input.getInvoiceCategory());
		updateEntity.setSettleAmount(total);
		updateEntity.setId(input.getId());
		updateEntity.setDescription(input.getDescription());
		updateEntity.setSubType(input.getSubType());

//		updateEntity.setSettleStatus(DingEnum.SETTLE_STATUS_WAIT.getType());

		wmScorePackageService.updateById(updateEntity);
		noteService.saveOrUpdateBatch(notes);

		return R.ok();
	}

	@Override
	public R settleReIssueBySubType(WmScorePackageSettleInput input) {
		WmScorePackageSettleNote note = noteService.getById(input.getId());

		WmScorePackage wmScorePackage = wmScorePackageService.getById(note.getPackageId());
		String settleNo = UUID.randomUUID().toString().replace("-", "");
		note.setSettleNo(settleNo);

		List<WmScorePackageSettleNote> notes = new ArrayList<>();
		notes.add(note);
		input.setNotes(notes);
		input.setInvoiceCategory(note.getInvoiceType());
		input.setSubType(note.getSubType());
		input.setScorePackageName(wmScorePackage.getScorePackageName());

		if (!DingEnum.NOTE_STATUS_FAIL.getType().equals(note.getSettleNoteStatus())) {
			return R.failed("状态异常，请刷新页面后再操作");
		}
		/**
		 * 结算配置信息
		 */
		SysDeptSub condition = new SysDeptSub();
		condition.setDeptId(SecurityUtils.getUser().getDeptId());
		condition.setSubjectType(input.getSubType());
		condition.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.query(condition));

		if (null == sysDeptSub || StringUtils.isEmpty(sysDeptSub.getAppId())) {
			return R.failed("机构appId未维护");
		}

		if (SubjectTypeEnum.TYPE_RENLIJIA.getCode().equals(input.getSubType())) {
			return settleByRenLiJia(input, sysDeptSub, wmScorePackage);
		} else {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

			String taxCode = sysDept.getTaxCode();
			if (StringUtils.isNotEmpty(taxCode)) {
				log.info("税邦云结算开始-获取会员所属企业的统一社会信用代码：{} ", taxCode);
			} else {
				return R.failed("未配置企业的统一社会信用代码");
			}
			return settleByShuiBangYun(input, sysDeptSub, wmScorePackage,taxCode);
		}

	}

	@Override
	public R settleIssueBySubType(WmScorePackageSettleInput input) {

		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());

		if (wmScorePackage.getSettleStatus() != 2 && wmScorePackage.getSettleStatus() != 9) {
			return R.failed("积分包结算状态异常");
		}

		/**
		 * 结算配置信息
		 */
		SysDeptSub condition = new SysDeptSub();
		condition.setDeptId(SecurityUtils.getUser().getDeptId());
		condition.setSubjectType(input.getSubType());
		condition.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.query(condition));

		if (null == sysDeptSub || StringUtils.isEmpty(sysDeptSub.getAppId())) {
			return R.failed("机构appId未维护");
		}

		if (SubjectTypeEnum.TYPE_RENLIJIA.getCode().equals(input.getSubType())) {
			return settleByRenLiJia(input, sysDeptSub, wmScorePackage);
		} else {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

			String taxCode = sysDept.getTaxCode();
			if (StringUtils.isNotEmpty(taxCode)) {
				log.info("税邦云结算开始-获取会员所属企业的统一社会信用代码：{} ", taxCode);
			} else {
				return R.failed("未配置企业的统一社会信用代码");
			}
			return settleByShuiBangYun(input, sysDeptSub, wmScorePackage,taxCode);
		}

	}

	private R settleByShuiBangYun(WmScorePackageSettleInput input,
								  SysDeptSub sysDeptSub,
								  WmScorePackage wmScorePackage,
								  String taxCode) {
		List<WmScorePackageSettleNote> notes = input.getNotes();
		StringBuilder noticeInfo = new StringBuilder();


		/**
		 * WmScorePackageSettleNote
		 */
		for (WmScorePackageSettleNote note : notes) {
			note.setInvoiceType(input.getInvoiceCategory());
			note.setCategoryName(input.toCategoryName());
			note.setSubToGigTime(LocalDateTime.now());
		}
		noteService.updateBatchById(notes);



		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);
			SysUser sysUser = sysUserMapper.selectById(note.getUserId());

			if (!Objects.equals(sysUser.getCertStatus(), TaxHelperCertStatus.CERT.getCode())) {
				return R.failed(sysUser.getRealname() + "人员未认证或未绑卡，不能结算");
			}

			if (redisTemplate.hasKey(CacheConstants.SETTLE_PACKAGE_KEY + note.getId())) {
				return R.failed("结算对象-" + sysUser.getRealname() + "：正在结算，请勿重复结算");
			}

			if (DingEnum.NOTE_STATUS_SUCCESS.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
			}
			if (DingEnum.NOTE_STATUS_SUBMIT.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
			}

		}

		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);

			/**
			 * 加锁
			 */
			redisTemplate.opsForValue().set(CacheConstants.SETTLE_PACKAGE_KEY + note.getId(),
					note.getId(), CacheConstants.SETTLE_TIME, TimeUnit.DAYS);

			SysUser sysUser = sysUserMapper.selectById(note.getUserId());

			TaxHelperConfig config = new TaxHelperConfig();
			config.setAppId(sysDeptSub.getAppId());
			config.setAppSecrete(sysDeptSub.getAppSecret());
			config.setQueryUrl(sysDeptSub.getQueryUrl());

			/**
			 * 开始结算
			 */
			TaxHelperSettlementModel taxHelperSettlementModel = new TaxHelperSettlementModel(config);
			taxHelperSettlementModel.setEnterpriseCode(taxCode);

			taxHelperSettlementModel.setExtendFieldNames(Arrays.asList("报告下载地址"));
			taxHelperSettlementModel.setCount(1);

			taxHelperSettlementModel.setNotifyUrl(taxNotifyConfig.getNotifyUrl() + "/admin/taxhelper/" + sysUser.getUserId() + "/settlementNotify");
			TaxHelperSettlementModel.DetailedArr detailedArr = new TaxHelperSettlementModel.DetailedArr();
			detailedArr.setIdCard(sysUser.getIdCardNumber());
			detailedArr.setInputAmount(note.getSettleAmount().doubleValue());
			detailedArr.setCategoryName(note.getCategoryName());
			taxHelperSettlementModel.setDetailedArr(Arrays.asList(detailedArr));

			TaxHelperSettlementModel.AbstractArr abstractArr = new TaxHelperSettlementModel.AbstractArr();

			abstractArr.setIdCard(sysUser.getIdCardNumber());
			abstractArr.setNumber(1);
			abstractArr.setPrice(note.getSettleAmount().doubleValue());
			abstractArr.setAmount(note.getSettleAmount().doubleValue());

			// abstractArr.setExtendField1(taxNotifyConfig.getTaskUrl() + "/admin/api/h5PackagePage?current=1&size=20&id=" + wmScorePackage.getScorePackageName());
			abstractArr.setExtendField1(taxNotifyConfig.getTaskUrl() + "/#/h5/indexTask?id=" + note.getPackageId() + "&userId=" + note.getUserId());

			taxHelperSettlementModel.setAbstractArr(Arrays.asList(abstractArr));

			TaxHelperSettlementRequest taxHelperSettlementRequest = new TaxHelperSettlementRequest(taxHelperSettlementModel);

			TaxHelperResponse response = taxHelperService.settlement(taxHelperSettlementRequest);

			log.info("税邦云结算： {}", response);


			if (response.success()) {
				log.info("税邦云结算提交成功： {}", note.getSettleNo());
				//streamId 获取不到
				if (StringUtils.isEmpty(response.getMessage())) {
					log.info("税邦云结算提交成功 streamId 获取不到： {}", note.getSettleNo());
					noticeInfo.append(sysUser.getRealname() + "：提交结算成功，业务流水号获取不到，请联系管理员；");
				}
				note.setUpdateTime(LocalDateTime.now());
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());
				// 新增字段streamId
				note.setStreamId(response.getMessage());
				noticeInfo.append(sysUser.getRealname() + "：提交结算成功；");
			} else {
				log.info("税邦云结算提交失败： {}", note.getSettleNo());
				note.setUpdateTime(LocalDateTime.now());
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
				noticeInfo.append(sysUser.getRealname() + "：结算提交失败-" + response.getMessage() + "；");

				log.info("认证状态异常，结算解锁settleNoteId：{}", note.getId());
				redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

			}
		}

		noteService.updateBatchById(notes);

		/**
		 * 更新结算结果
		 */
		SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(input.getId());
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setId(input.getId());
		updateEntity.setSettleStatus(output.toSettleStatus());
		wmScorePackageService.updateById(updateEntity);

		return R.ok(null, noticeInfo.toString());
	}

	private R settleByRenLiJia(WmScorePackageSettleInput input, SysDeptSub sysDeptSub, WmScorePackage wmScorePackage) {
		List<WmScorePackageSettleNote> notes = input.getNotes();

		for (WmScorePackageSettleNote note : notes) {
			note.setInvoiceType(input.getInvoiceCategory());
			note.setCategoryName(input.toCategoryName());
			note.setSubToGigTime(LocalDateTime.now());
		}
		noteService.updateBatchById(notes);

		/**
		 * 发起结算
		 */
		log.info("结算包ID： {} 开始结算-----------", input.getId());
		log.info("结算渠道： {} ", input.getSubType());
		/**
		 * 1.校验身份证信息
		 */
		DingConfig config = new DingConfig();
		config.setAppId(sysDeptSub.getAppId());
		config.setAppSecret(sysDeptSub.getAppSecret());
		config.setQueryUrl(sysDeptSub.getQueryUrl());

		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);

			SysUser sysUser = sysUserMapper.selectById(note.getUserId());

			if (StringUtils.isEmpty(sysUser.getIdCardNumber())) {
				log.info("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录");
				// 添加登录提醒
				redisTemplate.opsForValue().set(CacheConstants.USER_NOTICE_KEY + sysUser.getUserId(), "1", CacheConstants.NOTICE_TIME, TimeUnit.DAYS);
				return R.failed("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录");
			}

			if (!DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
				//认证中
				log.info("结算对象-" + sysUser.getRealname() + "：未认证成功，不能结算");
				return R.failed("结算对象-" + sysUser.getRealname() + "：未认证成功，不能结算");
			}

			if (redisTemplate.hasKey(CacheConstants.SETTLE_PACKAGE_KEY + note.getId())) {
				return R.failed("结算对象-" + sysUser.getRealname() + "：正在结算，请勿重复结算");
			}

			if (DingEnum.NOTE_STATUS_SUCCESS.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
			}
			if (DingEnum.NOTE_STATUS_SUBMIT.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
			}
		}

		// 进入结算环节  noticeInfo 失败原因
		StringBuilder noticeInfo = new StringBuilder();
		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);

			/**
			 * 结算失败过的更新 settleNo
			 */
			if (DingEnum.NOTE_STATUS_FAIL.getType().equals(note.getSettleNoteStatus())) {
				String settleNo = UUID.randomUUID().toString().replace("-", "");
				note.setSettleNo(settleNo);
			}

			/**
			 * 加锁
			 */
			redisTemplate.opsForValue().set(CacheConstants.SETTLE_PACKAGE_KEY + note.getId(),
					note.getId(), CacheConstants.SETTLE_TIME, TimeUnit.DAYS);

			SysUser sysUser = sysUserMapper.selectById(note.getUserId());

			/**
			 * 3.校验认证信息
			 */
			if (DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
				//认证成功  发起结算
				//当前登陆人的机构名称
				String subjectName = sysDeptSub.getSubjectName();

				List jsdList = new ArrayList();
				Map jsdMap = new HashMap();
				jsdMap.put("amount", note.getSettleAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
				jsdMap.put("mobile", sysUser.getPhone());
				jsdMap.put("idCard", sysUser.getIdCardNumber());
				jsdMap.put("name", sysUser.getRealname());
				jsdList.add(jsdMap);

				EmployPayResponse employPayResponse = dingService.pay(config, subjectName,
						note.getSettleNo(), input.getScorePackageName(),
						input.getInvoiceCategory(), jsdList);

				//提交结算接口失败
				if (!employPayResponse.isSuccess()) {
					log.info("人力家接口调用失败，结算解锁settleNoteId：{}", note.getId());
					redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
					noticeInfo.append("结算对象-" + sysUser.getRealname() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());
					note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());

				} else {
					//结算提交成功数据
					List<EmployPayResultSuccessItem> successResult = employPayResponse.getData().getSuccessResult();
					if (CollectionUtils.isNotEmpty(successResult)) {

						log.info("结算对象-" + sysUser.getRealname() + "：提交结算成功；");
						noticeInfo.append("结算对象-" + sysUser.getRealname() + "：提交结算成功；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());

						savePayoffFormNote(note);

					}

					//结算提交失败的数据
					List<EmployPayResultfailItem> failResult = employPayResponse.getData().getFailResult();
					if (CollectionUtils.isNotEmpty(failResult)) {

						log.info("认证状态异常，结算解锁settleNoteId：{}", note.getId());
						redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

						log.info("结算对象-" + sysUser.getRealname() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						noticeInfo.append("结算对象-" + sysUser.getRealname() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
					}
				}

			} else {
				log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
				redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
			}

		}

		noteService.updateBatchById(notes);

		/**
		 * 更新结算结果
		 */
		SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(input.getId());
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setId(input.getId());
		updateEntity.setSettleStatus(output.toSettleStatus());
		wmScorePackageService.updateById(updateEntity);

		return R.ok("", noticeInfo.toString());
	}

	@Override
	public R settleIssue(WmScorePackageSettleInput input) {

		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getId());

		if (wmScorePackage.getSettleStatus() != 2 && wmScorePackage.getSettleStatus() != 9) {
			return R.failed("积分包结算状态异常");
		}

		List<WmScorePackageSettleNote> notes = input.getNotes();

//		BigDecimal total = new BigDecimal(0);
		for (WmScorePackageSettleNote note : notes) {
//			total = total.add(note.getSettleAmount());
			note.setInvoiceType(input.getInvoiceCategory());
		}
		noteService.updateBatchById(notes);

//		WmScorePackage updateEntity = new WmScorePackage();
//		updateEntity.setInvoiceCategory(input.getInvoiceCategory());
//		updateEntity.setSettleAmount(total);
//		updateEntity.setId(input.getId());
//
//		wmScorePackageService.updateById(updateEntity);

//		if ("2".equals(wmScorePackage.getPackageType2())) {
//			return settleIssueType2Package(input);
//		}

		/**
		 * 发起结算
		 */
		log.info("结算包ID： {} 开始结算-----------", input.getId());
		/**
		 * 1.校验身份证信息
		 */
		Integer currentUserId = SecurityUtils.getUser().getId();
		SysUser currentUser = sysUserMapper.selectById(currentUserId);
		SysDept sysDept = sysDeptService.getById(currentUser.getDeptId());
		if (StringUtils.isEmpty(sysDept.getAppId())) {
			return R.failed("机构appId未维护");
		}
		DingConfig config = new DingConfig();
		config.setAppId(sysDept.getAppId());
		config.setAppSecret(sysDept.getAppSecret());
		config.setQueryUrl(sysDept.getQueryUrl());

		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);
			SysUser sysUser = sysUserMapper.selectById(note.getUserId());
			if (redisTemplate.hasKey(CacheConstants.SETTLE_PACKAGE_KEY + note.getId())) {
				return R.failed("结算对象-" + sysUser.getRealname() + "：正在结算，请勿重复结算");
			}

			if (DingEnum.NOTE_STATUS_SUCCESS.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已结算，请勿重复结算");
			}
			if (DingEnum.NOTE_STATUS_SUBMIT.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
				return R.failed("结算对象-" + sysUser.getRealname() + "：已提交，请等待耐心结算结果");
			}

			/**
			 * 1.校验身份证信息
			 */
			if (StringUtils.isEmpty(sysUser.getIdCardNumber())) {
				log.info("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录");
				// 添加登录提醒  TODO 发送短信提醒
				redisTemplate.opsForValue().set(CacheConstants.USER_NOTICE_KEY + sysUser.getUserId(), "1", CacheConstants.NOTICE_TIME, TimeUnit.DAYS);
				return R.failed("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录");
			}

			if (notes.size() == 1) {
				if (DingEnum.CER_STATUS_3.getType().equals(sysUser.getRljCertStatus())) {
					//认证中
					log.info("结算对象-" + sysUser.getRealname() + "：正在认证中，不能结算");
					return R.failed("结算对象-" + sysUser.getRealname() + "：正在认证中，不能结算");
				} else if (DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
					continue;
				} else {
					//需要发起认证

					List rzlist = new ArrayList();
					Map map = new HashMap();
					map.put("name", sysUser.getRealname());
					map.put("mobile", sysUser.getPhone());
					map.put("idCard", sysUser.getIdCardNumber());
					map.put("idType", "1");
					rzlist.add(map);
					EmployCheckResponse response = dingService.check(config, rzlist);
					if (!response.isSuccess()) {
						return R.failed("人力家接口调用失败" + response.getCode() + ":" + response.getMsg());
					}
					//接口请求成功，但是接口返回的状态还需区分checkStatus，1:验证通过，状态改成已提交，2:验证不通过，状态改成认证失败
					List<EmployCheckResultItem> freelancesResult = response.getData().getFreelancesResult();
					if (CollectionUtils.isNotEmpty(freelancesResult) && freelancesResult.size() == 1) {

						EmployCheckResultItem employCheckResultItem = freelancesResult.get(0);

						if (employCheckResultItem.getIdCard().equals(sysUser.getIdCardNumber())) {
							//验证通过
							if (employCheckResultItem.getCheckStatus() == 1) {
								log.info("认证提交成功：{},{}", sysUser.getRealname(), sysUser.getUsername());
								//更新用户的认证状态为认证中
								sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
								sysUserMapper.updateById(sysUser);
								return R.ok("结算对象-" + sysUser.getRealname() + "：提交认证成功，请认证通过后再发起结算");
							} else {
								//验证不通过
								if ("1014".equals(employCheckResultItem.getCheckRemark())) {
									log.info("认证返回1014：{},{}", sysUser.getRealname(), sysUser.getUsername());
									sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
									sysUserMapper.updateById(sysUser);
									return R.ok("结算对象-" + sysUser.getRealname() + "：正在认证中，请认证通过后再发起结算");
								}

								if ("1018".equals(employCheckResultItem.getCheckRemark())) {
									log.info("认证返回1018：{},{}", sysUser.getRealname(), sysUser.getUsername());
									sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
									sysUserMapper.updateById(sysUser);
									return R.ok("结算对象-" + sysUser.getRealname() + "：正在认证中，请认证通过后再发起结算");
								}
								if ("1019".equals(employCheckResultItem.getCheckRemark())) {
									log.info("认证返回1019：{},{}", sysUser.getRealname(), sysUser.getUsername());

									sysUser.setRljCertStatus(DingEnum.CER_STATUS_1.getType());
									sysUserMapper.updateById(sysUser);
									return R.ok("结算对象-" + sysUser.getRealname() + "：认证状态已更新，请重新发起结算");
								}

								sysUser.setRljCertStatus(DingEnum.CER_STATUS_2.getType());
								sysUserMapper.updateById(sysUser);
								//小程序认证失败提醒
								redisTemplate.opsForValue().set(CacheConstants.USER_NOTICE_KEY + sysUser.getUserId(), "1", CacheConstants.NOTICE_TIME, TimeUnit.DAYS);
								return R.ok("结算对象-" + sysUser.getRealname() + "：认证失败，请核实身份信息");

							}
						}
					} else {
						return R.failed("人力家接口调用异常");
					}

				}


			} else {
				if (!DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
					//认证中
					log.info("结算对象-" + sysUser.getRealname() + "：未认证成功，不能结算");
					return R.failed("结算对象-" + sysUser.getRealname() + "：未认证成功，不能结算");
				}
			}
		}

		// 进入结算环节

		StringBuilder noticeInfo = new StringBuilder();//失败原因
		for (int i = 0; i < notes.size(); i++) {
			WmScorePackageSettleNote note = notes.get(i);

			/**
			 * 加锁
			 */
			redisTemplate.opsForValue().set(CacheConstants.SETTLE_PACKAGE_KEY + note.getId(),
					note.getId(), CacheConstants.SETTLE_TIME, TimeUnit.DAYS);

			SysUser sysUser = sysUserMapper.selectById(note.getUserId());

			/**
			 * 3.校验认证信息
			 */
			if (DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
				//认证成功  发起结算
				//当前登陆人的机构名称
				String subjectName = sysDept.getSubjectName();

				List jsdList = new ArrayList();
				Map jsdMap = new HashMap();
				jsdMap.put("amount", note.getSettleAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
				jsdMap.put("mobile", sysUser.getPhone());
				jsdMap.put("idCard", sysUser.getIdCardNumber());
				jsdMap.put("name", sysUser.getRealname());
				jsdList.add(jsdMap);

				EmployPayResponse employPayResponse = dingService.pay(config, subjectName,
						note.getSettleNo(), input.getScorePackageName(),
						input.getInvoiceCategory(), jsdList);

				//提交结算接口失败
				if (!employPayResponse.isSuccess()) {
					log.info("人力家接口调用失败，结算解锁settleNoteId：{}", input.getId());
					redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
					noticeInfo.append("结算对象-" + sysUser.getRealname() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());
					note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());

				} else {
					//结算提交成功数据
					List<EmployPayResultSuccessItem> successResult = employPayResponse.getData().getSuccessResult();
					if (CollectionUtils.isNotEmpty(successResult)) {

						log.info("结算对象-" + sysUser.getRealname() + "：提交结算成功；");
						noticeInfo.append("结算对象-" + sysUser.getRealname() + "：提交结算成功；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());

						savePayoffFormNote(note);

					}

					//结算提交失败的数据
					List<EmployPayResultfailItem> failResult = employPayResponse.getData().getFailResult();
					if (CollectionUtils.isNotEmpty(failResult)) {

						log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
						redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

						log.info("结算对象-" + sysUser.getRealname() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						noticeInfo.append("结算对象-" + sysUser.getRealname() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
					}
				}

			} else {
				log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
				redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
			}

		}

		noteService.updateBatchById(notes);

		/**
		 * 更新结算结果
		 */
		SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(input.getId());
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setId(input.getId());
		updateEntity.setSettleStatus(output.toSettleStatus());
		wmScorePackageService.updateById(updateEntity);

		return R.ok("", noticeInfo.toString());
	}

	/**
	 * PackageType2 = 2 结算
	 *
	 * @param input
	 * @return
	 */
	private R settleIssueType2Package(WmScorePackageSettleInput input) {

		List<WmScorePackageSettleNote> notes = input.getNotes();
		/**
		 * 发起结算
		 */
		log.debug("结算包ID： {} 开始结算-----------", input.getId());
		/**
		 * 1.校验身份证信息
		 */
		Integer currentUserId = SecurityUtils.getUser().getId();
		SysUser currentUser = sysUserMapper.selectById(currentUserId);
		SysDept sysDept = sysDeptService.getById(currentUser.getDeptId());
		if (StringUtils.isEmpty(sysDept.getAppId())) {
			return R.failed("机构appId未维护");
		}
		DingConfig config = new DingConfig();
		config.setAppId(sysDept.getAppId());
		config.setAppSecret(sysDept.getAppSecret());
		config.setQueryUrl(sysDept.getQueryUrl());

		StringBuilder noticeInfo = new StringBuilder();
		//需要发起认证
		List rzlist = new ArrayList();
		for (int i = 0; i < notes.size(); i++) {

			WmScorePackageSettleNote note = notes.get(i);
			WmImportUser importUser = importUserService.getById(note.getUserId());

			if (redisTemplate.hasKey(CacheConstants.SETTLE_PACKAGE_KEY + note.getId())) {
				noticeInfo.append("结算对象-" + importUser.getImportName() + "：正在结算，请勿重复结算；");
				continue;
			}

			if (DingEnum.NOTE_STATUS_SUCCESS.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + importUser.getImportName() + "：已结算，请勿重复结算");
				noticeInfo.append("结算对象-" + importUser.getImportName() + "：已结算，请勿重复结算；");
				continue;
			}
			if (DingEnum.NOTE_STATUS_SUBMIT.getType().equals(note.getSettleNoteStatus())) {
				log.info("结算对象-" + importUser.getImportName() + "：已提交，请等待耐心结算结果");
				noticeInfo.append("结算对象-" + importUser.getImportName() + "：已提交，请等待耐心结算结果；");
				continue;
			}

			if (DingEnum.CER_STATUS_3.getType().equals(importUser.getCertStatus())) {
				//认证中
				log.info("结算对象-" + importUser.getImportName() + "：正在认证中，不能结算");
				noticeInfo.append("结算对象-" + importUser.getImportName() + "：正在认证中，不能结算；");
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
			} else if (DingEnum.CER_STATUS_1.getType().equals(importUser.getCertStatus())) {
				/**
				 * 发起结算  加锁
				 */
				redisTemplate.opsForValue().set(CacheConstants.SETTLE_PACKAGE_KEY + note.getId(),
						note.getId(), CacheConstants.SETTLE_TIME, TimeUnit.DAYS);

				String subjectName = sysDept.getSubjectName();

				List jsdList = new ArrayList();
				Map jsdMap = new HashMap();
				jsdMap.put("amount", note.getSettleAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
				jsdMap.put("mobile", importUser.getImportPhone());
				jsdMap.put("idCard", importUser.getImportIdCardNumber());
				jsdMap.put("name", importUser.getImportName());
				jsdList.add(jsdMap);

				EmployPayResponse employPayResponse = dingService.pay(config, subjectName,
						note.getSettleNo(), input.getScorePackageName(),
						input.getInvoiceCategory(), jsdList);

				//提交结算接口失败
				if (!employPayResponse.isSuccess()) {
					log.info("人力家接口调用失败，结算解锁settleNoteId：{}", input.getId());
					redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
					noticeInfo.append("结算对象-" + importUser.getImportName() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg() + "；");
					note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());

				} else {
					//结算提交成功数据
					List<EmployPayResultSuccessItem> successResult = employPayResponse.getData().getSuccessResult();
					if (CollectionUtils.isNotEmpty(successResult)) {

						log.info("结算对象-" + importUser.getImportName() + "：提交结算成功；");
						noticeInfo.append("结算对象-" + importUser.getImportName() + "：提交结算成功；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());

						savePayoffFormNote(note);
					}

					//结算提交失败的数据
					List<EmployPayResultfailItem> failResult = employPayResponse.getData().getFailResult();
					if (CollectionUtils.isNotEmpty(failResult)) {

						log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
						redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

						log.info("结算对象-" + importUser.getImportName() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						noticeInfo.append("结算对象-" + importUser.getImportName() + "，结算失败：" + failResult.get(0).getCheckRemark() + "；");
						note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
					}
				}


			} else {
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
				Map map = new HashMap();
				map.put("name", importUser.getImportName());
				map.put("mobile", importUser.getImportPhone());
				map.put("idCard", importUser.getImportIdCardNumber());
				map.put("idType", "1");
				rzlist.add(map);
				EmployCheckResponse response = dingService.check(config, rzlist);
				if (!response.isSuccess()) {
					return R.failed("人力家接口调用失败" + response.getCode() + ":" + response.getMsg());
				}
				//接口请求成功，但是接口返回的状态还需区分checkStatus，1:验证通过，状态改成已提交，2:验证不通过，状态改成认证失败
				List<EmployCheckResultItem> freelancesResult = response.getData().getFreelancesResult();
				if (CollectionUtils.isNotEmpty(freelancesResult) && freelancesResult.size() == 1) {

					EmployCheckResultItem employCheckResultItem = freelancesResult.get(0);

					if (employCheckResultItem.getIdCard().equals(importUser.getImportIdCardNumber())) {
						//验证通过
						if (employCheckResultItem.getCheckStatus() == 1) {
							log.info("认证提交成功：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());
							//更新用户的认证状态为认证中
							importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
							importUserService.updateById(importUser);
							noticeInfo.append("结算对象-" + importUser.getImportName() + "：提交认证成功，请认证通过后再发起结算；");
						} else {
							//验证不通过
							if ("1014".equals(employCheckResultItem.getCheckRemark())) {
								log.info("认证返回1014：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());
								importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
								importUserService.updateById(importUser);
								noticeInfo.append("结算对象-" + importUser.getImportName() + "：正在认证中，请认证通过后再发起结算；");
								continue;
							}

							if ("1018".equals(employCheckResultItem.getCheckRemark())) {
								log.info("认证返回1018：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());
								importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
								importUserService.updateById(importUser);
								noticeInfo.append("结算对象-" + importUser.getImportName() + "：正在认证中，请认证通过后再发起结算；");
								continue;
							}
							if ("1019".equals(employCheckResultItem.getCheckRemark())) {
								log.info("认证返回1019：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());

								importUser.setCertStatus(DingEnum.CER_STATUS_1.getType());
								importUserService.updateById(importUser);
								noticeInfo.append("结算对象-" + importUser.getImportName() + "：认证状态已更新，请重新发起结算；");
								continue;
							}

							importUser.setCertStatus(DingEnum.CER_STATUS_2.getType());
							importUserService.updateById(importUser);
							noticeInfo.append("结算对象-" + importUser.getImportName() + "：认证失败，请核实身份信息；");
						}
					}
				} else {
					return R.failed("人力家接口调用异常");
				}
			}
		}

		noteService.saveOrUpdateBatch(notes);

		/**
		 * 更新结算结果
		 */

		SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(input.getId());
		WmScorePackage updateEntity = new WmScorePackage();
		updateEntity.setId(input.getId());
		updateEntity.setSettleStatus(output.toSettleStatus());
		wmScorePackageService.updateById(updateEntity);

		return R.ok("", noticeInfo.toString());
	}


	@Override
	public R settleReIssue(WmScorePackageSettleInput input) {

		WmScorePackageSettleNote note = noteService.getById(input.getId());

		WmScorePackage wmScorePackage = wmScorePackageService.getById(note.getPackageId());

		String settleNo = UUID.randomUUID().toString().replace("-", "");
		note.setSettleNo(settleNo);

		if (!DingEnum.NOTE_STATUS_FAIL.getType().equals(note.getSettleNoteStatus())) {
			return R.failed("状态异常，请刷新页面后再操作");
		}

		Integer currentUserId = SecurityUtils.getUser().getId();
		SysUser currentUser = sysUserMapper.selectById(currentUserId);
		SysDept sysDept = sysDeptService.getById(currentUser.getDeptId());
		if (StringUtils.isEmpty(sysDept.getAppId())) {
			return R.failed("机构appId未维护");
		}
		DingConfig config = new DingConfig();
		config.setAppId(sysDept.getAppId());
		config.setAppSecret(sysDept.getAppSecret());
		config.setQueryUrl(sysDept.getQueryUrl());

		SysUser sysUser = sysUserMapper.selectById(note.getUserId());

		/**
		 * 2.校验身份证信息
		 */
		if (StringUtils.isEmpty(sysUser.getIdCardNumber())) {
			log.debug("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录;");

			// 添加登录提醒  TODO 发送短信提醒
			redisTemplate.opsForValue().set(CacheConstants.USER_NOTICE_KEY + sysUser.getUserId(), "1", CacheConstants.NOTICE_TIME, TimeUnit.DAYS);

			return R.failed("任务包众包代表-" + sysUser.getRealname() + "：身份证号未补录");
		}

		if (DingEnum.CER_STATUS_1.getType().equals(sysUser.getRljCertStatus())) {
			//认证成功  发起结算
			String subjectName = sysDept.getSubjectName();

			List jsdList = new ArrayList();
			Map jsdMap = new HashMap();
			jsdMap.put("amount", note.getSettleAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
			jsdMap.put("mobile", sysUser.getPhone());
			jsdMap.put("idCard", sysUser.getIdCardNumber());
			jsdMap.put("name", sysUser.getRealname());
			jsdList.add(jsdMap);

			EmployPayResponse employPayResponse = dingService.pay(config, subjectName,
					note.getSettleNo(), wmScorePackage.getScorePackageName(),
					note.getInvoiceType(), jsdList);

			//提交结算接口失败
			if (!employPayResponse.isSuccess()) {
				log.info("结算对象-" + sysUser.getRealname() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());
				log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
				redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
				return R.failed("结算对象-" + sysUser.getRealname() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());

			} else {
				//结算提交成功数据
				List<EmployPayResultSuccessItem> successResult = employPayResponse.getData().getSuccessResult();
				if (CollectionUtils.isNotEmpty(successResult)) {

					note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());
					noteService.updateById(note);

					/**
					 * 更新结算结果
					 */
					SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(note.getPackageId());
					WmScorePackage updateEntity = new WmScorePackage();
					updateEntity.setId(note.getPackageId());
					updateEntity.setSettleStatus(output.toSettleStatus());

					wmScorePackageService.updateById(updateEntity);

					savePayoffFormNote(note);
					return R.ok();
				}

				//结算提交失败的数据
				List<EmployPayResultfailItem> failResult = employPayResponse.getData().getFailResult();
				if (CollectionUtils.isNotEmpty(failResult)) {
					log.info("认证状态异常，结算解锁settleNoteId：{}", input.getId());
					redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
					return R.failed("结算失败：" + failResult.get(0).getCheckRemark());
				}

				return R.failed("结算失败，接口调用异常");
			}

		} else if (DingEnum.CER_STATUS_3.getType().equals(sysUser.getRljCertStatus())) {
			//认证中
			return R.failed("结算对象-" + sysUser.getRealname() + "，结算失败:正在认证中");

		} else {
			List rzlist = new ArrayList();
			Map map = new HashMap();
			map.put("name", sysUser.getRealname());
			map.put("mobile", sysUser.getPhone());
			map.put("idCard", sysUser.getIdCardNumber());
			map.put("idType", "1");
			rzlist.add(map);
			EmployCheckResponse response = dingService.check(config, rzlist);
			if (!response.isSuccess()) {
				return R.failed("人力家接口调用失败" + response.getCode() + ":" + response.getMsg());
			}
			//接口请求成功，但是接口返回的状态还需区分checkStatus，1:验证通过，状态改成已提交，2:验证不通过，状态改成认证失败
			List<EmployCheckResultItem> freelancesResult = response.getData().getFreelancesResult();
			if (CollectionUtils.isNotEmpty(freelancesResult) && freelancesResult.size() == 1) {
				EmployCheckResultItem employCheckResultItem = freelancesResult.get(0);
				if (employCheckResultItem.getIdCard().equals(sysUser.getIdCardNumber())) {
					//验证通过
					if (employCheckResultItem.getCheckStatus() == 1) {
						log.info("认证提交成功：{},{}", sysUser.getRealname(), sysUser.getUsername());

						//更新用户的认证状态为认证中
						sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
						sysUserMapper.updateById(sysUser);
						return R.failed("结算失败，人员正在认证中");
					} else {
						//验证不通过
						if ("1014".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1014：{},{}", sysUser.getRealname(), sysUser.getUsername());

							sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
							sysUserMapper.updateById(sysUser);

							return R.failed("结算失败，人员正在认证中");
						}

						if ("1018".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1018：{},{}", sysUser.getRealname(), sysUser.getUsername());
							sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
							sysUserMapper.updateById(sysUser);

							return R.failed("结算失败，人员正在认证中");
						}
						if ("1019".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1019：{},{}", sysUser.getRealname(), sysUser.getUsername());
							sysUser.setRljCertStatus(DingEnum.CER_STATUS_1.getType());
							sysUserMapper.updateById(sysUser);

							return R.failed("结算失败，人员认证状态已更新，请重新发起结算");
						}

						log.info("结算对象-" + sysUser.getRealname() + "，结算失败：认证失败；");

						//更新用户的认证状态为认证失败
						sysUser.setRljCertStatus(DingEnum.CER_STATUS_2.getType());
						sysUserMapper.updateById(sysUser);

						//小程序认证失败提醒 TODO 发送短信
						redisTemplate.opsForValue().set(CacheConstants.USER_NOTICE_KEY + sysUser.getUserId(), "1", CacheConstants.NOTICE_TIME, TimeUnit.DAYS);

						return R.failed("结算失败，人员认证失败，请核实人员信息");
					}
				} else {
					return R.failed("人力家接口调用异常，人力家与本系统人员信息不一致");
				}

			}

			return R.failed("人力家接口调用异常");
		}

	}

	/**
	 * PackageType2 = 2 结算
	 *
	 * @param wmScorePackage
	 * @param note
	 * @return
	 */
	private R settleType2ReIssue(WmScorePackage wmScorePackage, WmScorePackageSettleNote note) {

		String settleNo = UUID.randomUUID().toString().replace("-", "");
		note.setSettleNo(settleNo);

		if (!DingEnum.NOTE_STATUS_FAIL.getType().equals(note.getSettleNoteStatus())) {
			return R.failed("状态异常，请刷新页面后再操作");
		}

		Integer currentUserId = SecurityUtils.getUser().getId();
		SysUser currentUser = sysUserMapper.selectById(currentUserId);
		SysDept sysDept = sysDeptService.getById(currentUser.getDeptId());
		if (StringUtils.isEmpty(sysDept.getAppId())) {
			return R.failed("机构appId未维护");
		}
		DingConfig config = new DingConfig();
		config.setAppId(sysDept.getAppId());
		config.setAppSecret(sysDept.getAppSecret());
		config.setQueryUrl(sysDept.getQueryUrl());

		WmImportUser importUser = importUserService.getById(note.getUserId());

		/**
		 * 2.校验身份证信息
		 */
		if (StringUtils.isEmpty(importUser.getImportIdCardNumber())) {
			log.debug("任务包众包代表-" + importUser.getImportName() + "：身份证号未补录;");
			return R.failed("任务包众包代表-" + importUser.getImportName() + "：身份证号未补录");
		}

		if (DingEnum.CER_STATUS_1.getType().equals(importUser.getCertStatus())) {
			//认证成功  发起结算
			String subjectName = sysDept.getSubjectName();

			List jsdList = new ArrayList();
			Map jsdMap = new HashMap();
			jsdMap.put("amount", note.getSettleAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
			jsdMap.put("mobile", importUser.getImportPhone());
			jsdMap.put("idCard", importUser.getImportIdCardNumber());
			jsdMap.put("name", importUser.getImportName());
			jsdList.add(jsdMap);

			EmployPayResponse employPayResponse = dingService.pay(config, subjectName,
					note.getSettleNo(), wmScorePackage.getScorePackageName(),
					note.getInvoiceType(), jsdList);

			//提交结算接口失败
			if (!employPayResponse.isSuccess()) {
				log.info("结算对象-" + importUser.getImportName() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());
				log.info("认证状态异常，结算解锁settleNoteId：{}", note.getId());
				redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
				return R.failed("结算对象-" + importUser.getImportName() + "：提交结算失败" + employPayResponse.getCode() + employPayResponse.getMsg());

			} else {
				//结算提交成功数据
				List<EmployPayResultSuccessItem> successResult = employPayResponse.getData().getSuccessResult();
				if (CollectionUtils.isNotEmpty(successResult)) {

					note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());
					noteService.updateById(note);

					/**
					 * 更新结算结果
					 */
					SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(note.getPackageId());
					WmScorePackage updateEntity = new WmScorePackage();
					updateEntity.setId(note.getPackageId());
					updateEntity.setSettleStatus(output.toSettleStatus());

					wmScorePackageService.updateById(updateEntity);

					savePayoffFormNote(note);
					return R.ok();
				}

				//结算提交失败的数据
				List<EmployPayResultfailItem> failResult = employPayResponse.getData().getFailResult();
				if (CollectionUtils.isNotEmpty(failResult)) {
					log.info("认证状态异常，结算解锁settleNoteId：{}", note.getId());
					redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());
					return R.failed("结算失败：" + failResult.get(0).getCheckRemark());
				}

				return R.failed("结算失败，接口调用异常");
			}

		} else if (DingEnum.CER_STATUS_3.getType().equals(importUser.getCertStatus())) {
			//认证中
			return R.failed("结算对象-" + importUser.getImportName() + "，结算失败:正在认证中");

		} else {
			List rzlist = new ArrayList();
			Map map = new HashMap();
			map.put("name", importUser.getImportName());
			map.put("mobile", importUser.getImportPhone());
			map.put("idCard", importUser.getImportIdCardNumber());
			map.put("idType", "1");
			rzlist.add(map);
			EmployCheckResponse response = dingService.check(config, rzlist);
			if (!response.isSuccess()) {
				return R.failed("人力家接口调用失败" + response.getCode() + ":" + response.getMsg());
			}
			//接口请求成功，但是接口返回的状态还需区分checkStatus，1:验证通过，状态改成已提交，2:验证不通过，状态改成认证失败
			List<EmployCheckResultItem> freelancesResult = response.getData().getFreelancesResult();
			if (CollectionUtils.isNotEmpty(freelancesResult) && freelancesResult.size() == 1) {
				EmployCheckResultItem employCheckResultItem = freelancesResult.get(0);
				if (employCheckResultItem.getIdCard().equals(importUser.getImportIdCardNumber())) {
					//验证通过
					if (employCheckResultItem.getCheckStatus() == 1) {
						log.info("认证提交成功：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());

						//更新用户的认证状态为认证中
						importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
						importUserService.updateById(importUser);
						return R.failed("结算失败，人员正在认证中");
					} else {
						//验证不通过
						if ("1014".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1014：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());

							importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
							importUserService.updateById(importUser);

							return R.failed("结算失败，人员正在认证中");
						}

						if ("1018".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1018：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());
							importUser.setCertStatus(DingEnum.CER_STATUS_3.getType());
							importUserService.updateById(importUser);

							return R.failed("结算失败，人员正在认证中");
						}
						if ("1019".equals(employCheckResultItem.getCheckRemark())) {
							log.info("认证返回1019：{},{}", importUser.getImportName(), importUser.getImportIdCardNumber());
							importUser.setCertStatus(DingEnum.CER_STATUS_1.getType());
							importUserService.updateById(importUser);

							return R.failed("结算失败，人员认证状态已更新，请重新发起结算");
						}

						log.info("结算对象-" + importUser.getImportName() + "，结算失败：认证失败；");

						//更新用户的认证状态为认证失败
						importUser.setCertStatus(DingEnum.CER_STATUS_2.getType());
						importUserService.updateById(importUser);

						return R.failed("结算失败，人员认证失败，请核实人员信息");
					}
				} else {
					return R.failed("人力家接口调用异常，人力家与本系统人员信息不一致");
				}

			}

			return R.failed("人力家接口调用异常");
		}
	}

	/**
	 * 提交成功的记录
	 *
	 * @param note
	 */
	private void savePayoffFormNote(WmScorePackageSettleNote note) {
		WmPayOff wmPayOff = new WmPayOff();
		wmPayOff.setScoreId(note.getPackageId());
		wmPayOff.setNoteId(note.getId() + "");
		wmPayOff.setStatementNo(note.getSettleNo());
		wmPayOff.setSettleAmount(note.getSettleAmount());
		wmPayOff.setSettlePeople(note.getUserId());

		wmPayOffMapper.insert(wmPayOff);
	}

}
