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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.api.entity.SysUserRole;
import com.qunzhixinxi.hnqz.admin.api.entity.UserAgreementSignatureRecord;
import com.qunzhixinxi.hnqz.admin.config.TaxNotifyConfig;
import com.qunzhixinxi.hnqz.admin.entity.MonitoringIndicator;
import com.qunzhixinxi.hnqz.admin.entity.SysCertResultRecord;
import com.qunzhixinxi.hnqz.admin.entity.SysDeptSub;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageSettleNote;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageStatus;
import com.qunzhixinxi.hnqz.admin.entity.WmScoreTaskType;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskContent;
import com.qunzhixinxi.hnqz.admin.entity.dto.CancellationScorePackageDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.ExecSettlementDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.PickUpScorePackageDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.ScorePackageDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.ScorePackageSettleNoteDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.SettlementDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.TaxHelperAckBindingCardDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.TaxHelperAddMemberDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.TaxHelperAgreementSignatureDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.TaxHelperBindingCardCodeDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.TaxHelperTokenDTO;
import com.qunzhixinxi.hnqz.admin.entity.input.Record;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleAmountMonitorInput;
import com.qunzhixinxi.hnqz.admin.entity.input.TaskSettleBatch;
import com.qunzhixinxi.hnqz.admin.entity.input.TaskSettleInfo;
import com.qunzhixinxi.hnqz.admin.entity.output.SettleAmountMonitorOutput;
import com.qunzhixinxi.hnqz.admin.enums.ChannelEnum;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.LockEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageFinishStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.ScorePackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysCertResultRecordMapper;
import com.qunzhixinxi.hnqz.admin.mapper.UserAgreementSignatureRecordMapper;
import com.qunzhixinxi.hnqz.admin.service.MonitoringIndicatorService;
import com.qunzhixinxi.hnqz.admin.service.PartyAService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptSubService;
import com.qunzhixinxi.hnqz.admin.service.SysUserRoleService;
import com.qunzhixinxi.hnqz.admin.service.SysUserService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageSettleNoteService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageStatusService;
import com.qunzhixinxi.hnqz.admin.service.WmScoreTaskTypeService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskContentService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskService;
import com.qunzhixinxi.hnqz.common.ding.config.DingConfig;
import com.qunzhixinxi.hnqz.common.ding.enums.DingEnum;
import com.qunzhixinxi.hnqz.common.taxhelper.common.CommonConstants;
import com.qunzhixinxi.hnqz.common.taxhelper.config.TaxHelperConfig;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperAddMemberModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperBindingCardConfirmModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperBindingCardVerificationModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperGetUserAgreementModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperH5BizTokenModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperSettlementModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperUserAgreementAuthorizationModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperAddMemberRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperBindingCardConfirmRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperBindingCardVerificationRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperGetUserAgreementRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperH5BizTokenRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperSettlementRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperUserAgreementAuthorizationRequest;
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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * {@code PartyAServiceImpl} 甲方服务实现
 *
 * @author Hengchen.Sun
 * @version 1.0.0
 * @date 2021-05-17
 * @since ver.1.0.0
 */
@Service
@AllArgsConstructor
@Slf4j
public class PartyAServiceImpl implements PartyAService {

	/**
	 * 用户服务
	 */
	private final SysUserService userService;

	/**
	 * 税邦云服务
	 */
	private final TaxHelperService taxHelperService;

	/**
	 * 部门服务
	 */
	private final SysDeptService deptService;

	/**
	 * 认证记录mapper
	 */
	private final SysCertResultRecordMapper sysCertResultRecordMapper;

	/**
	 * 回调配置
	 */
	private final TaxNotifyConfig taxNotifyConfig;

	/**
	 * 积分包服务
	 */
	private final WmScorePackageService wmScorePackageService;

	/**
	 * 积分任务服务
	 */
	private final WmScoreTaskTypeService wmScoreTaskTypeService;

	/**
	 * 积分包状态服务
	 */
	private final WmScorePackageStatusService wmScorePackageStatusService;

	/**
	 * 任务服务
	 */
	private final WmTaskService wmTaskService;

	/**
	 * 任务内容服务
	 */
	private final WmTaskContentService wmTaskContentService;

	/**
	 * 部门子表服务
	 */
	private final SysDeptSubService sysDeptSubService;

	/**
	 * 用户角色服务
	 */
	private final SysUserRoleService userRoleService;

	/**
	 * 积分包结算服务
	 */
	private final WmScorePackageSettleNoteService wmScorePackageSettleNoteService;

	private final MonitoringIndicatorService monitoringIndicatorService;

	private final RedisTemplate redisTemplate;

	private final UserAgreementSignatureRecordMapper userAgreementSignatureRecordMapper;

	/**
	 * 税邦云增员
	 *
	 * @param taxHelperAddMemberDTO 增员DTO
	 * @return 增员信息
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> taxHelperAddMember(TaxHelperAddMemberDTO taxHelperAddMemberDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", taxHelperAddMemberDTO.getUsername())
				.eq("dept_id", taxHelperAddMemberDTO.getDeptId()));
		String info = checkoutMemberInfo(member, CommonConstants.ADD_MEMBER_METHOD);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(taxHelperAddMemberDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验结算信息
		SysDeptSub query = new SysDeptSub();
		query.setDeptId(dept.getDeptId());
		query.setSubjectType(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.query(query));
		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, String.valueOf(taxHelperAddMemberDTO.getType()));
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 开始增员
		log.info("{}：税邦云增员开始, 身份证号：{}", taxHelperAddMemberDTO.getUsername(), taxHelperAddMemberDTO.getIdNumber());
		// 开始增员
		TaxHelperConfig config = new TaxHelperConfig();
		config.setAppId(deptSub.getAppId());
		config.setAppSecrete(deptSub.getAppSecret());
		config.setQueryUrl(deptSub.getQueryUrl());

		TaxHelperAddMemberModel model = new TaxHelperAddMemberModel(config);
		model.setIdCard(taxHelperAddMemberDTO.getIdNumber());
		model.setPhone(member.getUsername());
		model.setType(taxHelperAddMemberDTO.getType());
		model.setName(member.getRealname());
		model.setNotifyUrl("http://localhost:8808");
		model.setEnterpriseCode(dept.getTaxCode());
		TaxHelperAddMemberRequest request = new TaxHelperAddMemberRequest(model);
		TaxHelperResponse response = taxHelperService.addMembers(request);

		// 记录认证结果
		saveCertRecord(response, member, ChannelEnum.TAX_HELPER.val(), CommonConstants.ADD_MEMBER_METHOD);

		// 更新用户信息
		if (response.success()) {
			// 更新用户
			SysUser tmp = new SysUser();
			tmp.setUserId(member.getUserId());
			tmp.setCertStatus(TaxHelperCertStatus.ADD_MEMBER.getCode());
			tmp.setIdCardNumber(taxHelperAddMemberDTO.getIdNumber());
			tmp.setUpdateTime(LocalDateTime.now());
			userService.updateById(tmp);
			return getResultMap(CommonConstants.SUCCESS_CODE + "", response.getMessage());
		} else {
			log.info("税邦云增员失败：{},{}，原因是：{}", member.getRealname(), member.getUsername(), response.getMessage());
		}

		log.info("{}：税邦云增员结束, 身份证号：{}", taxHelperAddMemberDTO.getUsername(), taxHelperAddMemberDTO.getIdNumber());
		return getResultMap(CommonConstants.CLIENT_ERROR_CODE + "", response.getMessage());
	}

	/**
	 * 回传用户协议授权信息
	 *
	 * @return 回传结果
	 */
	public Map<String, String> userAgreementAuthorization(TaxHelperAgreementSignatureDTO taxHelperAgreementSignatureDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", taxHelperAgreementSignatureDTO.getUsername())
				.eq("dept_id", taxHelperAgreementSignatureDTO.getDeptId()));
		String info = checkoutMemberInfo(member, CommonConstants.USER_AGREEMENT_SIGNATURE_METHOD);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验用户是否已经签署了信息
		if (member.getTaxHelperAgreementSignature() == 1) {
			return getResultMap("2000", "协议已签署");
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(taxHelperAgreementSignatureDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验结算信息
		SysDeptSub query = new SysDeptSub();
		query.setDeptId(dept.getDeptId());
		query.setSubjectType(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.query(query));
		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 签约开始
		log.info("【{}({})】,获取签约信息", member.getRealname(), member.getUsername());
		TaxHelperConfig config = new TaxHelperConfig();
		config.setAppId(deptSub.getAppId());
		config.setAppSecrete(deptSub.getAppSecret());
		config.setQueryUrl(deptSub.getQueryUrl());

		// 获取
		TaxHelperGetUserAgreementModel getUserAgreementModel = new TaxHelperGetUserAgreementModel(config);
		getUserAgreementModel.setEnterpriseCode(dept.getTaxCode());
		TaxHelperGetUserAgreementRequest getUserAgreementRequest = new TaxHelperGetUserAgreementRequest(getUserAgreementModel);
		TaxHelperResponse userAgreement = taxHelperService.getUserAgreement(getUserAgreementRequest);

		// 记录认证结果
		SysCertResultRecord record = new SysCertResultRecord();
		record.setCode(userAgreement.getCode());
		record.setCreateTime(LocalDateTime.now());
		record.setDeptId(dept.getDeptId());
		record.setMessage(StringUtils.isNotEmpty(userAgreement.getMessage()) ? userAgreement.getMessage() : "无");
		record.setStatus(null);
		record.setSubjectType(1);
		record.setMethod("税邦云用户协议");
		record.setUserId(member.getUserId());
		sysCertResultRecordMapper.insert(record);


		if (!userAgreement.success()) {
			return getResultMap("4000", userAgreement.getMessage());
		}


		// 签约
		log.info("【{}({})】,签约开始", member.getRealname(), member.getUsername());
		TaxHelperUserAgreementAuthorizationModel model = new TaxHelperUserAgreementAuthorizationModel(config);
		model.setEnterpriseCode(dept.getTaxCode());
		LocalDateTime signTime = LocalDateTime.now();
		model.setAuthorizationTime(LocalDateTimeUtil.format(signTime, CommonConstants.DEFAULT_DATE_TIME_FORMAT_PATTERN));
		model.setIdCard(member.getIdCardNumber());

		TaxHelperUserAgreementAuthorizationRequest request = new TaxHelperUserAgreementAuthorizationRequest(model);
		TaxHelperResponse response = taxHelperService.userAgreementAuthorization(request);

		// 记录认证结果
		record.setCode(response.getCode());
		record.setCreateTime(LocalDateTime.now());
		record.setDeptId(dept.getDeptId());
		record.setMessage(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage() : "无");
		record.setStatus(null);
		record.setSubjectType(1);
		record.setMethod("税邦云回传用户协议授权信息");
		record.setUserId(member.getUserId());
		sysCertResultRecordMapper.insert(record);

		if (response.success()) {
			// 签署协议
			UserAgreementSignatureRecord uasr = new UserAgreementSignatureRecord();
			uasr.setAgreement(userAgreement.getData());
			uasr.setUserId(member.getUserId());
			uasr.setCreateTime(LocalDateTime.now());
			uasr.setTarget(1);
			uasr.setSignTime(signTime);
			userAgreementSignatureRecordMapper.insert(uasr);


			// 修改用户状态
			member.setUpdateTime(LocalDateTime.now());
			member.setTaxHelperAgreementSignature(1);
			userService.updateById(member);


			return getResultMap("2000", response.getMessage());
		}
		return getResultMap("4000", response.getMessage());
	}


	/**
	 * 获取税邦云H5 token
	 *
	 * @param taxHelperTokenDTO TOKEN DTO
	 * @return 获取结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> taxHelperH5Token(TaxHelperTokenDTO taxHelperTokenDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", taxHelperTokenDTO.getUsername())
				.eq("dept_id", taxHelperTokenDTO.getDeptId()));
		String info = checkoutMemberInfo(member, CommonConstants.H5_TOKEN_METHOD);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(taxHelperTokenDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验结算信息
		SysDeptSub query = new SysDeptSub();
		query.setDeptId(dept.getDeptId());
		query.setSubjectType(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.query(query));
		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		log.info("税邦云获取H5 TOKEN开始, 用户名：{}，\n回退地址：{}", taxHelperTokenDTO.getUsername(), taxHelperTokenDTO.getReturnUrl());

		// 开始获取token
		TaxHelperConfig config = new TaxHelperConfig();
		config.setAppId(deptSub.getAppId());
		config.setAppSecrete(deptSub.getAppSecret());
		config.setQueryUrl(deptSub.getQueryUrl());

		TaxHelperH5BizTokenModel model = new TaxHelperH5BizTokenModel(config);
		model.setIdCard(member.getIdCardNumber());
		model.setReturnUrl(taxHelperTokenDTO.getReturnUrl());
		model.setNotifyUrl(taxNotifyConfig.getNotifyUrl() + "/admin/taxhelper/" + member.getUserId() + "/v2/checkFaceNotify");

		TaxHelperH5BizTokenRequest request = new TaxHelperH5BizTokenRequest(model);
		TaxHelperResponse response = taxHelperService.getH5BizToken(request);

		// 记录认证结果
		saveCertRecord(response, member, ChannelEnum.TAX_HELPER.val(), CommonConstants.H5_TOKEN_METHOD);

		if (response.success()) {
			// 修改用户状态
			member.setUpdateTime(LocalDateTime.now());
			if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.ADD_MEMBER.getCode())) {
				member.setCertStatus(TaxHelperCertStatus.CHECKING_UNBIND.getCode());
			} else if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.UNCHECKED_BIND.getCode())) {
				member.setCertStatus(TaxHelperCertStatus.CHECKING_BIND.getCode());
			}
			userService.updateById(member);
			log.info("税邦云获取H5 TOKEN成功, 用户名：{}，\nTOKEN：{}", taxHelperTokenDTO.getUsername(), response.getMessage());
			return getResultMap("2000", response.getMessage());
		} else {
			// 处理税邦云认证成功，但回调认证结果为失败，再次请求显示成
			if (StringUtils.equals(CommonConstants.ALREADY_CERT_SUCCESSFUL, response.getMessage())) {
				// 修改用户状态
				member.setUpdateTime(LocalDateTime.now());
				if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.ADD_MEMBER.getCode())) {
					member.setCertStatus(TaxHelperCertStatus.CHECKED_UNBIND.getCode());
				} else if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.UNCHECKED_BIND.getCode())) {
					member.setCertStatus(TaxHelperCertStatus.CERT.getCode());
				}
				userService.updateById(member);
				log.info("{}：税邦云获取H5 TOKEN失败, 失败原因：{}，已更新成功状态", taxHelperTokenDTO.getUsername(), response.getMessage());
				return getResultMap("2000", response.getMessage());
			}
			log.info("税邦云获取H5 TOKEN失败, 用户名：{}，\n失败原因：{}", taxHelperTokenDTO.getUsername(), response.getMessage());
			return getResultMap("4000", response.getMessage());
		}
	}

	/**
	 * 获取税邦云绑卡验证码
	 *
	 * @param taxHelperBindingCardCodeDTO 绑卡验证码DTO
	 * @return 获取绑卡验证码
	 */
	@Override
	public Map<String, String> taxHelperBindingCardVerification(TaxHelperBindingCardCodeDTO taxHelperBindingCardCodeDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", taxHelperBindingCardCodeDTO.getUsername())
				.eq("dept_id", taxHelperBindingCardCodeDTO.getDeptId()));
		String info = checkoutMemberInfo(member, CommonConstants.BINDING_CARD_CODE_METHOD);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(taxHelperBindingCardCodeDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验结算信息
		SysDeptSub query = new SysDeptSub();
		query.setDeptId(dept.getDeptId());
		query.setSubjectType(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.query(query));
		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		log.info("税邦云获取绑卡验证码开始, 用户名：{}，\n绑卡手机号：{}，\n银行卡号：{}",
				taxHelperBindingCardCodeDTO.getUsername(), taxHelperBindingCardCodeDTO.getMobile(), taxHelperBindingCardCodeDTO
						.getPayAccount());

		// 开始获取验证码
		TaxHelperConfig config = new TaxHelperConfig();
		config.setAppId(deptSub.getAppId());
		config.setAppSecrete(deptSub.getAppSecret());
		config.setQueryUrl(deptSub.getQueryUrl());

		TaxHelperBindingCardVerificationModel model = new TaxHelperBindingCardVerificationModel(config);
		model.setPayAccountPhone(taxHelperBindingCardCodeDTO.getMobile());
		model.setPayAccount(taxHelperBindingCardCodeDTO.getPayAccount());
		model.setIdCard(member.getIdCardNumber());
		TaxHelperBindingCardVerificationRequest request = new TaxHelperBindingCardVerificationRequest(model);
		TaxHelperResponse response = taxHelperService.bindingCardVerification(request);

		// 记录认证结果
		saveCertRecord(response, member, ChannelEnum.TAX_HELPER.val(), CommonConstants.BINDING_CARD_CODE_METHOD);

		if (response.success()) {
			log.info("税邦云获取绑卡验证码成功, 用户名：{}，\n绑卡手机号：{}，\n银行卡号：{}",
					taxHelperBindingCardCodeDTO.getUsername(), taxHelperBindingCardCodeDTO.getMobile(), taxHelperBindingCardCodeDTO
							.getPayAccount());
			return getResultMap("2000", response.getMessage());
		} else {
			log.info("税邦云获取绑卡验证码失败, 用户名：{}，\n绑卡手机号：{}，\n银行卡号：{}，\n失败原因：{}",
					taxHelperBindingCardCodeDTO.getUsername(), taxHelperBindingCardCodeDTO.getMobile(),
					taxHelperBindingCardCodeDTO.getPayAccount(), response.getMessage());
			return getResultMap("4000", response.getMessage());
		}
	}

	/**
	 * 税邦云绑卡确认
	 *
	 * @param taxHelperAckBindingCardDTO 确认绑卡DTO
	 * @return 绑卡结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> taxHelperAckBindingCard(TaxHelperAckBindingCardDTO taxHelperAckBindingCardDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", taxHelperAckBindingCardDTO.getUsername())
				.eq("dept_id", taxHelperAckBindingCardDTO.getDeptId()));
		String info = checkoutMemberInfo(member, CommonConstants.ACK_BINDING_CARD_METHOD);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(taxHelperAckBindingCardDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验结算信息
		SysDeptSub query = new SysDeptSub();
		query.setDeptId(dept.getDeptId());
		query.setSubjectType(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode());
		query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.query(query));
		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		log.info("税邦云获取绑卡确认开始, 用户名：{}，\n验证码：{}，\n银行卡号：{}",
				taxHelperAckBindingCardDTO.getUsername(), taxHelperAckBindingCardDTO.getCaptcha(), taxHelperAckBindingCardDTO
						.getPayAccount());

		// 开始确认
		TaxHelperConfig config = new TaxHelperConfig();
		config.setAppId(deptSub.getAppId());
		config.setAppSecrete(deptSub.getAppSecret());
		config.setQueryUrl(deptSub.getQueryUrl());

		TaxHelperBindingCardConfirmModel model = new TaxHelperBindingCardConfirmModel(config);
		model.setVerificationCode(taxHelperAckBindingCardDTO.getCaptcha());
		model.setPayAccount(taxHelperAckBindingCardDTO.getPayAccount());
		model.setIdCard(member.getIdCardNumber());
		model.setNotifyUrl(taxNotifyConfig.getNotifyUrl());
		TaxHelperBindingCardConfirmRequest request = new TaxHelperBindingCardConfirmRequest(model);
		TaxHelperResponse response = taxHelperService.bindingCardConfirm(request);

		// 记录认证结果
		saveCertRecord(response, member, ChannelEnum.TAX_HELPER.val(), CommonConstants.ACK_BINDING_CARD_METHOD);

		if (response.success()) {
			SysUser sysUser = new SysUser();
			sysUser.setBankCardNumber(taxHelperAckBindingCardDTO.getPayAccount());
			sysUser.setUserId(member.getUserId());

			if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.ADD_MEMBER.getCode())) {
				sysUser.setCertStatus(TaxHelperCertStatus.UNCHECKED_BIND.getCode());
			} else if (Objects.equals(member.getCertStatus(), TaxHelperCertStatus.CHECKED_UNBIND.getCode())) {
				sysUser.setCertStatus(TaxHelperCertStatus.CERT.getCode());
			} else {
				sysUser.setCertStatus(TaxHelperCertStatus.CHECKING_BIND.getCode());
			}

			sysUser.setUpdateTime(LocalDateTime.now());
			userService.updateById(sysUser);
			log.info("税邦云获取绑卡确认成功, 用户名：{}，\n验证码：{}，\n银行卡号：{}",
					taxHelperAckBindingCardDTO.getUsername(), taxHelperAckBindingCardDTO.getCaptcha(), taxHelperAckBindingCardDTO
							.getPayAccount());
			return getResultMap("2000", response.getMessage());
		} else {
			log.info("税邦云获取绑卡确认失败, 用户名：{}，\n验证码：{}，\n银行卡号：{}，\n原因是：{}",
					taxHelperAckBindingCardDTO.getUsername(), taxHelperAckBindingCardDTO.getCaptcha(), taxHelperAckBindingCardDTO
							.getPayAccount(), response
							.getMessage());
			return getResultMap("4000", response.getMessage());
		}
	}

	/**
	 * 创建积分包
	 *
	 * @param scorePackageDTO 积分包DTO
	 * @return 创建结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> createScorePackage(ScorePackageDTO scorePackageDTO) {

		// 获取部门并校验
		SysDept dept = deptService.getById(scorePackageDTO.getDeptId());
		String info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		//判断名字不能重复
		if (StringUtils.isNotEmpty(scorePackageDTO.getName())) {
			WmScorePackage sp = wmScorePackageService.getBaseMapper().selectOne(Wrappers.<WmScorePackage>query()
					.eq("score_package_name", scorePackageDTO.getName())
					.eq("dept_id", scorePackageDTO.getDeptId()));
			if (sp != null) {
				// return getResultMap("4000", "积分包名称重复");
				return getResultMap("2000", sp.getId());
			}
		} else {
			return getResultMap("4000", "积分包名称为空");
		}

		// 封装积分包
		WmScorePackage scorePackage = new WmScorePackage();
		scorePackage.setScorePackageName(scorePackageDTO.getName());
		scorePackage.setPackageType1(String.valueOf(scorePackageDTO.getPackageType()));
		scorePackage.setPackageType2(String.valueOf(scorePackageDTO.getPackageCategory()));
		scorePackage.setTypeid(String.valueOf(scorePackageDTO.getToType()));
		scorePackage.setTaskTypeId(String.valueOf(scorePackageDTO.getTaskType()));
		scorePackage.setUserScore(null);
		scorePackage.setTaskNum(null);
		scorePackage.setUserNum(scorePackageDTO.getMemberAmount());
		scorePackage.setRelationScoreId(null);
		scorePackage.setSendPackageDeptId(String.valueOf(scorePackageDTO.getDeptId()));
		scorePackage.setDeptId(String.valueOf(scorePackageDTO.getDeptId()));
		scorePackage.setBelongDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
		scorePackage.setDelFlag(DelEnum.NOT_DEL.val());
		scorePackage.setEnableFlag(LockEnum.UN_LOCK.val());
		scorePackage.setPackageFinishStatus(PackageFinishStatusEnum.NOT_COMPLETE.val());
		scorePackage.setPackageUserScope(String.valueOf(scorePackageDTO.getPickUpScope()));
		scorePackage.setIsReceive("0");
		scorePackage.setSourceType("1");
		//已分派待申领
		scorePackage.setScorePackageStatus(ScorePackageStatusEnum.UNCLAIMED.val());
		scorePackage.setDescription(scorePackageDTO.getDescription());
		scorePackage.setSubType(scorePackageDTO.getChannel().val());

		// 获取企业发包人
		List<SysUser> userList = userService.list(Wrappers.<SysUser>query().eq("dept_id", scorePackageDTO.getDeptId()));
		SysUser sender = null;
		out:
		for (SysUser sysUser : userList) {
			List<SysUserRole> userRoleList = userRoleService.list(Wrappers.<SysUserRole>query()
					.eq("user_id", sysUser.getUserId()));
			for (SysUserRole userRole : userRoleList) {
				if (userRole.getRoleId() == 9 || userRole.getRoleId() == 11) {
					sender = sysUser;
					break out;
				}
			}
		}

		if (sender == null) {
			return getResultMap("4000", "没有发包管理员，请联系要易平台");
		}

		scorePackage.setCreateUser(sender.getUserId());
		scorePackage.setCreateTime(LocalDateTime.now());
		wmScorePackageService.save(scorePackage);

		if (scorePackage.getPackageType1().equals("5") || scorePackage.getPackageType1().equals("4")
				|| scorePackage.getPackageType2().equals("2")) {
			//结算包
			WmScoreTaskType wmScoreTaskType = new WmScoreTaskType();
			wmScoreTaskType.setScoreId(scorePackage.getId());
			wmScoreTaskType.setTaskTypeId(scorePackage.getTaskTypeId());
			wmScoreTaskType.setType("2");
			wmScoreTaskTypeService.save(wmScoreTaskType);
		}

		return getResultMap("2000", scorePackage.getId());
	}

	/**
	 * 领取积分包
	 *
	 * @param pickUpScorePackageDTO 领取积分包DTO
	 * @return 领取结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> pickUpScorePackage(PickUpScorePackageDTO pickUpScorePackageDTO) {

		String info = null;
		// 获取积分包
		WmScorePackage scorePackage = wmScorePackageService.getBaseMapper().selectOne(
				Wrappers.<WmScorePackage>query().eq("id", pickUpScorePackageDTO.getPackageId())
						.eq("dept_id", pickUpScorePackageDTO.getDeptId())
		);

		// 校验积分包
		info = checkoutScorePackageInfo(scorePackage, true);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", pickUpScorePackageDTO.getUsername())
				.eq("dept_id", pickUpScorePackageDTO.getDeptId()));
		info = checkoutMemberInfo(member, "pickUpScorePackage");
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验医生
		if (!pickUpScorePackageDTO.getUsername().equals(scorePackage.getDescription())) {
			return getResultMap("4000", "接单医生和挂号目标医生不一致");
		}

		WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
		wmScorePackageStatus.setPackageId(pickUpScorePackageDTO.getPackageId().toString());
		wmScorePackageStatus.setUserId(member.getUserId().toString());
		wmScorePackageStatus.setDelFlag(DelEnum.NOT_DEL.val());
		wmScorePackageStatus.setEnableFlag(LockEnum.UN_LOCK.val());

		// 校验积分包是否已经被领取
		List<WmScorePackageStatus> wmScorePackageStatusList = wmScorePackageStatusService.
				list(Wrappers.query(wmScorePackageStatus).lambda().ne(WmScorePackageStatus::getStatus, 3));
		if (CollectionUtils.isNotEmpty(wmScorePackageStatusList)) {
			return getResultMap("4000", "积分包已领取");
		}

		wmScorePackageStatus.setStatus("1");
		wmScorePackageStatus.setTaskAddFlag("1");
		wmScorePackageStatus.setUserScore(null);
		wmScorePackageStatus.setTaskNum(null);
		wmScorePackageStatus.setDeptId(pickUpScorePackageDTO.getDeptId().toString());
		LocalDateTime localDateTime = LocalDateTime.now();
		wmScorePackageStatus.setCreateTime(localDateTime);
		wmScorePackageStatus.setUpdateTime(localDateTime);
		wmScorePackageStatusService.save(wmScorePackageStatus);

		// 更新积分包状态
		scorePackage.setScorePackageStatus("2");
		scorePackage.setUpdateTime(LocalDateTime.now());
		scorePackage.setIsReceive("1");
		wmScorePackageService.updateById(scorePackage);

		return getResultMap("2000", String.valueOf(wmScorePackageStatus.getId()));
	}


	/**
	 * 关闭积分包
	 *
	 * @param cancellationScorePackageDTO 关闭积分包
	 * @return 关闭结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> cancelScorePackage(CancellationScorePackageDTO cancellationScorePackageDTO) {

		// 获取积分包
		WmScorePackage scorePackage = wmScorePackageService.getBaseMapper().selectOne(
				Wrappers.<WmScorePackage>query().eq("id", cancellationScorePackageDTO.getPackageId())
						.eq("dept_id", cancellationScorePackageDTO.getDeptId())
		);

		// 校验积分包
		String info = checkoutScorePackageInfo(scorePackage, false);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		WmTask wmTask = new WmTask();
		wmTask.setScorePackageId(scorePackage.getId());
		List<WmTask> taskList = wmTaskService.getBaseMapper().selectList(Wrappers.query(wmTask));
		//将所有未接单审核的，改成审核不通过
		wmScorePackageStatusService.update(new WmScorePackageStatus(),
				Wrappers.<WmScorePackageStatus>lambdaUpdate()
						.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
						.eq(WmScorePackageStatus::getStatus, "1")
						.set(WmScorePackageStatus::getStatus, "3")
						.set(WmScorePackageStatus::getTaskAddFlag, "0")
		);
		//查询所有接单审核通过的
		LambdaQueryWrapper<WmScorePackageStatus> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(WmScorePackageStatus::getPackageId, scorePackage.getId());
		queryWrapper.eq(WmScorePackageStatus::getDelFlag, "0");
		queryWrapper.in(WmScorePackageStatus::getStatus, "2");
		List<WmScorePackageStatus> scorestatusList = wmScorePackageStatusService.list(queryWrapper);
		//全部终止，终止任务和积分包
		if ("0".equals(scorePackage.getEnableType())) {
			scorePackage.setScorePackageStatus("6");//已终止
			//更新结单
			if (null != scorestatusList && scorestatusList.size() > 0) {
				wmScorePackageStatusService.update(new WmScorePackageStatus(),
						Wrappers.<WmScorePackageStatus>lambdaUpdate()
								.eq(WmScorePackageStatus::getPackageId, scorePackage.getId())
								.set(WmScorePackageStatus::getTaskAddFlag, "0")
								.set(WmScorePackageStatus::getEnableFlag, "1")
								.set(WmScorePackageStatus::getEnableType, "1")
				);
			}
			scorePackage.setEnableFlag("1");
			wmScorePackageService.updateById(scorePackage);
			if (CollectionUtils.isNotEmpty(taskList)) {
				wmTaskService.update(
						wmTask, Wrappers.<WmTask>lambdaUpdate()
								.eq(WmTask::getScorePackageId, scorePackage.getId())
								.set(WmTask::getEnableFlag, "1"));
			}
		}
		return getResultMap("2000", "终止成功");
	}

	/**
	 * 批量上传证据链
	 * 上传证据链，需要对积分包进行审核，
	 * 并且根据实际上传的任务数，和积分值
	 * 对积分包的情况进行更新
	 *
	 * @param taskSettleBatch 证据链批量
	 * @return 上传结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> submitEvidence(TaskSettleBatch taskSettleBatch) {

		// 判断积分包状态
		QueryWrapper<WmScorePackage> queryWrapper = Wrappers.<WmScorePackage>query()
				.eq("id", taskSettleBatch.getPackageId())
				.eq("dept_id", taskSettleBatch.getDeptId());
		WmScorePackage scorePackage = wmScorePackageService.getOne(queryWrapper);

		// 校验积分包
		String info = checkoutScorePackageInfo(scorePackage, false);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验积分包领取记录
		WmScorePackageStatus scorePackageStatus = wmScorePackageStatusService.getById(taskSettleBatch.getScorePackageStatusId());
		scorePackageStatus.setStatus("1");
		info = checkoutScorePackageStatusInfo(scorePackageStatus);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 封装任务
		List<TaskSettleInfo> taskSettleInfoList = taskSettleBatch.getTaskSettleInfoList();
		if (CollectionUtils.isEmpty(taskSettleInfoList)) {
			return getResultMap("4000", "证据链任务数为0, 批量上传证据链失败");
		}

		List<TaskSettleInfo> errorList = new ArrayList<>();
		List<Map<String, Object>> correctList = new ArrayList<>();
		LocalDateTime now = LocalDateTime.now();

		// 校验证据链列表信息，并记录正确信息
		out:
		for (TaskSettleInfo taskSettleInfo : taskSettleInfoList) {
			List<Record> recordList = taskSettleInfo.getRecordList();
			if (CollectionUtils.isEmpty(recordList)) {
				errorList.add(taskSettleInfo);
				continue;
			} else {
				SysUser user = userService.getOne(Wrappers.<SysUser>query()
						.eq("username", taskSettleInfo.getMobile())
						.eq("dept_id", taskSettleBatch.getDeptId())
						.eq("realname", taskSettleInfo.getMemberName()));
				if (user == null) {
					log.error("用户不存在");
					errorList.add(taskSettleInfo);
					continue;
				}

				// 校验校验金额是否一致
				for (Record record : recordList) {

					// 校验处方单号唯一
					boolean absent = redisTemplate.opsForValue()
							.setIfAbsent(record.getTemp3().trim(), record.getTemp3());

					if (!absent) {
						log.error("证据链不能重复上传:{}", record.getTemp3());
						errorList.add(taskSettleInfo);
						continue out;
					}

					Record.RecordExt recordExt = record.getRecordExt();
					if (recordExt == null) {
						log.error("证据链详细信息为空");
						errorList.add(taskSettleInfo);
						continue out;
					}
					// 判断结算结算金额和证据链金额是否相同
					if (!recordExt.getAmount().equals(record.getTemp5())) {
						log.error("证据链金额和实际金额不同:{},{}", recordExt.getAmount(), record.getTemp5());
						errorList.add(taskSettleInfo);
						continue out;
					}

					// 封装合法证据链
					WmTask task = new WmTask();
					task.setTaskTypeId("32");
					task.setTaskUsername(taskSettleInfo.getMobile());
					task.setScorePackageId(scorePackage.getId());
					task.setTaskUserId(String.valueOf(user.getUserId()));
					task.setDeptId(String.valueOf(scorePackage.getDeptId()));
					task.setDrugEntId(String.valueOf(scorePackage.getDrugEntId()));
					task.setLookintoDate(now);
					task.setCreateTime(now);
					task.setTaskStatus("3");
					task.setDelFlag("0");
					task.setEnableFlag("0");
					task.setTaskFrom("2");
					task.setScore(new BigDecimal(recordExt.getAmount()).multiply(BigDecimal.valueOf(100)).intValue());
					// task.setReportDrugApprovalStatus("0");
					// task.setReportOneApprovalStatus("0");
					// task.setReportSecondApprovalStatus("0");

					WmTaskContent taskContent = new WmTaskContent();
					BeanUtil.copyProperties(record, taskContent);
					taskContent.setTemp32(scorePackage.getId());

					WmScorePackageSettleNote note = new WmScorePackageSettleNote();
					note.setInvoiceType(recordExt.getInvoiceType());
					note.setCategoryName(recordExt.getInvoiceCategory());
					note.setPackageId(scorePackage.getId());
					note.setCreateTime(now);
					note.setIdCardNumber(user.getIdCardNumber());
					// note.setSettleNoteStatus(4);
					note.setSettleAmount(new BigDecimal(recordExt.getAmount()));

					note.setUserId(String.valueOf(user.getUserId()));
					note.setSubType("1");

					Map<String, Object> saveMap = new HashMap<>(3);
					saveMap.put("task", task);
					saveMap.put("taskContent", taskContent);
					saveMap.put("scorePackageSettleNote", note);
					correctList.add(saveMap);
				}
			}
		}

		// 如果错误list为空，这表示证据链正确，执行更新积分包和审核操作
		if (CollectionUtils.isNotEmpty(errorList)) {
			log.error("错误的证据链:{}", JSONUtil.toJsonStr(errorList));
			return getResultMap("4000", JSONUtil.toJsonStr(errorList));
		}

		// 校验正确的容量
		if (CollectionUtils.isEmpty(correctList)) {
			log.error("上传的正确证据链为数量为0");
			return getResultMap("4000", "上传的正确证据链为数量为0");
		} else {
			AtomicInteger total = new AtomicInteger();
			List<Map<String, Object>> result = new ArrayList<>();
			Map<String, List<Map<String, Object>>> userToResultMap = new HashMap<>(taskSettleInfoList.size());
			correctList.forEach(map -> {
				WmTask t = (WmTask) map.get("task");
				total.addAndGet(t.getScore());
				WmTaskContent taskContent = (WmTaskContent) map.get("taskContent");
				wmTaskContentService.save(taskContent);
				t.setWmTaskContent(taskContent);
				t.setTaskContentId(String.valueOf(taskContent.getId()));
				wmTaskService.save(t);
				WmScorePackageSettleNote scorePackageSettleNote = (WmScorePackageSettleNote) map.get("scorePackageSettleNote");
				scorePackageSettleNote.setTaskId(t.getId());
				String settleNo = UUID.randomUUID().toString().replace("-", "");
				scorePackageSettleNote.setSettleNo(settleNo);
				wmScorePackageSettleNoteService.save(scorePackageSettleNote);
				Map<String, Object> recordMap = new HashMap<>(3);
				recordMap.put("taskId", Integer.parseInt(t.getId()));
				recordMap.put("prescriptionNo", taskContent.getTemp3());
				recordMap.put("settleNoteId", scorePackageSettleNote.getId());
				result.add(recordMap);
				userToResultMap.put(t.getTaskUsername(), result);
			});
			// 审核领包记录记录
			scorePackageStatus.setTaskNum(correctList.size());
			scorePackageStatus.setUserScore(String.valueOf(total.get()));
			approvalScorePackageStatus(scorePackageStatus);
			// 更新积分包
			// 已提交结算申请
			scorePackage.setScorePackageStatus("4");
			scorePackage.setPackageFinishStatus("1");
			scorePackage.setUserScore(String.valueOf(total.get()));
			scorePackage.setTaskNum(correctList.size());
			scorePackage.setUpdateTime(now);
			scorePackage.setReceiveDate(now);
			wmScorePackageService.updateById(scorePackage);
			return getResultMap("2000", JSONUtil.toJsonStr(userToResultMap));
		}

	}

	/**
	 * 提交结算
	 *
	 * @param scorePackageSettleNoteDTO 结算记录DTO
	 * @return 提交结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> submitSettlement(ScorePackageSettleNoteDTO scorePackageSettleNoteDTO) {

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", scorePackageSettleNoteDTO.getMobile())
				.eq("dept_id", scorePackageSettleNoteDTO.getDeptId()));
		String info = checkoutMemberInfo(member, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取部门并校验
		SysDept dept = deptService.getById(scorePackageSettleNoteDTO.getDeptId());
		info = checkoutDeptInfo(dept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		List<String> idCard = new ArrayList<>();
		List<String> userIds = new ArrayList<>();
		List<Integer> ids = new ArrayList<>();
		idCard.add(member.getIdCardNumber());
		userIds.add(member.getUserId().toString());
		if (null != scorePackageSettleNoteDTO.getSettleNoteId()) {
			ids.add(scorePackageSettleNoteDTO.getSettleNoteId());
		}

		WmScorePackageSettleNote note = wmScorePackageSettleNoteService.getById(scorePackageSettleNoteDTO.getSettleNoteId());

		// 校验金额
		if (!new BigDecimal(scorePackageSettleNoteDTO.getAmount()).equals(note.getSettleAmount())) {
			log.error("结算金额不正确，实际金额：{},传入金额：{}", note.getSettleAmount(), scorePackageSettleNoteDTO.getAmount());
			return getResultMap("4000", "结算金额不正确");
		}

		SettleAmountMonitorInput monitorInput = SettleAmountMonitorInput.fromIdCard(idCard, ids, scorePackageSettleNoteDTO
				.getChannel()
				.val());
		List<SettleAmountMonitorOutput> monitorOutputList = sysDeptSubService.getSettleAmountMonitor(monitorInput);

		SettleAmountMonitorInput deptMonitorInput = SettleAmountMonitorInput.fromUserId(userIds, ids, scorePackageSettleNoteDTO
				.getChannel()
				.val());
		List<SettleAmountMonitorOutput> deptAmountMonitor = sysDeptSubService.getDeptAmountMonitor(deptMonitorInput);


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

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

		MonitoringIndicator monitoringIndicator = monitoringIndicatorService.getBySubType(note.getSubType());
		SysDeptSub sysDeptSub = sysDeptSubService.getOne(Wrappers.<SysDeptSub>lambdaQuery()
				.eq(SysDeptSub::getDeptId, dept.getDeptId())
				.eq(SysDeptSub::getSubjectType, note.getSubType())
		);
		BigDecimal deptLimit = sysDeptSub.getLimitAmount();
		BigDecimal monitoringLimit = monitoringIndicator.getLimitAmount();
		BigDecimal monitorAmount = note.getSettleAmount();
		BigDecimal deptMonitorAmount = note.getSettleAmount();
		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 getResultMap("4000", note.getRealName() + "：超过当月限额");
			}
		}
		if (null != monitoringLimit) {
			if (monitorAmount.compareTo(monitoringLimit) > 0) {
				return getResultMap("4000", note.getRealName() + "：超过结算渠道限额");
			}
		}

		WmScorePackageSettleNote updateEntity;
		LocalDateTime localDateTime = LocalDateTime.now();
		if (null != note.getId()) {
			WmScorePackageSettleNote oldData = wmScorePackageSettleNoteService.getById(note.getId());
			if (0 != oldData.getSettleNoteStatus()) {
				return getResultMap("4000", "状态异常，不能提交");
			}
			updateEntity = new WmScorePackageSettleNote();
			updateEntity.setId(note.getId());
			updateEntity.setSubType(note.getSubType());
			updateEntity.setInvoiceType(note.getInvoiceType());
			updateEntity.setCategoryName(scorePackageSettleNoteDTO.getInvoiceCategory());
			updateEntity.setSettleAmount(note.getSettleAmount());
			updateEntity.setSettleNoteStatus(9);
			updateEntity.setSubTime(localDateTime);
			updateEntity.setUpdateTime(localDateTime);
			updateEntity.setIdCardNumber(member.getIdCardNumber());
			wmScorePackageSettleNoteService.updateById(updateEntity);
			WmScorePackageSettleNote settleNote = wmScorePackageSettleNoteService.getById(note.getId());

			// 如果是最后的结算，则更新积分包状态
			List<WmScorePackageSettleNote> one = wmScorePackageSettleNoteService.list(Wrappers.<WmScorePackageSettleNote>lambdaQuery()
					.ne(WmScorePackageSettleNote::getId, updateEntity.getId())
					.eq(WmScorePackageSettleNote::getPackageId, settleNote.getPackageId())
					.eq(WmScorePackageSettleNote::getSettleNoteStatus, 0)
			);

			if (CollectionUtils.isEmpty(one)) {
				WmScorePackage wmScorePackage = wmScorePackageService.getById(settleNote.getPackageId());
				wmScorePackage.setSettlementDate(LocalDateTime.now());
				wmScorePackage.setScorePackageStatus("5");
				wmScorePackage.setSettleFlag("1");
				wmScorePackageService.updateById(wmScorePackage);
			}
		} else {
			WmScorePackageSettleNote entity = new WmScorePackageSettleNote();
			entity.setSubType(note.getSubType());
			entity.setInvoiceType(note.getInvoiceType());
			entity.setCategoryName(note.toCategoryName());
			entity.setSettleAmount(note.getSettleAmount());
			entity.setDiscount(new BigDecimal(1));
			entity.setPackageId(note.getPackageId());
			entity.setTaskId(note.getTaskId());
			entity.setUserId(note.getUserId());
			String settleNo = UUID.randomUUID().toString().replace("-", "");
			entity.setSettleNo(settleNo);
			entity.setSettleNoteStatus(9);

			entity.setCreateTime(localDateTime);
			entity.setSubTime(localDateTime);
			entity.setUpdateTime(localDateTime);
			entity.setIdCardNumber(member.getIdCardNumber());

			wmScorePackageSettleNoteService.save(entity);
		}

		return getResultMap("2000", "");
	}

	/**
	 * 结算
	 *
	 * @param execSettlementDTOList 结算DTO列表
	 * @return 提交结算结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> doSettlement(List<ExecSettlementDTO> execSettlementDTOList) {

		Assert.notEmpty(execSettlementDTOList);

		ExecSettlementDTO execSettlementDTO = execSettlementDTOList.get(0);

		// 获取用户并校验
		SysUser member = userService.getOne(Wrappers.<SysUser>query()
				.eq("username", execSettlementDTO.getMobile())
				.eq("dept_id", execSettlementDTO.getDeptId()));
		String info = checkoutMemberInfo(member, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 校验部门
		SysDept sysDept = deptService.getById(execSettlementDTO.getDeptId());
		info = checkoutDeptInfo(sysDept);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		// 获取并校验结算信息
		SysDeptSub deptSub = sysDeptSubService.getOne(Wrappers.<SysDeptSub>lambdaQuery()
				.eq(SysDeptSub::getDeptId, execSettlementDTO.getDeptId())
				.eq(SysDeptSub::getEnableFlag, SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode())
				.eq(SysDeptSub::getSubjectType, execSettlementDTO.getSubjectType())
		);

		info = checkoutDeptSubInfo(deptSub, ChannelEnum.TAX_HELPER, null);
		if (StringUtils.isNotEmpty(info)) {
			return getResultMap("4000", info);
		}

		List<SettlementDTO> settlementDTOList = new ArrayList<>();
		for (ExecSettlementDTO settlementDTO : execSettlementDTOList) {
			List<SettlementDTO> tempList = settlementDTO.getSettlementDTOList();
			if (CollectionUtils.isEmpty(tempList)) {
				return getResultMap("4000", "结算内容为空");
			}
			settlementDTOList.addAll(tempList);
		}

		List<WmScorePackageSettleNote> noteList = settlementDTOList.stream().map(settlementDTO -> {
			WmScorePackageSettleNote note = wmScorePackageSettleNoteService.getOne(
					Wrappers.<WmScorePackageSettleNote>lambdaQuery()
							.eq(WmScorePackageSettleNote::getId, settlementDTO.getSettleNoteId())
							.and(i -> i.eq(WmScorePackageSettleNote::getSettleNoteStatus, 9)
									.or()
									.eq(WmScorePackageSettleNote::getSettleNoteStatus, 2))
							.isNotNull(WmScorePackageSettleNote::getUserId)
			);
			WmScorePackage wmScorePackage = wmScorePackageService.getById(execSettlementDTO.getPackageId());
			note.setPackageName(wmScorePackage.getScorePackageName());
			return note;
		}).collect(Collectors.toList());

		// 校验限额
		BigDecimal tmp = new BigDecimal("0.0");
		for (WmScorePackageSettleNote note : noteList) {
			tmp = tmp.add(note.getSettleAmount());
		}
		String errInfo = checkoutSettleLimit(member, noteList.stream().mapToInt(WmScorePackageSettleNote::getId).boxed()
				.collect(Collectors.toList()), deptSub.getLimitAmount(), tmp);
		if (StringUtils.isNotEmpty(errInfo)) {
			log.error(errInfo);
			return getResultMap("4000", errInfo);
		}

		log.info("结算渠道： {} ", execSettlementDTO.getSubjectType());
		Map<String, String> result = null;
		if (SubjectTypeEnum.TYPE_RENLIJIA.getCode().equals(execSettlementDTO.getSubjectType())) {
			DingConfig config = new DingConfig();
			config.setAppId(deptSub.getAppId());
			config.setAppSecret(deptSub.getAppSecret());
			config.setQueryUrl(deptSub.getQueryUrl());
			String subjectName = deptSub.getSubjectName();
			// settleByRenLiJia(note, config, wmScorePackage, subjectName);

		} else {
			String taxCode = sysDept.getTaxCode();
			TaxHelperConfig config = new TaxHelperConfig();
			config.setAppId(deptSub.getAppId());
			config.setAppSecrete(deptSub.getAppSecret());
			config.setQueryUrl(deptSub.getQueryUrl());
			result = settleByTaxHelper(noteList, config, member, taxCode);
		}

		return result;
	}

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

		String info = null;

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

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

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

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

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

	/**
	 * 税帮云结算
	 *
	 * @param noteList 结算记录
	 * @param config   税帮云config
	 * @param sysUser  用户
	 * @param taxCode  企业三合一码
	 * @return 结果
	 */
	private Map<String, String> settleByTaxHelper(List<WmScorePackageSettleNote> noteList,
												  TaxHelperConfig config,
												  SysUser sysUser,
												  String taxCode) {

		// 加锁
		boolean absent = redisTemplate.opsForValue().setIfAbsent(
				CacheConstants.SETTLE_PACKAGE_KEY + ":" + sysUser.getUsername() + ":" + taxCode + ":"
						+ new HashSet(noteList).hashCode(), noteList, CacheConstants.SETTLE_TIME, TimeUnit.DAYS);

		if (!absent) {
			log.error("当前用户存在其他结算请求");
			return getResultMap("4000", "当前用户存在其他结算请求");
		}

		// 开始结算
		TaxHelperSettlementModel taxHelperSettlementModel = new TaxHelperSettlementModel(config);
		taxHelperSettlementModel.setEnterpriseCode(taxCode);
		taxHelperSettlementModel.setExtendFieldNames(Arrays.asList("报告下载地址"));
		taxHelperSettlementModel.setNotifyUrl(taxNotifyConfig.getNotifyUrl() + "/admin/taxhelper/" + sysUser.getUserId() + "/v2/settlementNotify");

		List<TaxHelperSettlementModel.AbstractArr> abstractArrList = new ArrayList<>();
		Map<String, TaxHelperSettlementModel.DetailedArr> detailArrMap = new HashMap<>();
		noteList.forEach(note -> {
			TaxHelperSettlementModel.DetailedArr detailedArr;
			if (detailArrMap.containsKey(sysUser.getIdCardNumber())) {
				detailedArr = detailArrMap.get(sysUser.getIdCardNumber());
				detailedArr.setInputAmount((BigDecimal.valueOf(detailedArr.getInputAmount())
						.add(note.getSettleAmount())
						.doubleValue()));
			} else {
				detailedArr = new TaxHelperSettlementModel.DetailedArr();
				detailedArr.setIdCard(sysUser.getIdCardNumber());
				detailedArr.setInputAmount(note.getSettleAmount().doubleValue());
				// detailedArr.setCategoryName("专业技术服务");
				detailedArr.setCategoryName(StringUtils.isEmpty(note.getCategoryName()) ? "健康咨询服务费" : note.getCategoryName());
				detailArrMap.put(sysUser.getIdCardNumber(), 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() + "/#/h5/indexTask?id=" + note.getPackageId() + "&userId=" + note
					.getUserId());
			abstractArrList.add(abstractArr);
		});
		taxHelperSettlementModel.setCount(detailArrMap.size());
		List<TaxHelperSettlementModel.DetailedArr> detailedArrList = new ArrayList<>(detailArrMap.values());
		taxHelperSettlementModel.setDetailedArr(detailedArrList);
		taxHelperSettlementModel.setAbstractArr(abstractArrList);
		TaxHelperSettlementRequest taxHelperSettlementRequest = new TaxHelperSettlementRequest(taxHelperSettlementModel);
		TaxHelperResponse response = taxHelperService.settlement(taxHelperSettlementRequest);
		log.info("税邦云结算： {}", response);
		if (response.success()) {
			noteList.forEach(note -> {
				log.info("税邦云结算提交成功： {}", note.getSettleNo());
				//streamId 获取不到
				if (StringUtils.isEmpty(response.getMessage())) {
					log.info("税邦云结算提交成功 streamId 获取不到： {}", note.getSettleNo());
				}
				note.setUpdateTime(LocalDateTime.now());
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_SUBMIT.getType());
				// 新增字段streamId
				note.setStreamId(response.getMessage());
				wmScorePackageSettleNoteService.updateById(note);
			});
			return getResultMap("2000", "提交结算成功");
		} else {
			noteList.forEach(note -> {
				log.info("税邦云结算提交失败： {}", note.getSettleNo());
				note.setUpdateTime(LocalDateTime.now());
				note.setSettleNoteStatus(DingEnum.NOTE_STATUS_FAIL.getType());
				wmScorePackageSettleNoteService.updateById(note);
			});
			return getResultMap("4000", "结算失败");

		}


	}

	/**
	 * 记录用户认证信息
	 *
	 * @param response    响应记录
	 * @param member      用户
	 * @param subjectType 结算类型
	 * @param method      方法
	 */
	private void saveCertRecord(TaxHelperResponse response, SysUser member, String subjectType, String method) {
		// 记录认证结果
		SysCertResultRecord record = new SysCertResultRecord();
		record.setCode(response.getCode());
		record.setCreateTime(LocalDateTime.now());
		record.setDeptId(member.getDeptId());
		record.setMessage(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage() : CommonConstants.NO_RES_MSG);
		record.setStatus(null);
		record.setSubjectType(Integer.parseInt(subjectType));
		record.setMethod(method);
		record.setUserId(member.getUserId());
		sysCertResultRecordMapper.insert(record);
	}

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

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

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

		if ("1".equals(scorePackage.getIsReceive()) && isPickUpMethod) {
			log.error("积分包不能领取");
			return "积分包不能领取";
		}
		return null;
	}


	/**
	 * 校验用户信息
	 *
	 * @param member     用户
	 * @param methodName 方法名称
	 * @return 校验信息
	 */
	private String checkoutMemberInfo(SysUser member, String methodName) {

		// 校验用户是否存在
		if (member == null) {
			log.error("该用户不存在");
			return "该用户不存在，请联系要易管理员";
		}

		// 校验用户是否被删除
		if (DelEnum.DELETED.val().equals(member.getDelFlag())) {
			log.error("该用户已被删除");
			return "该用户已被删除，请联系要易管理员";
		}

		// 校验用户是否休眠
		if (!LockEnum.UN_LOCK.val().equals(member.getLockFlag())) {
			log.error("该用户已被休眠，请联系要易管理员");
			return "该用户已被休眠，请联系要易管理员";
		}

		// 根据方法名称校验用户状态
		List<Integer> taxHelperCertStatusList = new ArrayList<>();
		if (CommonConstants.ADD_MEMBER_METHOD.equals(methodName)) {
			taxHelperCertStatusList.add(TaxHelperCertStatus.UN_CERT.getCode());
		} else if (CommonConstants.USER_AGREEMENT_SIGNATURE_METHOD.equals(methodName)){
			taxHelperCertStatusList.add(TaxHelperCertStatus.ADD_MEMBER.getCode());
		} else if (CommonConstants.H5_TOKEN_METHOD.equals(methodName)) {
			taxHelperCertStatusList.add(TaxHelperCertStatus.ADD_MEMBER.getCode());
			// 税邦云调整回调时间为24小时，允许中途再次获取token
			taxHelperCertStatusList.add(TaxHelperCertStatus.CHECKING_UNBIND.getCode());
			taxHelperCertStatusList.add(TaxHelperCertStatus.CHECKING_BIND.getCode());
			taxHelperCertStatusList.add(TaxHelperCertStatus.UNCHECKED_BIND.getCode());
		} else if (CommonConstants.BINDING_CARD_CODE_METHOD.equals(methodName) || CommonConstants.ACK_BINDING_CARD_METHOD
				.equals(methodName)) {
			taxHelperCertStatusList.add(TaxHelperCertStatus.ADD_MEMBER.getCode());
			taxHelperCertStatusList.add(TaxHelperCertStatus.CHECKED_UNBIND.getCode());
			taxHelperCertStatusList.add(TaxHelperCertStatus.CHECKING_UNBIND.getCode());
		} else if ("pickUpScorePackage".equals(methodName)) {
			return null;
		} else {
			taxHelperCertStatusList.add(TaxHelperCertStatus.CERT.getCode());
		}

		if (!taxHelperCertStatusList.contains(member.getCertStatus())) {
			log.error("当前用户：{}-{}，不支持{}。", member.getRealname(), member.getUsername(), methodName);
			return "用户状态不支持操作";
		}

		return null;
	}


	/**
	 * 校验部门信息
	 *
	 * @param dept 部门
	 * @return 校验结果
	 */
	private String checkoutDeptInfo(SysDept dept) {

		// 校验部门是否存在
		if (dept == null) {
			log.error("该部门不存在");
			return "该部门不存在，请联系要易管理员";
		}

		// 校验部门是否被删除
		if (DelEnum.DELETED.val().equals(dept.getDelFlag())) {
			log.error("该部门已被删除");
			return "该部门已被删除，请联系要易管理员";
		}

		// 校验是否配置了企业的统一社会信用代码
		if (StringUtils.isEmpty(dept.getTaxCode())) {
			log.error("该部门未配置企业的统一社会信用代码");
			return "该部门未配置企业的统一社会信用代码，请联系要易管理员";
		}

		return null;
	}

	/**
	 * 校验部门结算信息
	 *
	 * @param deptSub 部门结算信息
	 * @param channel 渠道
	 * @return 校验结果
	 */
	private String checkoutDeptSubInfo(SysDeptSub deptSub, ChannelEnum channel, String subjectUserType) {

		// 校验用户是否存在
		if (deptSub == null) {
			log.error("该部门结算信息不存在");
			return "该部门结算信息不存在，请联系要易管理员";
		}

		// 校验用户是否被删除
		if (SubjectTypeEnum.ENABLE_FLAG_FALSE.getCode().equals(deptSub.getEnableFlag())) {
			log.error("该部门结算信息已被禁用");
			return "该部门结算信息已被删除，请联系要易管理员";
		}

		// 校验配置属性
		switch (channel) {
			case DING:
				if (StringUtils.isEmpty(deptSub.getAppId()) || StringUtils.isEmpty(deptSub.getAppSecret())
						|| StringUtils.isEmpty(deptSub.getRsaPublicKey()) || StringUtils.isEmpty(deptSub.getQueryUrl())) {
					log.error("部门{}结算信息配置不全，请联系要易管理员", channel.type());
					return "部门结算信息配置不全，请联系要易管理员";
				}
				break;
			case TAX_HELPER:
				if (StringUtils.isEmpty(deptSub.getAppId()) || StringUtils.isEmpty(deptSub.getAppSecret())
						|| StringUtils.isEmpty(deptSub.getQueryUrl()) || StringUtils.isEmpty(deptSub.getSubjectUserType())) {
					log.error("部门{}结算信息配置不全，请联系要易管理员", channel.type());
					return "部门结算信息配置不全，请联系要易管理员";
				}

				if (StringUtils.isNotEmpty(subjectUserType)) {
					if (!deptSub.getSubjectUserType().equals(subjectUserType)) {
						log.error("部门{}传入用户结算类型:{}与系统设置不匹配，请联系要易管理员", channel.type(), subjectUserType);
						return "传入用户结算类型+" + subjectUserType + "+与系统设置不匹配，请联系要易管理员";
					}
				}
				break;
		}

		return null;
	}

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

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

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

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

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

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

		return null;
	}

	/**
	 * 审核领包记录
	 *
	 * @param scorePackageStatus 领包记录
	 */
	private void approvalScorePackageStatus(WmScorePackageStatus scorePackageStatus) {

		// 审核领包记录
		LocalDateTime now = LocalDateTime.now();
		scorePackageStatus.setUpdateTime(now);
		scorePackageStatus.setStatus("2");
		scorePackageStatus.setTaskAddFlag("0");
		wmScorePackageStatusService.updateById(scorePackageStatus);

	}

	/**
	 * 获取
	 *
	 * @param code 状态码
	 * @param data 结果数据
	 * @return 结果map
	 */
	private Map<String, String> getResultMap(String code, String data) {
		Map<String, String> resMap = new HashMap<>(4);
		resMap.put("code", code);
		resMap.put("data", data);
		if ("2000".equals(code)) {
			resMap.put("success_msg", "SUCCESS");
		} else {
			resMap.put("error_msg", "FAILURE");
		}
		return resMap;
	}

}
