package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.WriterException;
import com.qunzhixinxi.hnqz.admin.api.constant.CacheConstants;
import com.qunzhixinxi.hnqz.admin.api.dto.UserDTO;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDictItem;
import com.qunzhixinxi.hnqz.admin.api.entity.SysRole;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.api.enums.SignatureStatusEnum;
import com.qunzhixinxi.hnqz.admin.api.vo.UserVO;
import com.qunzhixinxi.hnqz.admin.config.UpmsConfig;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.entity.input.NoticeApiInput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageApiInput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageApiOutput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmWkAlbumApiInput;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.DisplayStatusEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysCertResultRecordMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.admin.util.GetOpenIDUtil;
import com.qunzhixinxi.hnqz.admin.util.Html2ImageByJsWrapper;
import com.qunzhixinxi.hnqz.admin.util.QRCodeGenerator;
import com.qunzhixinxi.hnqz.admin.view.user.UserUpdateInput;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.ding.config.DingConfig;
import com.qunzhixinxi.hnqz.common.ding.entity.EmployCheckResponse;
import com.qunzhixinxi.hnqz.common.ding.entity.EmployCheckResultItem;
import com.qunzhixinxi.hnqz.common.ding.enums.DingEnum;
import com.qunzhixinxi.hnqz.common.ding.service.DingService;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.annotation.Inner;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import com.qunzhixinxi.hnqz.common.taxhelper.config.TaxHelperConfig;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperAddMemberModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperAddMemberRequest;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author hnqz
 * @date 2018/11/14
 * <p>
 * 手机验证码
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
@Api(value = "api", tags = "api接口")
public class ApiController {
	private final WmTaskContentService wmTaskContentService;
	private final WmTaskContentConfigService wmTaskContentConfigService;
	private final WmWkArticleService wmWkArticleService;
	private final SysDictItemService sysDictItemService;
	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmDaAgentService wmDaAgentService;
	private final SysUserService sysUserService;
	private final SysDeptService sysDeptService;
	private final WmTaskRuleService wmTaskRuleService;
	private final WmTaskTypeService wmTaskTypeService;
	private final WmWkArticleShareService wmWkArticleShareService;
	private final WmScorePackageService wmScorePackageService;
	private final WmScoreTaskTypeService wmScoreTaskTypeService;
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final WmTaskService wmTaskService;
	private final WmDaDistributionService wmDaDistributionService;
	private final WmDaDrugEntDrugtableService wmDaDrugEntDrugtableService;
	private final SysFileService sysFileService;
	private final WmFeedbackService wmFeedbackService;
	private final WmDaPharmacyService wmDaPharmacyService;
	private final RedisTemplate redisTemplate;
	private final DingService dingService;
	private final UpmsConfig upmsConfig;
	private final TaxHelperService taxHelperService;
	private final SysCertResultRecordMapper sysCertResultRecordMapper;
	private final SysDeptSubService sysDeptSubService;
	private final SysPublicParamService sysPublicParamService;
	private final WmWkAlbumService wmWkAlbumService;

	@SysLog("通过任务类型获取表单配置")
	@ApiOperation(value = "任务类型表单配置-通过任务类型获取表单配置", notes = "根据任务类型获取表单配置")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "taskTypeId", value = "任务类型ID", dataType = "long", paramType = "path")})
	@GetMapping("/getTaskContentConfigByTaskTypeId/{taskTypeId}")
	public R getById(@PathVariable String taskTypeId) {
		if (null == taskTypeId) {
			return R.failed("taskTypeId不能为空");

		}

		Map<String, Object> connfigMap = new LinkedHashMap<>();

		// 库存调查需要调查常规的和首次的
		if ("14".equals(taskTypeId) || "31".equals(taskTypeId)) {
			// 常规调查
			connfigMap.put("14", getTaskContentConfigByTaskTypeId("14"));
			// 首次调查
			connfigMap.put("31", getTaskContentConfigByTaskTypeId("31"));

		} else {
			connfigMap = getTaskContentConfigByTaskTypeId(taskTypeId);
		}

		return R.ok(connfigMap);
	}

	/**
	 * 根据任务类型id获取任务内容配置信息
	 *
	 * @param taskTypeId 任务类型id
	 * @return 任务内容配置信息
	 */
	private Map<String, Object> getTaskContentConfigByTaskTypeId(String taskTypeId) {
		Map<String, Object> connfigMap = new LinkedHashMap<>();
		Map<String, Object> dictMap = new LinkedHashMap<>();

		WmTaskContentConfig queryConn = new WmTaskContentConfig();
		queryConn.setTaskTypeId(taskTypeId);
		queryConn.setDelFlag("0");
		queryConn.setEnableFlag("0");
		List<WmTaskContentConfig> listConfig = wmTaskContentConfigService.list(
				new QueryWrapper<>(queryConn).orderByAsc("seq"));
		for (WmTaskContentConfig config :
				listConfig) {
			if ("select".equals(config.getTaskFiledType())) {
				SysDictItem sysDictItemConn = new SysDictItem();
				sysDictItemConn.setType(config.getDictGroupName());
				List<SysDictItem> dictItems = sysDictItemService.list(new QueryWrapper<>(sysDictItemConn));
				dictMap.put(config.getDictGroupName(), dictItems);
			}

			if ("domain".equals(config.getTaskFiledType())) {
				if ("ent_service".equals(config.getDictGroupName())) {
					List<WmDaDrugEnt> wmDaDrugEnts = new ArrayList<>();
					if (null == SecurityUtils.getUser()) {
						wmDaDrugEnts = wmDaDrugEntService.list();
					} else {
						wmDaDrugEnts = getDrugListBySecUser(SecurityUtils.getUser().getPlatId());
					}
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getEntname());
						map.put("value", wmDaDrugEnts.get(i).getId());
						map.put("type", "drug");
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);

				} else if ("ent_bus".equals(config.getDictGroupName())) {
					List<WmDaDistribution> wmDaDrugEnts = wmDaDistributionService.list();
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getGsmc());
						map.put("value", wmDaDrugEnts.get(i).getId());
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);
				} else if ("ent_dclx".equals(config.getDictGroupName())) {
					List<WmDaHospital> wmDaHospitalList = new ArrayList<>();
					List<Map<String, Object>> wmDaHospitalListList = new ArrayList<>();
					for (int i = 0; i < wmDaHospitalList.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaHospitalList.get(i).getYymc());
						map.put("value", wmDaHospitalList.get(i).getId());
						wmDaHospitalListList.add(map);
					}
					dictMap.put("hospital_service", wmDaHospitalListList);


					List<WmDaDistribution> wmDaDistributions = wmDaDistributionService.list();
					List<Map<String, Object>> wmDaDistributionList = new ArrayList<>();
					for (int i = 0; i < wmDaDistributions.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDistributions.get(i).getGsmc());
						map.put("value", wmDaDistributions.get(i).getId());
						wmDaDistributionList.add(map);
					}
					dictMap.put("distribution_service", wmDaDistributionList);
				} else if ("ent_pharmacy".equals(config.getDictGroupName())) {
					List<WmDaPharmacy> wmDaDrugEnts = wmDaPharmacyService.list();
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getPharmacyName());
						map.put("value", wmDaDrugEnts.get(i).getId());
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);
				} else if ("package_list".equals(config.getDictGroupName())) {
					/**
					 * 查询可以关联的积分包
					 */
					List<Map<String, Object>> listMap = new ArrayList<>();
					if (null == SecurityUtils.getUser()) {

					} else {
						UserVO userVO = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
						WmScorePackageStatus query = new WmScorePackageStatus();
						query.setUserId(userVO.getUserId() + "");
						query.setStatus("2");
						query.setTaskAddFlag("1");
						query.setDelFlag("0");
						query.setEnableFlag("0");

						List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(Wrappers.lambdaQuery(query));
						for (WmScorePackageStatus item : statusList) {
							WmScorePackage wmScorePackage = wmScorePackageService.getById(item.getPackageId());
							if (null != wmScorePackage) {
								if ("0".equals(wmScorePackage.getTaskAddFlag())) {
									continue;
								}
								if ("1".equals(wmScorePackage.getEnableFlag())) {
									continue;
								}
								if ("2".equals(wmScorePackage.getPackageType2())) {
									continue;
								}

								if ("28".equals(taskTypeId)) {
									if ("3".equals(wmScorePackage.getPackageType1())) {
										Map<String, Object> map = new HashMap<>();
										map.put("label", wmScorePackage.getScorePackageName());
										map.put("value", wmScorePackage.getId());
										listMap.add(map);
									}

								} else {
									if ("3".equals(wmScorePackage.getPackageType1())) {
										continue;
									}
									/**
									 * 过滤有效任务类型
									 */
									WmScoreTaskType taskType = new WmScoreTaskType();
									taskType.setTaskTypeId(taskTypeId);
									taskType.setScoreId(wmScorePackage.getId());

									int total = wmScoreTaskTypeService.count(Wrappers.query(taskType));

									if (total != 0) {
										Map<String, Object> map = new HashMap<>();
										map.put("label", wmScorePackage.getScorePackageName());
										map.put("value", wmScorePackage.getId());
										listMap.add(map);
									}
								}
							}
						}
					}

					dictMap.put(config.getDictGroupName(), listMap);
				}

			}
		}
		connfigMap.put("config", listConfig);
		connfigMap.put("dict", dictMap);
		return connfigMap;
	}

	@SysLog("通过任务类型获取表单配置")
	@ApiOperation(value = "任务类型表单配置-通过任务类型获取表单配置", notes = "根据任务类型获取表单配置")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "taskTypeId", value = "任务类型ID", dataType = "long", paramType = "path")})
	@GetMapping("/getTaskContentConfigByTaskTypeByShareId/{taskTypeId}")
	public R getShareById(@PathVariable String taskTypeId) {
		if (null == taskTypeId) {
			return R.failed("taskTypeId不能为空");

		}

		Map<String, Object> connfigMap = new LinkedHashMap<>();
		Map<String, Object> dictMap = new LinkedHashMap<>();

		WmTaskContentConfig queryConn = new WmTaskContentConfig();
		queryConn.setTaskTypeId(taskTypeId);
		queryConn.setDelFlag("0");
		queryConn.setEnableFlag("0");

		List<WmTaskContentConfig> listConfig =
				wmTaskContentConfigService.list(new QueryWrapper<>(queryConn).orderByAsc("seq", "id"));
		for (WmTaskContentConfig config :
				listConfig) {
			if ("select".equals(config.getTaskFiledType())) {
				SysDictItem sysDictItemConn = new SysDictItem();
				sysDictItemConn.setType(config.getDictGroupName());
				List<SysDictItem> dictItems = sysDictItemService.list(new QueryWrapper<>(sysDictItemConn));
				dictMap.put(config.getDictGroupName(), dictItems);
			}

			if ("domain".equals(config.getTaskFiledType())) {
				if ("ent_service".equals(config.getDictGroupName())) {
					List<WmDaDrugEnt> wmDaDrugEnts = new ArrayList<>();
					if (null == SecurityUtils.getUser()) {
						wmDaDrugEnts = wmDaDrugEntService.list();
					} else {
						wmDaDrugEnts = getDrugListBySecUser(SecurityUtils.getUser().getPlatId());
					}
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getEntname());
						map.put("value", wmDaDrugEnts.get(i).getId());
						map.put("type", "drug");
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);

					List<WmDaDistribution> wmDaDistributions = wmDaDistributionService.list();
					List<Map<String, Object>> wmDaDistributionList = new ArrayList<>();
					for (int i = 0; i < wmDaDistributions.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDistributions.get(i).getGsmc());
						map.put("value", wmDaDistributions.get(i).getId());
						wmDaDistributionList.add(map);
					}
					dictMap.put("distribution_service", listMap);
				} else if ("ent_bus".equals(config.getDictGroupName())) {
					List<WmDaDistribution> wmDaDrugEnts = wmDaDistributionService.list();
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getGsmc());
						map.put("value", wmDaDrugEnts.get(i).getId());
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);
				} else if ("ent_pharmacy".equals(config.getDictGroupName())) {
					List<WmDaPharmacy> wmDaDrugEnts = wmDaPharmacyService.list();
					List<Map<String, Object>> listMap = new ArrayList<>();
					for (int i = 0; i < wmDaDrugEnts.size(); i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("label", wmDaDrugEnts.get(i).getPharmacyName());
						map.put("value", wmDaDrugEnts.get(i).getId());
						listMap.add(map);
					}
					dictMap.put(config.getDictGroupName(), listMap);
				} else if ("package_list".equals(config.getDictGroupName())) {
					/**
					 * 查询可以关联的积分包
					 */
					List<Map<String, Object>> listMap = new ArrayList<>();
					if (null == SecurityUtils.getUser()) {

					} else {
						UserVO userVO = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
						WmScorePackageStatus query = new WmScorePackageStatus();
						query.setUserId(userVO.getUserId() + "");
						query.setStatus("2");
						query.setTaskAddFlag("1");
						query.setDelFlag("0");
						query.setEnableFlag("0");

						List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(Wrappers.lambdaQuery(query));
						for (WmScorePackageStatus item : statusList) {
							WmScorePackage wmScorePackage = wmScorePackageService.getById(item.getPackageId());
							if (null != wmScorePackage) {
								if ("0".equals(wmScorePackage.getTaskAddFlag())) {
									continue;
								}
								if ("1".equals(wmScorePackage.getEnableFlag())) {
									continue;
								}
								if ("2".equals(wmScorePackage.getPackageType2())) {
									continue;
								}

								if ("28".equals(taskTypeId)) {
									if ("3".equals(wmScorePackage.getPackageType1())) {
										Map<String, Object> map = new HashMap<>();
										map.put("label", wmScorePackage.getScorePackageName());
										map.put("value", wmScorePackage.getId());
										listMap.add(map);
									}

								} else {
									if ("3".equals(wmScorePackage.getPackageType1())) {
										continue;
									}
									/**
									 * 过滤有效任务类型
									 */
									WmScoreTaskType taskType = new WmScoreTaskType();
									taskType.setTaskTypeId(taskTypeId);
									taskType.setScoreId(wmScorePackage.getId());

									int total = wmScoreTaskTypeService.count(Wrappers.query(taskType));

									if (total != 0) {
										Map<String, Object> map = new HashMap<>();
										map.put("label", wmScorePackage.getScorePackageName());
										map.put("value", wmScorePackage.getId());
										listMap.add(map);
									}
//									List<WmScoreTaskType> taskTypes = wmScoreTaskTypeService.
//											list(Wrappers.query(taskType));
//
//									if (CollectionUtils.isNotEmpty(taskTypes)) {
//										Map<String, Object> map = new HashMap<>();
//										map.put("label", wmScorePackage.getScorePackageName());
//										map.put("value", wmScorePackage.getId());
//										listMap.add(map);
//									}
								}

							}
						}
					}

					dictMap.put(config.getDictGroupName(), listMap);
				}

			}
		}

		connfigMap.put("config", listConfig);
		connfigMap.put("dict", dictMap);
		return R.ok(connfigMap);
	}

	@GetMapping("/getDeptBuildName/{deptId}")
	public R getDeptBuildName(@PathVariable String deptId) {
		Map<String, Object> connfigMap = new LinkedHashMap<>();
		if (null == deptId || "".equals(deptId)) {
			return R.failed("deptId不能为空");
		}

		connfigMap.put("buildName", wmDaAgentService.getDeptBuildName(deptId));
		return R.ok(connfigMap);
	}

	@ApiOperation(value = "用户信息-获取用户基本信息", notes = "登录认证成功后，调用此接口获取用户基本信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "code", value = "小程序信息code", dataType = "String", paramType = "query")})
	@GetMapping("/getUserInfoByCode")
	public R getUserInfo(String code, String avatar) {
		Map<String, Object> result = new HashMap<>();

		UserDTO userDTO = new UserDTO();
		userDTO.setPlatId(SecurityUtils.getUser().getPlatId());
		//获取用户基本信息
		List<UserVO> sysUserList = sysUserService.getUserVoByPlatId(userDTO);

		if (sysUserList.size() == 0) {
			return R.failed("账号信息异常，请联系管理员");
		}

		//获取小程序openid
		Map<String, Object> opemMap = GetOpenIDUtil.oauth2GetOpenid(code,upmsConfig.getWechatEnv());
		System.out.println("opemMap:" + opemMap);
		if (null != opemMap) {
			String openid = opemMap.get("openid") + "";

			SysUser sysUser1 = sysUserService.getById(SecurityUtils.getUser().getId());
			if (null == sysUser1.getWxOpenid() || null == sysUser1.getAvatar()) {
				sysUser1.setWxOpenid(openid);
				sysUser1.setAvatar(avatar);
				sysUserService.saveOrUpdate(sysUser1);
			}
		}
		Integer completedCount = 0;
		Integer sumCount = 0;


		List<Integer> roleList = new ArrayList<>();
		if (null != sysUserList && sysUserList.size() > 0) {
			List<Map<String, Object>> list = new ArrayList<>();
			for (UserVO sysU : sysUserList) {
				Integer onTheWay = 0;
				Integer waitApprove = 0;
				Map<String, Object> mapOne = new HashMap<>();
				mapOne.put("userId", sysU.getUserId() + "");
				mapOne.put("realname", sysU.getRealname() + "");
				mapOne.put("phone", sysU.getPhone() + "");
				mapOne.put("idCardNumber", sysU.getIdCardNumber());
				mapOne.put("certStatus", sysU.getCertStatus());
				mapOne.put("rljCertStatus", sysU.getRljCertStatus());
				mapOne.put("userSign", sysU.getUserSign());
				mapOne.put("certRemark", sysU.getCertRemark());
				mapOne.put("taxHelperAgreementSignature", sysU.getTaxHelperAgreementSignature());

				if (redisTemplate.hasKey(CacheConstants.USER_NOTICE_KEY + sysU.getUserId())) {
					mapOne.put("notice", true);
				}
				if (redisTemplate.hasKey(CacheConstants.USER_ADD_NOTICE_KEY + sysU.getUserId())) {
					mapOne.put("userNewFlag", true);
				}

				if (null == sysU.getAvatar() || "".equals(sysU.getAvatar())) {
					mapOne.put("avatar", avatar);
					SysUser sysUser2 = sysUserService.getById(sysU.getUserId());
					sysUser2.setAvatar(avatar);
					sysUserService.updateById(sysUser2);
				} else {
					mapOne.put("avatar", sysU.getAvatar() + "");
				}

				SysDept sysDept = sysDeptService.getById(sysU.getDeptId());
				if (null != sysDept) {
					mapOne.put("deptId", sysDept.getDeptId() + "");
					mapOne.put("deptName", sysDept.getName() + "");
				}

				String management;
				Boolean managementFlag = false;
				if (sysDept.getLevel() == 2) {
					WmDaDrugEnt drugEnt = wmDaDrugEntService.selectByDeptId(sysDept.getDeptId());
					mapOne.put("management", drugEnt.getManagement() + "");
					management = drugEnt.getManagement();
				} else {
					WmDaAgent agent = wmDaAgentService.selectByDeptId(sysDept.getDeptId());
					mapOne.put("management", agent.getManagement() + "");
					management = agent.getManagement();
				}

				// 小程序角色:5-全职学术信息沟通专员, 6-兼职学术信息沟通专员, 10-兼职CRC, 13-HCP
				List<Integer> roleIdList = sysU.getRoleList().stream().filter(item ->
						item.getRoleId() == 5 || item.getRoleId() == 6 || item.getRoleId() == 10 || item.getRoleId() == 13)
						.map(SysRole::getRoleId).collect(Collectors.toList());

				if ("2".equals(management) && roleIdList.contains(5)) {
					managementFlag = true;
				} else if ("3".equals(management) && roleIdList.contains(6)) {
					managementFlag = true;
				} else if ("3".equals(management) && roleIdList.contains(10)) {
					managementFlag = true;
				} else if ("4".equals(management)) {
					managementFlag = true;
				}
				mapOne.put("managementFlag", managementFlag);

				WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(sysU.getDrugEntId());
				if (null != wmDaDrugEnt) {
					mapOne.put("drugEntId", wmDaDrugEnt.getId() + "");
					mapOne.put("drugEntName", wmDaDrugEnt.getEntname() + "");
				}

				mapOne.put("roles", roleIdList);
				mapOne.put("temp1", sysU.getTemp1() + "");
				mapOne.put("temp2", sysU.getTemp2() + "");
				mapOne.put("temp3", sysU.getTemp3() + "");
				mapOne.put("temp4", sysU.getTemp4() + "");
				mapOne.put("temp5", sysU.getTemp5() + "");

				/**
				 * 查询待审核包
				 */
				WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
				wmScorePackageStatus.setUserId(sysU.getUserId() + "");
				wmScorePackageStatus.setTaskAddFlag("1");
				wmScorePackageStatus.setDelFlag("0");
				wmScorePackageStatus.setEnableFlag("0");
				List<WmScorePackageStatus> statusList = wmScorePackageStatusService.
						list(Wrappers.query(wmScorePackageStatus));

				List<Map<String, Object>> listMap = new ArrayList<>();

				for (WmScorePackageStatus item : statusList) {
					WmScorePackage wmScorePackage = wmScorePackageService.getById(item.getPackageId());
					if (null != wmScorePackage) {
						if ("1".equals(item.getStatus())) {
							waitApprove++;
						} else if ("2".equals(item.getStatus())) {
							onTheWay++;
							Map<String, Object> map = new HashMap<>();
							map.put("label", wmScorePackage.getScorePackageName());
							map.put("value", wmScorePackage.getId());
							listMap.add(map);
						}
					}
				}
				mapOne.put("packageList", listMap);
				mapOne.put("waitApprove", waitApprove + "");
				mapOne.put("onTheWay", onTheWay + "");
				mapOne.put("userType", sysU.getUserType());
				mapOne.put("jumpFlag", "0");
				if ("北京遥领医疗科技有限公司".equals(sysDept.getName())) {
					mapOne.put("jumpFlag", "1");
				}
				/**
				 * @Modify: start
				 * @Version: v2021.4.16
				 * @Author: ryz
				 * @Date: 2021/4/28
				 */
				SysDeptSub query = new SysDeptSub();
				query.setDeptId(sysU.getDeptId());
				query.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
				List<SysDeptSub> subList = sysDeptSubService.list(Wrappers.query(query));
//				List<String> subTypeList = new ArrayList<>();
//				for (SysDeptSub item : subList) {
//					subTypeList.add(item.getSubjectType());
//					if(SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode().equals(item.getSubjectType())
//					&& "北京遥领医疗科技有限公司".equals(item.getSubjectName())){
//						mapOne.put("jumpFlag", "1");
//					}
//				}
				List<String> subTypeList = subList.stream()
						.map(SysDeptSub::getSubjectType)
						.collect(Collectors.toList());
				mapOne.put("subList", subTypeList);

				list.add(mapOne);

				roleList.addAll(roleIdList);

			}

			result.put("userInfo", list);
			result.put("roles", roleList);


			result.put("completedCount", completedCount);
			result.put("sumCount", sumCount);
			result.put("taskProgress", 0);
			if (sumCount > 0) {
				double d = Math.ceil(completedCount * 100 / sumCount);
				if (d > 100) {
					d = 100;
				}
				result.put("taskProgress", new Double(d).intValue());
			}

		}
		return R.ok(result);
	}

	/**
	 * @param input
	 * @return
	 */
	@ApiOperation(value = "积分-获取积分规则", notes = "获取积分规则")
	@SysLog("获取积分规则")
	@GetMapping("/getPackageCanTaskList")
	public R getPackageCanTaskList(WmScorePackageApiInput input) {
		if (null == input.getPackageId()) {
			return R.failed("积分包ID不能为空");
		}

		WmScorePackage wmScorePackage = wmScorePackageService.getById(input.getPackageId());
		if (StringUtils.isEmpty(wmScorePackage.getRuleId())) {
			return R.ok();
		}
		WmScoreTaskType query = new WmScoreTaskType();
		query.setScoreId(input.getPackageId());

		/**
		 * 所有能做的任务
		 */
		List<WmScoreTaskType> wmScoreTaskTypeList = wmScoreTaskTypeService.list(Wrappers.query(query));

		List<String> baseIds = wmScoreTaskTypeList.stream().
				map(WmScoreTaskType::getTaskTypeId).collect(Collectors.toList());

		List<WmTaskType> baseTypeList = wmTaskTypeService.
				list(Wrappers.<WmTaskType>query().lambda().in(WmTaskType::getParentId, baseIds));

		List<String> baseNames = baseTypeList.stream().
				map(WmTaskType::getTaskTypeName).collect(Collectors.toList());
		WmTaskType wmTaskType = new WmTaskType();
		wmTaskType.setRuleId(wmScorePackage.getRuleId());
		wmTaskType.setDelFlag("0");
		wmTaskType.setEnableFlag("0");
		List<WmTaskType> taskTypeList = wmTaskTypeService.list(Wrappers.query(wmTaskType)
				.lambda().in(WmTaskType::getTaskTypeName, baseNames));

		return R.ok(taskTypeList);
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "积分-获取积分规则", notes = "获取积分规则")
	@SysLog("获取积分规则")
	@GetMapping("/getTaskTypeListByRuleId")
	public R getTaskTypeListByRuleId(WmTaskType wmTaskType) {

		if (StringUtils.isEmpty(wmTaskType.getRuleId())) {
			return R.failed("积分规则ID不能为空");
		}

		wmTaskType.setDelFlag("0");
		wmTaskType.setEnableFlag("0");
		List<String> noDisplayTaskTypeNameList = Arrays.asList("专家咨询", "受试者管理", "医学撰写", "受试者招募", "数据管理",
				"统计分析", "临床监察", "通用", "患者教育");
		List<WmTaskType> wmTaskTypeList = wmTaskTypeService.list(Wrappers.query(wmTaskType)).stream()
				.filter(taskType -> !noDisplayTaskTypeNameList.contains(taskType.getTaskTypeName()))
				.collect(Collectors.toList());

		return R.ok(wmTaskTypeList);
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "积分-获取积分规则", notes = "获取积分规则")
	@SysLog("获取积分规则")
	@GetMapping("/taskTypeScoreList")
	public R taskTypeScoreList(WmTaskType wmTaskType) {
		if (null == wmTaskType.getDurgentId()) {
			return R.failed("药企ID不能为空");
		}

		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(wmTaskType.getDurgentId());

		SysUser sysUser = new SysUser();
		sysUser.setDrugEntId(wmDaDrugEnt.getId());
		sysUser.setPlatId(SecurityUtils.getUser().getPlatId());
		sysUser.setDelFlag("0");
		List<SysUser> sysUserList = sysUserService.list(Wrappers.query(sysUser));
		if (sysUserList.size() > 0) {
			SysDept sysDept = sysDeptService.getById(sysUserList.get(0).getDeptId());
			wmTaskType.setLevel1Id(sysDept.getLevel2Id() + "");
		} else {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
			wmTaskType.setLevel1Id(sysDept.getLevel2Id() + "");
		}


		wmTaskType.setDelFlag("0");
		wmTaskType.setEnableFlag("0");
		wmTaskType.setTaskTypeLevel("2");

		return R.ok(wmTaskTypeService.list(Wrappers.query(wmTaskType)));
	}

	/**
	 * 新增任务内容表
	 *
	 * @param wmTaskContent 任务内容表
	 * @return R
	 */
	@ApiOperation(value = "任务-新增任务内容表", notes = "新增任务内容表")
	@SysLog("新增任务内容表")
	@PostMapping("/saveTaskContent")
	public R saveTaskContent(@RequestBody WmTaskContent wmTaskContent) {
		return wmTaskContentService.saveTaskContent(wmTaskContent);
	}

	/**
	 * 修改任务内容表
	 *
	 * @param wmTaskContent 任务内容表
	 * @return R
	 */
	@ApiOperation(value = "任务-修改任务内容表", notes = "修改任务内容表")
	@SysLog("修改任务内容表")
	@PostMapping("/updateTaskContent")
	public R updateById(@RequestBody WmTaskContent wmTaskContent) {
		return R.ok(wmTaskContentService.updateById(wmTaskContent));
	}

	/**
	 * 分页查询
	 *
	 * @param page        分页对象
	 * @param wmWkArticle 文库-文章
	 * @return
	 */
	/**
	 * @param page
	 * @param wmWkArticle
	 * @return
	 */
	@ApiOperation(value = "文章-分页获取资讯列表", notes = "分页获取资讯列表")
	@GetMapping("/getArticlePage")
	public R getWmWkArticlePage(Page page, WmWkArticle wmWkArticle) {
		WmWkArticle query = new WmWkArticle();
		query.setEnableFlag(0);
		query.setDelFlag(0);
		LambdaQueryWrapper<WmWkArticle> wrapper = Wrappers.query(query).lambda();
		if (StringUtils.isNotEmpty(wmWkArticle.getArea())) {
			wrapper.like(WmWkArticle::getArea, wmWkArticle.getArea());
		}
		if (StringUtils.isNotEmpty(wmWkArticle.getTitle())) {
			wrapper.like(WmWkArticle::getTitle, wmWkArticle.getTitle());
		}
		wrapper.orderByDesc(WmWkArticle::getHotFlag);
		wrapper.orderByDesc(WmWkArticle::getCreateTime);
		IPage<WmWkArticle> pages = wmWkArticleService.page(page, wrapper);

//		if (showHot) {
//			if (page.getCurrent() == 1L) {
//				for (int i = 0; i < pages.getRecords().size(); i++) {
//					WmWkArticle wkArticle = pages.getRecords().get(i);
//					wkArticle.setHotFlag(1);
////					redisTemplate.opsForZSet().add(CacheConstants.ARTICLE_HOT_KEY, wkArticle.getId(),
////							wmWkArticle.getForwardNum());
//					if (i >= 4) {
//						break;
//					}
//				}
//			}
//		} else {
//			if (page.getCurrent() == 1L) {
//				Set<ZSetOperations.TypedTuple<String>> hotIds = redisTemplate.opsForZSet()
//						.reverseRangeWithScores(CacheConstants.ARTICLE_HOT_KEY, 0, 4);
//				List<Integer> ids = new ArrayList<>();
//				hotIds.forEach(item -> ids.add(Integer.parseInt(item.getValue())));
//				for (WmWkArticle item : pages.getRecords()) {
//					if(ids.contains(item.getId())){
//						item.setHotFlag(1);
//					}
//				}
//			}
//
//		}
		return R.ok(pages);
	}


	/**
	 * 通过id查询文库-文章
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "文章-通过id获取资讯列表", notes = "通过id获取资讯列表")
	@GetMapping("/getArticleById")
	public R getArticleById(Integer id) {
		WmWkArticle wmWkArticle = wmWkArticleService.getById(id);
		wmWkArticle.setReadNum(wmWkArticle.getReadNum() + 1);

//		if (null != id) {
//			redisTemplate.opsForZSet().add(CacheConstants.ARTICLE_HOT_KEY, id.toString(),
//					wmWkArticle.getForwardNum() + wmWkArticle.getReadNum());
//		}

		return R.ok(wmWkArticle);
	}

	/**
	 * 通过id查询文库-相册
	 *
	 * @param articleId   文章id
	 * @param shareUserId 分享人id
	 * @param openUserId  获取打开人openid授权码
	 * @param type        操作类型
	 * @param packageId   积分包id
	 * @param sharePicUrl 分享图片链接
	 * @return 结果
	 */
	@ApiOperation(value = "文章-通过分享链接，获取文章", notes = "文章-通过分享链接，获取文章")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "articleId", value = "文章ID", dataType = "String"),
			@ApiImplicitParam(name = "shareUserId", value = "分享人ID", dataType = "String"),
			@ApiImplicitParam(name = "openUserId", value = "获取打开人openid的授权码", dataType = "String"),
			@ApiImplicitParam(name = "type", value = "操作类型", dataType = "String"),
			@ApiImplicitParam(name = "packageId", value = "所属积分包id", dataType = "String"),
			@ApiImplicitParam(name = "sharePicUrl", value = "分享url", dataType = "String")
	})
	@GetMapping("/shareArticleById")
	public R<?> shareArticleById(String articleId, String shareUserId, String openUserId, String type, String packageId, String sharePicUrl) {
		return shareAndReadTaskMethod(articleId, shareUserId, openUserId, type, packageId, sharePicUrl, "article");
	}


	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param wmWkAlbum 文库-相册
	 * @return
	 */
	@ApiOperation(value = "相册-分页获取相册列表", notes = "分页获取相册列表")
	@GetMapping("/getAlbumPage")
	public R getWmWkAlbumPage(Page page, WmWkAlbum wmWkAlbum, String shareUserId) {

		//查询当前登录人药企的
		System.out.println(shareUserId);
		if (StringUtils.isNotEmpty(shareUserId)) {
			WmWkAlbumApiInput input = new WmWkAlbumApiInput();
			SysUser sysUser = sysUserService.getById(shareUserId);
			List<String> drugIds = new ArrayList<>();
			SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
			if (sysDept.getLevel() == 2) {
				WmDaDrugEnt drugEnt = wmDaDrugEntService.selectByDeptId(sysDept.getDeptId());
				drugIds.add(drugEnt.getId());
			}
			if (sysDept.getLevel() == 3 || sysDept.getLevel() == 4) {

				List<WmDaDrugEnt> entList = wmDaDrugEntService.getListByCsoDeptId(sysDept.getDeptId());

				drugIds.addAll(entList.stream().map(WmDaDrugEnt::getId).collect(Collectors.toList()));
			}

			/**
			 * 能查到药企
			 */
			if (CollectionUtils.isNotEmpty(drugIds)) {
				input.setDrugIds(drugIds);
				Page pageAnswer2 = wmWkAlbumService.pageByCondition(page, input);
				return R.ok(pageAnswer2);
			}
		}

		wmWkAlbum.setDelFlag(0);
		wmWkAlbum.setEnableFlag(0);
		Page pageAnswer = wmWkAlbumService.page(page, Wrappers.query(wmWkAlbum)
				.lambda()
				.orderByDesc(WmWkAlbum::getCreateTime));
		return R.ok(pageAnswer);
	}

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param wmWkAlbum 文库-相册
	 * @return
	 */
	@Inner(false)
	@ApiOperation(value = "相册-分页获取相册列表", notes = "分页获取相册列表")
	@GetMapping("/getAlbumPageNew")
	public R getAlbumPageNew(Page page, WmWkAlbum wmWkAlbum, String shareUserId) {

		//查询当前登录人药企的
		System.out.println(shareUserId);
		if (StringUtils.isNotEmpty(shareUserId)) {
			WmWkAlbumApiInput input = new WmWkAlbumApiInput();
			SysUser sysUser = sysUserService.getById(shareUserId);
			input.setDeptId(sysUser.getDeptId());
			Page pageAnswer2 = wmWkAlbumService.pageByConditionNew(page, input);
			return R.ok(pageAnswer2);
		}

		wmWkAlbum.setDelFlag(0);
		wmWkAlbum.setEnableFlag(0);
		Page pageAnswer = wmWkAlbumService.page(page, Wrappers.query(wmWkAlbum)
				.lambda()
				.orderByDesc(WmWkAlbum::getCreateTime));

		return R.ok(pageAnswer);
	}


	/**
	 * 通过id查询文库-相册
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "相册-通过id获取相册信息", notes = "通过id获取相册信息")
	@GetMapping("/getAlbumById")
	public R getById(Integer id) {
		WmWkAlbum wmWkAlbum = wmWkAlbumService.getById(id);
		if (null != wmWkAlbum) {
			if (null != wmWkAlbum.getGlyp()) {
				if (wmWkAlbum.getGlyp().indexOf(",") > 0) {
					String drugTables[] = wmWkAlbum.getGlyp().split(",");
					List<String> stringList = new ArrayList<>();
					for (String str : drugTables) {
						stringList.add(str);
					}
					List<WmDaDrugEntDrugtable> wmDaDrugEntDrugtableList = wmDaDrugEntDrugtableService.listByIds(stringList);
					if (wmDaDrugEntDrugtableList.size() > 0) {
						String drugStr = "";
						for (int i = 0; i < wmDaDrugEntDrugtableList.size(); i++) {
							drugStr += wmDaDrugEntDrugtableList.get(i).getDrugname();
							if (i < wmDaDrugEntDrugtableList.size() - 1) {
								drugStr += "、";
							}
						}
						wmWkAlbum.setGlyp(drugStr);
					}
				} else {
					WmDaDrugEntDrugtable wmDaDrugEntDrugtable = wmDaDrugEntDrugtableService.getById(wmWkAlbum.getGlyp());
					if (null != wmDaDrugEntDrugtable) {
						wmWkAlbum.setGlyp(wmDaDrugEntDrugtable.getDrugname());
					}
				}
			}
		}
		return R.ok(wmWkAlbum);
	}


	/**
	 * 通过id查询文库-相册
	 *
	 * @param id          相册id
	 * @param shareUserId 分享人id
	 * @param openUserId  获取打开人openid授权码
	 * @param type        操作类型
	 * @param packageId   积分包id
	 * @param sharePicUrl 分享图片链接
	 * @return 结果
	 */
	@ApiOperation(value = "相册-分享通过分享链接，获取相册", notes = "通过分享链接，获取相册  type=share 分享， type=open 分享链接打开")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "相册id", dataType = "String"),
			@ApiImplicitParam(name = "shareUserId", value = "分享人ID", dataType = "String"),
			@ApiImplicitParam(name = "openUserId", value = "获取打开人openid的授权码", dataType = "String"),
			@ApiImplicitParam(name = "type", value = "操作类型", dataType = "String"),
			@ApiImplicitParam(name = "packageId", value = "所属积分包id", dataType = "String"),
			@ApiImplicitParam(name = "sharePicUrl", value = "分享url", dataType = "String")
	})
	@GetMapping("/shareAlbumById")
	public R<?> shareAlbumById(String id, String shareUserId, String openUserId, String type, String packageId, String sharePicUrl) {
		return shareAndReadTaskMethod(id, shareUserId, openUserId, type, packageId, sharePicUrl, "album");
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "药企-获取药企列表", notes = "获取药企列表")
	@GetMapping("/getDrugEntList")
	public R listDrugEnt(WmDaDrugEnt wmDaDrugEnt) {
		System.out.println("SecurityUtils.getUser():" + SecurityUtils.getUser());
		System.out.println("SecurityUtils.getUser().getPlatId():" + SecurityUtils.getUser().getPlatId());

		List<WmDaDrugEnt> wmDaDrugEntList = new ArrayList<>();
		if (null == SecurityUtils.getUser()) {
			wmDaDrugEnt.setDelFlag("0");
			wmDaDrugEnt.setDelFlag("0");
			return R.ok(wmDaDrugEntService.list(Wrappers.query(wmDaDrugEnt)));
		} else {
			List<SysUser> list = sysUserService.getUserByPlatId(SecurityUtils.getUser().getPlatId());
			if (list.size() > 0) {
				List<String> deptIdList = new ArrayList<>();
				deptIdList.add("-1");
				for (SysUser sysU : list) {
					UserVO userVO = sysUserService.selectUserVoById(sysU.getUserId());
					for (SysRole sysRole : userVO.getRoleList()) {
						if (5 == sysRole.getRoleId() || 6 == sysRole.getRoleId()) {
							deptIdList.add(sysU.getDrugEntId() + "");
						}
					}
				}
				return R.ok(wmDaDrugEntService.listByIds(deptIdList));
			}
		}
		return R.ok();
	}


	public List<WmDaDrugEnt> getDrugListBySecUser(String platId) {
		List<SysUser> list = sysUserService.getUserByPlatId(platId);
		if (list.size() > 0) {
			List<String> deptIdList = new ArrayList<>();
			for (SysUser sysU : list) {
				deptIdList.add(sysU.getDeptId() + "");
			}

			List<String> agentIdList = new ArrayList<>();
			List<SysDept> deptList = sysDeptService.listByIds(deptIdList);
			if (deptList.size() > 0) {
				for (SysDept sysD : deptList) {
					System.out.println("SysDept:" + sysD.getLevel());

					if (3 == sysD.getLevel()) {
						System.out.println("sysD.getLevel2Id():" + sysD.getLevel2Id());
						agentIdList.add(sysD.getLevel2Id() + "");
					} else if (4 == sysD.getLevel()) {
						System.out.println("sysD.getLevel3Id():" + sysD.getLevel3Id());
						agentIdList.add(sysD.getLevel3Id() + "");
					}
				}
			}

			if (agentIdList.size() > 0) {
				List<String> drugIdList = new ArrayList<>();
				List<WmDaAgent> wmDaAgentList = wmDaAgentService.listByIds(agentIdList);
				if (wmDaAgentList.size() > 0) {
					for (WmDaAgent wmDaAgent : wmDaAgentList) {
						if (null != wmDaAgent.getExtDrugEnt()) {
							drugIdList.addAll(Arrays.asList(wmDaAgent.getExtDrugEnt().split(",")));
						}
						drugIdList.add(wmDaAgent.getDrugEntId());
					}
					return wmDaDrugEntService.listByIds(drugIdList);
				}


			}

		}
		return null;
	}

	private final WmUserSignService wmUserSignService;


	/**
	 * 通过id查询用户签到表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "签到-通过ID获取签到信息", notes = "通过id查询")
	@GetMapping("/getSignInfoById")
	public R getSignInfoById(Integer id) {
		return R.ok(wmUserSignService.getById(id));
	}

	/**
	 * 新增用户签到表
	 *
	 * @param wmUserSign 用户签到表
	 * @return R
	 */
	@ApiOperation(value = "签到-新增用户签到表", notes = "新增用户签到表")
	@SysLog("新增用户签到表")
	@PostMapping("/saveSignInfo")
	public R save(@RequestBody WmUserSign wmUserSign) {
		if (null == wmUserSign.getLatitude() || null == wmUserSign.getLongitude()) {
			return R.failed("签到经纬度不能为空");
		}

		return wmUserSignService.saveWmUserSign(wmUserSign);
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "签到-通过用户ID获取签到列表", notes = "通过用户ID获取签到列表")
	@GetMapping("/getSignListByUserId")
	public R listDrugEnt(WmUserSign wmUserSign) {
		return R.ok(wmUserSignService.list(Wrappers.query(wmUserSign)));
	}

	private final WmDaHospitalService wmDaHospitalService;

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "医院-获取医院列表", notes = "医院-获取医院列表")
	@GetMapping("/getHospitalList")
	public R getHospitalList(String longitude, String latitude, String type) {
		return R.ok(wmDaHospitalService.list(Wrappers.emptyWrapper()));
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "积分包-获取用户积分包", notes = "积分包-获取用户积分包，selType  众包用户传值，1 可领取  2 已领取")
	@GetMapping("/getUserScorePackageList2")
	public R getUserScorePackageList2(Page page, int selType, String packageName, String selDate, String activeId) {

		UserVO userVO = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
//		Page scorePage = null;

		List<WmScorePackageApiOutput> scorePackageList = new ArrayList<>();
		if (1 == selType && isZbRole(userVO.getRoleList(), 5)) {
			return R.ok();
		}


//		LambdaQueryWrapper<WmScorePackage> scoreQuery = Wrappers.lambdaQuery(query);
//		Boolean inFlag = false;


		List<Map<String, Object>> resultList = new ArrayList<>();

//		String packageType2 = "1";
//		if("1".equals(userVO.getUserType())){
//			packageType2 = "2";
//		}

		IPage<WmScorePackageApiOutput> scorePage;
		// 小程序角色:5-全职学术信息沟通专员, 6-兼职学术信息沟通专员, 10-兼职CRC, 13-HCP
		if (1 == selType && (isZbRole(userVO.getRoleList(), 6) || isZbRole(userVO.getRoleList(), 10)
				|| isZbRole(userVO.getRoleList(), 13))) {
			WmScorePackage query = new WmScorePackage();
			query.setDeptId(userVO.getDeptId() + "");
			query.setTypeid("4");
			query.setScorePackageName(packageName);
			query.setBelongDate(selDate);
			query.setZbId(userVO.getUserId() + "");
//			query.setPackageType2(packageType2);

//			scorePage = wmScorePackageService.page(page, scoreQuery);
			scorePage = wmScorePackageService.getPackageListForReceive(page, query);
			scorePackageList = scorePage.getRecords();

			for (WmScorePackageApiOutput item : scorePackageList) {
//				Map<String, Object> map = new HashMap<>();
//				map.put("id", item.getId());
//				map.put("packageName", item.getScorePackageName());
//				map.put("score", item.getScore());
//				map.put("packageEntName", item.getPackageEntName());
//				map.put("userNum", item.getUserNum());
				WmScorePackageStatus queryGetUser = new WmScorePackageStatus();
				queryGetUser.setPackageId(item.getId());
				queryGetUser.setStatus("2");
				queryGetUser.setDelFlag("0");
				queryGetUser.setEnableFlag("0");
				item.setUserGetNum(wmScorePackageStatusService.count(Wrappers.query(queryGetUser)));

				if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(item.getPackageType1()) && item.getScore() != null) {
					// 如果是患者教育，则转换积分 '分'->'元'
					item.setScore(String.format("%.2f", Integer.parseInt(item.getScore()) / 100.0));
				}

//				map.put("taskNum", item.getTaskNum());
//				map.put("createTime", item.getCreateTime());
//				map.put("description", item.getDescription());
//				map.put("packageType1", item.getPackageType1());
//				if ("1".equals(item.getPackageType1())) {
//					map.put("type1", "定额");
//				} else if ("2".equals(item.getPackageType1())) {
//					map.put("type1", "定量");
//				} else if ("3".equals(item.getPackageType1())) {
//					map.put("type1", "通用");
//				}

//				resultList.add(map);
			}
//			scorePage.setRecords(resultList);
			return R.ok(scorePage);
		}

//		WmScorePackageStatus status = new WmScorePackageStatus();
//		status.setDeptId(userVO.getDeptId() + "");
//		status.setUserId(userVO.getUserId() + "");
//		LambdaQueryWrapper<WmScorePackageStatus> statusQuery = Wrappers.lambdaQuery(status);

		if (2 == selType) {
			WmScorePackageApiInput input = new WmScorePackageApiInput();
			input.setScorePackageName(packageName);
			input.setSelDate(selDate);
			input.setUserId(userVO.getUserId() + "");
//			input.setPackageType2(packageType2);
			if (isZbRole(userVO.getRoleList(), 5)) {
				input.setTypeid("3");

				if ("2".equals(activeId)) {
					input.setTaskAddFlag("1");
					input.setStatus("2");
				} else if ("3".equals(activeId)) {
					return R.ok();
				} else if ("4".equals(activeId)) {
					input.setStatus("2");
					input.setTaskAddFlag("0");
				}
			} else if (isZbRole(userVO.getRoleList(), 6) || isZbRole(userVO.getRoleList(), 10)
					|| isZbRole(userVO.getRoleList(), 13)) {
				// 小程序角色:5-全职学术信息沟通专员, 6-兼职学术信息沟通专员, 10-兼职CRC, 13-HCP
				input.setTypeid("4");

				if ("2".equals(activeId)) {
					input.setTaskAddFlag("1");
					input.setStatus("2");
				} else if ("3".equals(activeId)) {
					input.setTaskAddFlag("1");
					input.setStatus("1");
				} else if ("4".equals(activeId)) {
					input.setStatus("2");
					input.setTaskAddFlag("0");
				}
			} else {
				return R.ok();
			}
//			if(inFlag){
//				List<WmScorePackage> inList =  wmScorePackageService.list(scoreQuery);
//				List<String> ids = inList.stream().map(WmScorePackage::getId).collect(Collectors.toList());
//				System.err.println("-----"+inList.size());
//				if (CollectionUtils.isNotEmpty(ids)) {
//					statusQuery.in(WmScorePackageStatus::getPackageId,ids);
//				}else {
//					statusQuery.eq(WmScorePackageStatus::getPackageId,"-1");
//				}
//			}


			scorePage = wmScorePackageStatusService.getReceivedPackageList(page, input);

			scorePackageList = scorePage.getRecords();
			if (CollectionUtils.isNotEmpty(scorePackageList)) {
//				Map<String, Object> map = new HashMap<>();
				for (WmScorePackageApiOutput item : scorePackageList) {
//					WmScorePackage item = wmScorePackageService.getById(status1.getPackageId());
//					map.put("id", item.getId());
//					map.put("packageName", item.getScorePackageName());
//					map.put("score", item.getScore());
////					map.put("packageEntName", sysDeptService.getById(item.getSendPackageDeptId()).getName());
//					map.put("packageEntName", item.getPackageEntName());
//					map.put("userNum", item.getUserNum());
//					map.put("taskNum", item.getTaskNum());
//					map.put("createTime", item.getCreateTime());
//					map.put("description", item.getDescription());
//					map.put("packageType1", item.getPackageType1());

//					if ("1".equals(item.getStatus())) {
//						item.setStatusLabel("审核中");
//					} else if ("2".equals(item.getStatus())) {
//						item.setStatusLabel("审核通过");
//					} else if ("3".equals(item.getStatus())) {
//						item.setStatusLabel("审核不通过");
//					}
//					if (!"0".equals(item.getEnableType())) {
//						item.setStatusLabel("已终止");
//					}
//					map.put("taskAddFlag", item.getTaskAddFlag());

					WmScorePackageStatus queryGetUser = new WmScorePackageStatus();
					queryGetUser.setPackageId(item.getId());
					queryGetUser.setStatus("2");
					queryGetUser.setDelFlag("0");
					queryGetUser.setEnableFlag("0");
					item.setUserGetNum(wmScorePackageStatusService.count(Wrappers.query(queryGetUser)));

					if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val()
							.equals(item.getPackageType1()) && item.getScore() != null) {
						// 如果是患者教育，则转换积分 '分'->'元'
						item.setScore(String.format("%.2f", Integer.parseInt(item.getScore()) / 100.0));
					}

					WmTask wmTask = new WmTask();
					wmTask.setScorePackageId(item.getId());
					wmTask.setTaskUserId(userVO.getUserId() + "");
					wmTask.setRealFlag("0");
					List<WmTask> wmTaskList = wmTaskService.list(Wrappers.query(wmTask)
							.lambda()
							.eq(WmTask::getRealFlag, "0")
							.eq(WmTask::getDelFlag, DelEnum.NOT_DEL.val())
							.ne(WmTask::getTaskStatus, "4"));
//							.ne(WmTask::getRealFlag, "1").ne(WmTask::getTaskStatus, "4"));

//					map.put("taskFinishNum", wmTaskList.size());
//					map.put("speedProgress", "0");
					item.setTaskFinishNum(wmTaskList.size());
					item.setSpeedProgress(0);
					item.setFinishScore(0);
					item.setWaitApprovalScore(0);
					item.setWaitApprovalTaskNum(0);
					if ("3".equals(item.getStatus())) {
						item.setTaskAddFlag("1");
						continue;
					}

					if ("1".equals(item.getPackageType1())) {
						Integer finishScore = 0;
						Integer waitApprovalScore = 0;
						for (WmTask task : wmTaskList) {
							finishScore += task.getScore();
							if ("2".equals(task.getTaskStatus())) {
								waitApprovalScore += task.getScore();
							}
						}
						item.setFinishScore(finishScore);
						item.setWaitApprovalScore(waitApprovalScore);
						if (StringUtils.isNumeric(item.getScore()) && Integer.parseInt(item.getScore()) > 0) {
							double d = Math.ceil(finishScore * 100 / Integer.parseInt(item.getScore()));
							if (d > 100) {
								d = 100;
							}
//							map.put("speedProgress", new Double(d).intValue());
							item.setSpeedProgress(new Double(d).intValue());
						}
					} else {
//					} else if ("2".equals(item.getPackageType1())) {
						Integer waitApprovalTaskNum = 0;
						double d = Math.ceil(wmTaskList.size() * 100 / item.getTaskNum());
						if (d > 100) {
							d = 100;
						}
						for (WmTask task : wmTaskList) {
							if ("2".equals(task.getTaskStatus())) {
								waitApprovalTaskNum++;
							}
						}
						item.setWaitApprovalTaskNum(waitApprovalTaskNum);
//						map.put("speedProgress", new Double(d).intValue());
						item.setSpeedProgress(new Double(d).intValue());
					}

//					resultList.add(map);

				}
			}
//			scorePage.setRecords(resultList);
			return R.ok(scorePage);

		}

		return R.ok();

	}


//	/**
//	 * 获取用户积分包
//	 *
//	 * @return 获取用户积分包
//	 */
//	@ApiOperation(value = "积分包-获取用户积分包", notes = "积分包-获取用户积分包，selType  众包用户传值，1 可领取  2 已领取")
//	@GetMapping("/getUserScorePackageList")
//	public R getUserScorePackageList(Page page, int selType, String taskTypeId, String selDate, String packagename, String activeId) {
//
//		if (!"null".equals(selDate) || !"".equals(selDate)) {
//			selDate = null;
//		}
//		boolean isRule = false;
//
//		List<Map<String, Object>> answerList = new ArrayList<>();
//
//		UserVO userVO1 = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
//
//		Page scorePage = null;
//		WmScorePackage wmScorePackage = new WmScorePackage();
//		if (isZbRole(userVO1.getRoleList(), 5)) {
//			if (1 == selType) {
//				return R.ok();
//			}
//		}
//
//		if (null != selDate && !"".equals(selDate) || null != taskTypeId && !"".equals(taskTypeId)) {
//			WmTaskRule qwmTaskRule = new WmTaskRule();
//			qwmTaskRule.setDrugentId(userVO1.getDrugEntId());
//			qwmTaskRule.setDelFlag("0");
//
//			if (null == selDate || "".equals(selDate)) {
//				qwmTaskRule.setRuleMonth(taskTypeId);
//
//			} else {
//				qwmTaskRule.setRuleMonth(selDate);
//			}
//			List<WmTaskRule> listWmTaskRule = wmTaskRuleService.list(Wrappers.query(qwmTaskRule));
//			if (listWmTaskRule.size() > 0) {
//				wmScorePackage.setTaskRuleId(listWmTaskRule.get(0).getId());
//			} else {
//				wmScorePackage.setTaskRuleId("-1");
//				isRule = true;
//
//			}
//		}
//
//
//		wmScorePackage.setDeptId(userVO1.getDeptId() + "");
//		LambdaQueryWrapper<WmScorePackage> queryWrapper = Wrappers.query(wmScorePackage).lambda().
//				orderByAsc(WmScorePackage::getPackageStatus).orderByDesc(WmScorePackage::getCreateTime);
//		if (StringUtils.isNotEmpty(packagename)) {
//			queryWrapper.like(WmScorePackage::getScoreName, packagename);
//		}
//
//		if (isZbRole(userVO1.getRoleList(), 5)) {
//
//			if (2 == selType && StringUtils.isNotEmpty(activeId)) {
//				if ("2".equals(activeId)) {
//					queryWrapper.eq(WmScorePackage::getPackageStatus, "2");
//					queryWrapper.eq(WmScorePackage::getPackageFinishStatus, "0");
//				} else if ("4".equals(activeId)) {
//					queryWrapper.eq(WmScorePackage::getPackageStatus, "2");
//					queryWrapper.eq(WmScorePackage::getPackageFinishStatus, "1");
//				}
//			}
//
//			wmScorePackage.setTypeid("3");
//			wmScorePackage.setXxdbId(userVO1.getUserId() + "");
//			scorePage = wmScorePackageService.page(page, queryWrapper);
//		}
//
//
//		List<WmScorePackage> type2List = new ArrayList<>();
//
//		if (isZbRole(userVO1.getRoleList(), 6)) {
//			wmScorePackage.setTypeid("4");
//			if (1 == selType) {
//				wmScorePackage.setZbId("");
//				queryWrapper = queryWrapper.isNull(WmScorePackage::getPackageStatus);
//				wmScorePackage.setDeptId(userVO1.getDeptId() + "");
//
//				scorePage = wmScorePackageService.page(page, queryWrapper);
//
//			} else {
//				if (StringUtils.isNotEmpty(activeId) && "2".equals(activeId)) {
//					wmScorePackage.setZbId(userVO1.getUserId() + "");
//					wmScorePackage.setPackageStatus("2");
//					wmScorePackage.setPackageFinishStatus("0");
//					scorePage = wmScorePackageService.page(page, queryWrapper);
//
//				} else if (StringUtils.isNotEmpty(activeId) && "4".equals(activeId)) {
//					wmScorePackage.setZbId(userVO1.getUserId() + "");
//					wmScorePackage.setPackageStatus("2");
//					wmScorePackage.setPackageFinishStatus("1");
//					scorePage = wmScorePackageService.page(page, queryWrapper);
//
//				} else {
//					WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
//					if (isRule) {
//						wmScorePackageStatus.setId(-1);
//					}
//
//					LambdaQueryWrapper<WmScorePackageStatus> wmScorePackageStatusLambdaQueryWrapper = Wrappers.query(wmScorePackageStatus).lambda();
//					if (null != packagename && !"".equals(packagename)) {
//						LambdaQueryWrapper<WmScorePackage> lambdaQueryWrapper = Wrappers.lambdaQuery();
//						lambdaQueryWrapper.like(WmScorePackage::getScoreName, packagename);
//
//						List<WmScorePackage> list = wmScorePackageService.list(lambdaQueryWrapper);
//						List<String> list1 = new ArrayList<>();
//						if (list.size() > 0) {
//							for (WmScorePackage wmScorePackage1 : list) {
//								list1.add(wmScorePackage1.getId());
//							}
//						} else {
//							list1.add("-1");
//						}
//						wmScorePackageStatusLambdaQueryWrapper.in(WmScorePackageStatus::getPackageId, list1);
//					}
//
//					if (null != selDate && !"".equals(selDate) || null != taskTypeId && !"".equals(taskTypeId)) {
//						String dateStr = "";
//						if (null != selDate && !"".equals(selDate)) {
//							dateStr = selDate;
//
//						} else {
//							dateStr = taskTypeId;
//
//						}
//
//						wmScorePackageStatusLambdaQueryWrapper.ge(WmScorePackageStatus::getCreateTime, getLocalDateTime(dateStr, "start"));
//						wmScorePackageStatusLambdaQueryWrapper.le(WmScorePackageStatus::getCreateTime, getLocalDateTime(dateStr, "end"));
//					}
//
//					if (StringUtils.isNotEmpty(activeId) && "3".equals(activeId)) {
//						wmScorePackageStatusLambdaQueryWrapper.eq(WmScorePackageStatus::getStatus, "1");
//
//					}
//
//					wmScorePackageStatusLambdaQueryWrapper.orderByDesc(WmScorePackageStatus::getCreateTime);
//					wmScorePackageStatus.setUserId(userVO1.getUserId() + "");
//					scorePage = wmScorePackageStatusService.page(page, wmScorePackageStatusLambdaQueryWrapper);
//					List<WmScorePackageStatus> statusList = scorePage.getRecords();
//
//					List<String> stringList = new ArrayList<>();
//
//					if (statusList.size() > 0) {
//						for (WmScorePackageStatus wmScorePackageStatus1 : statusList) {
//							stringList.add(wmScorePackageStatus1.getPackageId());
//						}
//					}
//
//					if (stringList.size() > 0) {
//						for (String str1 : stringList) {
//							WmScorePackage wmScorePackage1 = wmScorePackageService.getById(str1);
//							if (null != wmScorePackage1) {
//								type2List.add(wmScorePackage1);
//							}
//						}
//					} else {
//						wmScorePackage.setZbId(SecurityUtils.getUser().getId() + "");
//					}
//				}
//
//			}
//		}
//
//		//获取积分包配置
//
//		List<WmScorePackage> list = new ArrayList<>();
//		if (isZbRole(userVO1.getRoleList(), 5)) {
//			list = scorePage.getRecords();
//		} else {
//			if (1 == selType) {
//				list = scorePage.getRecords();
//			} else {
//				if (StringUtils.isNotEmpty(activeId) && "2".equals(activeId)) {
//					list = scorePage.getRecords();
//
//				} else if (StringUtils.isNotEmpty(activeId) && "4".equals(activeId)) {
//
//					list = scorePage.getRecords();
//				} else {
//					list = type2List;
//				}
//
//			}
//		}
//
//
//		System.out.println("list:" + list.size());
//		if (list.size() > 0) {
//			List<String> notInStatus = new ArrayList<>();
//			notInStatus.add("1000000000");
//			for (WmScorePackage wms : list) {
//				Map<String, Object> map = new HashMap<>();
//				WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(wms.getDrugEntId());
//				if (null != wmDaDrugEnt) {
//					map.put("drugEntName", wmDaDrugEnt.getEntname());
//				} else {
//					map.put("drugEntName", "");
//				}
//
//				if (null != wms.getLevel2Id() && !"".equals(wms.getLevel2Id())) {
//					WmDaAgent wmDaAgent = wmDaAgentService.getById(wms.getLevel2Id());
//					map.put("packageEntName", wmDaAgent.getGsmc());
//				} else {
//					if (null != wms.getLevel1Id() && !"".equals(wms.getLevel1Id())) {
//						WmDaAgent wmDaAgent = wmDaAgentService.getById(wms.getLevel1Id());
//						map.put("packageEntName", wmDaAgent.getGsmc());
//					} else {
//						map.put("packageEntName", wmDaDrugEnt.getEntname());
//					}
//				}
//				if (null != wms.getTaskRuleId()) {
//					WmTaskRule wmTaskRule = wmTaskRuleService.getById(wms.getTaskRuleId());
//					if (null != wmTaskRule) {
//						map.put("termDate", wmTaskRule.getRuleMonth() + "-01 至 " + wmTaskRule.getRuleMonth() + "-30");
//						DateFormat format = new SimpleDateFormat("yyyy-MM");
//						DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//
//						try {
//							Date adata = format.parse(wmTaskRule.getRuleMonth());
//							// 获取Calendar
//							Calendar calendar = Calendar.getInstance();
//							// 设置时间,当前时间不用设置
//							calendar.setTime(adata);
//							// 设置日期为本月最大日期
//							calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
//
//							// 打印
//							String endDate = format1.format(calendar.getTime());
//							if (null != endDate) {
//								map.put("termDate", wmTaskRule.getRuleMonth() + "-01 至 " + endDate);
//							}
//
//						} catch (ParseException e) {
//							e.printStackTrace();
//						}
//
//					}
//				}
//
//				map.put("packageName", wms.getScoreName());
//				map.put("socre", wms.getScore());
//				map.put("createTime", wms.getCreateTime());
//				map.put("id", wms.getId());
//				map.put("finishScore", "0");
//				map.put("submitScore", "0");
//				map.put("cannelAuditScore", "0");
//				map.put("speedProgress", "0");
//
//
//				WmTask wmTask = new WmTask();
//				wmTask.setDelFlag("0");
//				wmTask.setEnableFlag("0");
//				wmTask.setScorePackageId(wms.getId());
//				/**
//				 * TODO 审核不通过的分数 不计入积分包
//				 * .ne(WmTask::getRealFlag,"1")
//				 */
//				List<WmTask> wmTaskList = wmTaskService.
//						list(Wrappers.query(wmTask).lambda().ne(WmTask::getRealFlag, "1"));
//				if (wmTaskList.size() > 0) {
//					Integer submitScore = 0;
//					Integer finishScore = 0;
//					Integer cannelAuditScore = 0;
//					for (WmTask wmT : wmTaskList
//					) {
//						if ("4".equals(wmT.getTaskStatus())) {
//							cannelAuditScore += wmT.getScore();
//						} else {
//							submitScore += wmT.getScore();
//						}
//						finishScore += wmT.getScore();
//					}
//
//					map.put("finishScore", finishScore + "");
//					map.put("submitScore", submitScore + "");
//					if (wms.getScore() > 0) {
//						double d = Math.ceil(submitScore * 100 / wms.getScore());
//						if (d > 100) {
//							d = 100;
//						}
//						map.put("speedProgress", new Double(d).intValue());
//
//					}
//					map.put("cannelAuditScore", cannelAuditScore + "");
//				}
//
//				if (isZbRole(userVO1.getRoleList(), 5)) {
//					if ("4".equals(wms.getPackageStatus())) {
//						map.put("status", "已终止");
//						map.put("statusId", "4");
//					} else {
//						map.put("status", "已领取");
//					}
//				}
//
//
//				if (SecurityUtils.getRoles().contains(6)) {
//					if (1 == selType) {
//						map.put("status", "未领取");
//						map.put("statusId", 0);
//					} else {
//						WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
//						wmScorePackageStatus.setPackageId(wms.getId());
//						wmScorePackageStatus.setUserId(userVO1.getUserId() + "");
//						List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(Wrappers.query(wmScorePackageStatus).lambda().notIn(true, WmScorePackageStatus::getId, notInStatus).orderByDesc(WmScorePackageStatus::getCreateTime));
//						if (statusList.size() > 0) {
//							notInStatus.add(statusList.get(0).getId() + "");
//							if ("1".equals(statusList.get(0).getStatus())) {
//								map.put("status", "审核中");
//								map.put("statusId", 1);
//							} else if ("2".equals(statusList.get(0).getStatus())) {
//								map.put("status", "审核通过");
//								map.put("statusId", 2);
//							} else if ("3".equals(statusList.get(0).getStatus())) {
//								map.put("status", "审核不通过");
//								map.put("statusId", 3);
//							} else if ("3".equals(statusList.get(0).getStatus())) {
//								map.put("status", "审核不通过");
//								map.put("statusId", 3);
//							}
//
//							map.put("statusId", statusList.get(0).getStatus());
//
//							if ("4".equals(wms.getPackageStatus())) {
//								map.put("status", "已终止");
//								map.put("statusId", "4");
//
//							}
//						}
//						//map.put("status","审核通过");
//						//map.put("statusId",2);
//					}
//				}
//				map.put("packageFinishStatus", wms.getPackageFinishStatus());
//				answerList.add(map);
//			}
//		}
//		scorePage.setRecords(answerList);
//		return R.ok(scorePage);
//
//	}


	/**
	 * 通过id查询积分包
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "积分包-", notes = "通过id查询")
	@GetMapping("/getScorePackageInfoById")
	public R getScorePackageInfoById(String id) {
		WmScorePackage wms = wmScorePackageService.getById(id);
		Map<String, Object> map = new HashMap<>();
//		WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.getById(wms.getDrugEntId());
//		map.put("drugEntId", wmDaDrugEnt.getId());
//		if (null != wmDaDrugEnt) {
//			map.put("drugEntName", wmDaDrugEnt.getEntname());
//		} else {
//			map.put("drugEntName", "");
//		}
//
//		if (null != wms.getLevel2Id() && !"".equals(wms.getLevel2Id())) {
//			WmDaAgent wmDaAgent = wmDaAgentService.getById(wms.getLevel2Id());
//			map.put("packageEntName", wmDaAgent.getGsmc());
//			map.put("packageEntId", wmDaAgent.getId());
//
//		} else {
//			if (null != wms.getLevel1Id() && !"".equals(wms.getLevel1Id())) {
//				WmDaAgent wmDaAgent = wmDaAgentService.getById(wms.getLevel1Id());
//				map.put("packageEntName", wmDaAgent.getGsmc());
//				map.put("packageEntId", wmDaAgent.getId());
//
//			} else {
//				map.put("packageEntName", wmDaDrugEnt.getEntname());
//				map.put("packageEntId", wmDaDrugEnt.getId());
//
//			}
//		}

		SysDept dept = sysDeptService.getById(wms.getSendPackageDeptId());
		map.put("packageEntName", dept.getName());
		map.put("packageEntId", dept.getDeptId());

//		if (null != wms.getTaskRuleId()) {
//			WmTaskRule wmTaskRule = wmTaskRuleService.getById(wms.getTaskRuleId());
//			if (null != wmTaskRule) {
//				map.put("termDate", wmTaskRule.getRuleMonth() + "-01 至 " + wmTaskRule.getRuleMonth() + "-30");
//				DateFormat format = new SimpleDateFormat("yyyy-MM");
//				DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//
//				try {
//					Date adata = format.parse(wmTaskRule.getRuleMonth());
//					// 获取Calendar
//					Calendar calendar = Calendar.getInstance();
//					// 设置时间,当前时间不用设置
//					calendar.setTime(adata);
//					// 设置日期为本月最大日期
//					calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
//
//					// 打印
//					String endDate = format1.format(calendar.getTime());
//					if (null != endDate) {
//						map.put("termDate", wmTaskRule.getRuleMonth() + "-01 至 " + endDate);
//					}
//
//				} catch (ParseException e) {
//					e.printStackTrace();
//				}
//
//			}
//		}
		if (StringUtils.isNotEmpty(wms.getBelongDate())) {
			map.put("termDate", wms.getBelongDate() + "-01 至 " + wms.getBelongDate() + "-30");
			DateFormat format = new SimpleDateFormat("yyyy-MM");
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

			try {
				Date adata = format.parse(wms.getBelongDate());
				// 获取Calendar
				Calendar calendar = Calendar.getInstance();
				// 设置时间,当前时间不用设置
				calendar.setTime(adata);
				// 设置日期为本月最大日期
				calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

				// 打印
				String endDate = format1.format(calendar.getTime());
				if (null != endDate) {
					map.put("termDate", wms.getBelongDate() + "-01 至 " + endDate);
				}

			} catch (ParseException e) {
				e.printStackTrace();
			}

		}
		map.put("status", wms.getPackageStatus());
		map.put("packageName", wms.getScorePackageName());
//		map.put("packageName", wms.getScoreName());
		if (PackageTypeEnum.TYPE1_HCP_PACKAGE.val().equals(wms.getPackageType1())) {
			// 如果是患者教育，则需要转换积分包单位 ‘分’->‘元’
			map.put("score", String.format("%.2f", wms.getScore() / 100.0) + "分");
		} else {
			map.put("score", wms.getScore() + "分");
		}
		map.put("userNum", wms.getUserNum());
		map.put("taskNum", wms.getTaskNum() + "个");
		map.put("createTime", wms.getCreateTime());
		map.put("packageType1", wms.getPackageType1());
		map.put("id", wms.getId());
		map.put("finishScore", "0");
//		map.put("packageFinishStatus", wms.getPackageFinishStatus()+"");

		WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
		wmScorePackageStatus.setUserId(SecurityUtils.getUser().getId() + "");
		wmScorePackageStatus.setPackageId(id);
		wmScorePackageStatus.setDelFlag("0");
		wmScorePackageStatus.setEnableFlag("0");
		List<WmScorePackageStatus> statusList = wmScorePackageStatusService.
				list(Wrappers.query(wmScorePackageStatus).lambda().ne(WmScorePackageStatus::getStatus, "3"));

		if (CollectionUtils.isNotEmpty(statusList)) {
			map.put("receiveFlag", 0);
		} else {
			map.put("receiveFlag", 1);
		}

		/**
		 * 判断是否可导出任务明细
		 */
		WmTask wmTask = new WmTask();
//		List<String> list = new ArrayList<>();
//		list.add(id);
//		wmTask.setExtIds(list);
		wmTask.setScorePackageId(id);
		wmTask.setTaskStatus("3");
//		List<WmTask> wmTaskList = wmTaskService.list(Wrappers.query(wmTask));
		int count = wmTaskService.count(Wrappers.query(wmTask));
//		List<WmTask> wmTaskList = wmTaskService.getTaskListByPackageIdsReturnWmtaskInfo(wmTask);
		if (count > 0) {
			map.put("exportFlag", "1");
		} else {
			map.put("exportFlag", "0");
		}
		map.put("email", redisTemplate.opsForValue()
				.get(CacheConstants.EMAIL_KEY + SecurityUtils.getUser().getPlatId()));

		if ("1".equals(wms.getEnableFlag())) {
			map.put("receiveFlag", 0);
		}
		if (!"0".equals(wms.getEnableType())) {
			map.put("receiveFlag", 0);
		}

		return R.ok(map);
	}


	/**
	 * 通过id查询积分包
	 *
	 * @param packageId
	 * @return R
	 */
	@ApiOperation(value = "积分包-领取", notes = "积分包-领取")
	@GetMapping("/receivePackage")
	public R receivePackage(String packageId) {
		WmScorePackage wmScorePackage = wmScorePackageService.getById(packageId);
		if (null == wmScorePackage) {
			return R.failed("积分包不存在");
		}

		if ("1".equals(wmScorePackage.getEnableFlag())) {
			return R.failed("积分包已终止，不能领取");
		}

		if (!"0".equals(wmScorePackage.getEnableType())) {
			return R.failed("积分包剩余积分值已收回，不能领取");
		}

		if ("1".equals(wmScorePackage.getIsReceive())) {
			return R.failed("积分包不能领取");
		}

//		UserDTO userDTO = new UserDTO();
//		userDTO.setPlatId(SecurityUtils.getUser().getPlatId());
//		userDTO.setDrugEntId(wmScorePackage.getDrugEntId());
		UserVO userVO = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
//		List<UserVO> userVOList = sysUserService.getUserVoByPlatId(userDTO);
		if (null == userVO) {
			return R.failed("账号出错");
		}
		if (isZbRole(userVO.getRoleList(), 5)) {
			return R.failed("全职学术推广员不能领取积分包");
		}

		WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
		wmScorePackageStatus.setPackageId(packageId);
		wmScorePackageStatus.setUserId(userVO.getUserId() + "");
		wmScorePackageStatus.setDelFlag("0");
		wmScorePackageStatus.setEnableFlag("0");
		List<WmScorePackageStatus> wmScorePackageStatusList = wmScorePackageStatusService.
				list(Wrappers.query(wmScorePackageStatus).lambda().ne(WmScorePackageStatus::getStatus, 3));
		if (wmScorePackageStatusList.size() > 0) {
			return R.failed("积分包已领取");
		}

		wmScorePackageStatus.setStatus("1");
		wmScorePackageStatus.setTaskAddFlag("1");
		if ("1".equals(wmScorePackage.getPackageType1())) {
			wmScorePackageStatus.setUserScore(wmScorePackage.getScore() + "");
		} else {
			wmScorePackageStatus.setUserScore(wmScorePackage.getUserScore());
		}
		wmScorePackageStatus.setTaskNum(wmScorePackage.getTaskNum());
		wmScorePackageStatus.setDeptId(userVO.getDeptId() + "");
		LocalDateTime localDateTime = LocalDateTime.now();
		wmScorePackageStatus.setCreateTime(localDateTime);
		wmScorePackageStatus.setUpdateTime(localDateTime);
		wmScorePackageStatusService.save(wmScorePackageStatus);

		WmScorePackageStatus query = new WmScorePackageStatus();
		query.setPackageId(packageId);
		query.setStatus("1");
		query.setDelFlag("0");
		query.setEnableFlag("0");
		int total = wmScorePackageStatusService.count(Wrappers.query(query));
		/**
		 * 显示用的
		 */
		if (total == 1) {
			WmScorePackage update = new WmScorePackage();
			update.setId(wmScorePackage.getId());
			update.setScorePackageStatus("2");
//			wmScorePackage.setPackageStatus("1");
			update.setIsConduct("1");
			wmScorePackageService.updateById(update);
		}

		return R.ok();

	}

	/**
	 * 根据积分包获取任务列表
	 *
	 * @return 根据积分包获取任务列表
	 */
	@ApiOperation(value = "根据积分包获取任务列表", notes = "根据积分包获取任务列表")
	@GetMapping("/getTaskListByPackageId")
	public R getTaskListByPackageId(Page page, WmTask wmTask) {

		Page<WmTask> taskPage = wmTaskService.page(page,
				Wrappers.<WmTask>lambdaQuery()
						.eq(WmTask::getScorePackageId, wmTask.getScorePackageId())
						.eq(WmTask::getTaskUserId, wmTask.getTaskUserId())
						.ne(WmTask::getScore, 0)
						.eq(WmTask::getRealFlag, "0")
						.eq(WmTask::getDelFlag, DelEnum.NOT_DEL.val())
						.orderByDesc(WmTask::getCreateTime));

		List<WmTask> wmTaskList = taskPage.getRecords();

		List<WmTaskType> wmTaskTypeList = wmTaskTypeService.
				list(Wrappers.<WmTaskType>lambdaQuery().eq(WmTaskType::getTaskTypeLevel, "1"));

		Map<String, String> typeMap = wmTaskTypeList.stream()
				.collect(Collectors.toMap(WmTaskType::getId, WmTaskType::getTaskTypeName));

		for (int i = 0; i < wmTaskList.size(); i++) {
			wmTaskList.get(i).setTaskTypeId(typeMap.get(wmTaskList.get(i).getTaskTypeId()));
		}
		taskPage.setRecords(wmTaskList);

		return R.ok(taskPage);
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@ApiOperation(value = "任务-我的任务记录列表", notes = "任务-我的任务记录列表")
	@GetMapping("/getHistoryTaskList")
	public R getHistoryTaskList(Page page, WmTask wmTask) {
		wmTask.setEnableFlag("0");
		wmTask.setDelFlag("0");
		UserDTO userDTO = new UserDTO();
		userDTO.setPlatId(SecurityUtils.getUser().getPlatId());
		List<UserVO> userVOList = sysUserService.getUserVoByPlatId(userDTO);
		Page<WmTask> taskPage = null;
		LambdaQueryWrapper<WmTask> queryWrapper = Wrappers.lambdaQuery();

		int num = 0;
		int allnum = 0;
		for (UserVO userVO : userVOList) {

			if (null != wmTask.getTaskRuleId() && !"".equals(wmTask.getTaskRuleId())) {
				WmTaskRule wmTaskRule = new WmTaskRule();
				wmTaskRule.setRuleMonth(wmTask.getTaskRuleId());
				wmTaskRule.setDrugentId(userVO.getDrugEntId());
				List<WmTaskRule> wmTaskRuleList = wmTaskRuleService.list(Wrappers.query(wmTaskRule));
				if (wmTaskRuleList.size() > 0) {
					if (num == 0) {
						queryWrapper.and(
								Wrapper -> Wrapper.eq(WmTask::getTaskRuleId, wmTaskRuleList.get(0).getId() + "")
										.eq(WmTask::getTaskUserId, userVO.getUserId() + "")
						);
					} else {
						queryWrapper.or(
								Wrapper -> Wrapper.eq(WmTask::getTaskRuleId, wmTaskRuleList.get(0).getId() + "")
										.eq(WmTask::getTaskUserId, userVO.getUserId() + "")
						);
					}

				} else {
					queryWrapper.eq(WmTask::getTaskRuleId, "-100");
				}
				num++;


//				queryWrapper.ge(WmTask::getCreateTime,getLocalDateTime(wmTask.getTaskRuleId(),"start"));
//				queryWrapper.le(WmTask::getCreateTime,getLocalDateTime(wmTask.getTaskRuleId(),"end"));

			} else {
				if (allnum == 0) {
					queryWrapper.and(Wrapper -> Wrapper.eq(WmTask::getTaskUserId, userVO.getUserId()));
				} else {
					queryWrapper.or(Wrapper -> Wrapper.eq(WmTask::getTaskUserId, userVO.getUserId()));
				}
				allnum++;

			}
		}

		queryWrapper.ne(WmTask::getScore, 0);
		queryWrapper.orderByDesc(WmTask::getCreateTime);
		taskPage = wmTaskService.page(page, queryWrapper);
		List<WmTask> wmTaskList = taskPage.getRecords();

		for (int i = 0; i < wmTaskList.size(); i++) {
			WmTaskType wmTaskType = wmTaskTypeService.getById(wmTaskList.get(i).getTaskTypeId());
			if (null != wmTaskType) {
				wmTaskList.get(i).setTaskTypeId(wmTaskType.getTaskTypeName());
			}
		}
		taskPage.setRecords(wmTaskList);

		return R.ok(taskPage);
	}


	/**
	 * 新增任务内容表
	 *
	 * @param taskId 任务内容表
	 * @return R
	 */
	@ApiOperation(value = "任务-根据ID获取任务", notes = "任务-根据ID获取任务")
	@SysLog("任务-根据ID获取任务")
	@GetMapping("/getTaskInfoById")
	public R getTaskInfoById(String taskId) {
		Map<String, Object> map = new HashMap<>();
		WmTask wmTask = wmTaskService.getById(taskId);
		if (null != wmTask) {
			map.put("taskType", wmTask.getTaskTypeId());
			WmTaskType wmTaskType = wmTaskTypeService.getById(wmTask.getTaskTypeId());
			map.put("taskInfo", wmTask);
			WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask.getTaskContentId());
			if (null != wmTaskContent) {
				WmScorePackage wmScorePackage = wmScorePackageService.getById(wmTask.getScorePackageId());
				if (null != wmScorePackage) {
					wmTaskContent.setTemp32(wmScorePackage.getScorePackageName());
				}
			}
			map.put("wmTaskContent", wmTaskContent);

			if ("8".equals(wmTask.getTaskTypeId()) || "11".equals(wmTask.getTaskTypeId()) || "9".equals(wmTask.getTaskTypeId()) || "10"
					.equals(wmTask.getTaskTypeId())) {
				map.put("title", "");
				WmWkArticleShare wmWkArticleShare = wmWkArticleShareService.getById(wmTask.getTaskContentId());
				if (null != wmWkArticleShare) {
					if ("8".equals(wmTask.getTaskTypeId()) || "11".equals(wmTask.getTaskTypeId())) {
						WmWkAlbum wmWkAlbum = wmWkAlbumService.getById(wmWkArticleShare.getArctileId());
						map.put("title", wmWkAlbum.getXcmc());
					} else {
						WmWkArticle wmWkArticle = wmWkArticleService.getById(wmWkArticleShare.getArctileId());
						map.put("title", wmWkArticle.getTitle());
					}
				}
				map.put("score", wmTask.getScore());
				map.put("shareId", wmWkArticleShare.getArctileId());

			}

			if (null != wmTaskType) {
				wmTask.setTaskTypeId(wmTaskType.getTaskTypeName());
			}
		}
		return R.ok(map);
	}


	/**
	 * 通过id查询用户签到表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "签到-通过ID获取签到信息", notes = "通过id查询")
	@GetMapping("/getSignInfoByTaskId")
	public R getSignInfoByTaskId(Integer id) {
		WmTask wmTask = wmTaskService.getById(id);
		if (null != wmTask) {
			if (null != wmTask.getTaskContentId()) {
				WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask.getTaskContentId());

				if (null != wmTaskContent) {
					if (null != wmTaskContent.getTemp3()) {
						List<WmUserSign> wmUserSignList = new ArrayList<>();
						wmUserSignList.add(wmUserSignService.getById(wmTaskContent.getTemp3()));
						return R.ok(wmUserSignList);
					}
				}
			}
		}
		return R.ok();
	}

	/**
	 * 新增任务内容表
	 *
	 * @return R
	 */
	@ApiOperation(value = "根据链接生成二维码图片", notes = "根据链接生成二维码图片")
	@GetMapping("/getQrCodeByUrl")
	public R getQrCodeByUrl(String url, int width, int height) throws FileNotFoundException {

		String QR_CODE_IMAGE_PATH = "/" + UUID.randomUUID() + ".png";
		try {
			QRCodeGenerator.generateQRCodeImage(url, width, height, QR_CODE_IMAGE_PATH);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		File imageFile = new File(QR_CODE_IMAGE_PATH);
		FileInputStream in = new FileInputStream(imageFile);
		MultipartFile file = null;
		try {
			file = new MockMultipartFile("file", imageFile.getName(), "text/plain", IOUtils.toByteArray(in));
		} catch (IOException e) {
			e.printStackTrace();
		}

		return R.ok(sysFileService.uploadFile(file));
	}


	/**
	 * 修改用户信息接口
	 *
	 * @return R
	 */
	@ApiOperation(value = "修改用户信息接口", notes = "修改用户信息接口")
	@SysLog("修改用户信息接口")
	@PostMapping("/updateUserInfo")
	public R<?> updateUserInfo(@RequestBody UserUpdateInput userUpdateInput) {

		List<SysUser> list = sysUserService.getUserByPlatId(SecurityUtils.getUser().getPlatId());
		Optional<SysUser> userOptional = list.stream()
				.filter(user -> StringUtils.equals(String.valueOf(user.getUserId()), userUpdateInput.getUserId()))
				.findAny();

		if (!userOptional.isPresent()) {
			return R.failed("只能修改自己的用户信息");
		}

		SysUser sysUser = sysUserService.getById(userUpdateInput.getUserId());

		// 获取更新操作的用户角色
		List<Integer> roles = SecurityUtils.getRoles();

		// 如果角色中包含全职和兼职就需要校验身份证年龄
		if (roles.contains(5) || roles.contains(6)) {
			// 校验身份证上的年龄
			if (StringUtils.isNotEmpty(userUpdateInput.getIdCardNumber())) {
				int ageByIdCard = IdcardUtil.getAgeByIdCard(userUpdateInput.getIdCardNumber());
				if (ageByIdCard < 18) {
					return R.failed("年龄未满十八");
				} else if (ageByIdCard > 65) {
					return R.failed("年龄已超过六十五");
				}
			}
		}

		/**
		 * TODO 小程序的认证
		 * @Modify: start
		 * @Version: v2021.4.16
		 * @Author: ryz
		 * @Date: 2021/4/28
		 */
		boolean updateFlag = true;
		if (null != sysUser.getCertStatus()) {
			if (sysUser.getCertStatus() != 10) {
				updateFlag = false;
			}

		}
		if (null != sysUser.getRljCertStatus()) {
			if (sysUser.getRljCertStatus() == 1 || sysUser.getRljCertStatus() == 3) {
				updateFlag = false;
			}
		}
		if (!updateFlag) {
			if (!userUpdateInput.getRealname().equals(sysUser.getRealname())) {
				return R.failed("用户认证通过或正在认证，暂不能修改姓名");
			}
			if (!userUpdateInput.getIdCardNumber().equals(sysUser.getIdCardNumber())) {
				return R.failed("用户认证通过或正在认证，暂不能修改身份证号");
			}
		}

		SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());

		// 开启认证
		if (CollectionUtils.isNotEmpty(userUpdateInput.getSubList())) {
			for (String subType : userUpdateInput.getSubList()) {

				if (SubjectTypeEnum.TYPE_RENLIJIA.getCode().equals(subType)) {

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

					DingConfig config = new DingConfig();
					config.setAppId(deptSub.getAppId());
					config.setAppSecret(deptSub.getAppSecret());
					config.setQueryUrl(deptSub.getQueryUrl());

					Map map = new HashMap();
					map.put("name", userUpdateInput.getRealname());
					map.put("mobile", sysUser.getPhone());
					map.put("idCard", userUpdateInput.getIdCardNumber());
					map.put("idType", "1");
					List certList = new ArrayList();
					certList.add(map);

					EmployCheckResponse response = dingService.check(config, certList);
					if (!response.isSuccess()) {
						return R.failed("人力家接口调用失败");
					}
					//接口请求成功，但是接口返回的状态还需区分checkStatus，1:验证通过，状态改成已提交，2:验证不通过，状态改成认证失败
					List<EmployCheckResultItem> freelancesResult = response.getData().getFreelancesResult();
					if (CollectionUtils.isNotEmpty(freelancesResult)) {
						for (EmployCheckResultItem employCheckResultItem : freelancesResult) {
							if (employCheckResultItem.getIdCard().equals(userUpdateInput.getIdCardNumber())) {
								if (employCheckResultItem.getCheckStatus() == 1) {//验证通过
									sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
									continue;
								} else {//验证不通过
									if ("1014".equals(employCheckResultItem.getCheckRemark())) {
										log.info("认证返回1014按成功处理：{},{}", sysUser.getRealname(), sysUser.getUsername());
										sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
										continue;
									}
									if ("1018".equals(employCheckResultItem.getCheckRemark())) {
										log.info("认证返回1018按处理中处理：{},{}", sysUser.getRealname(), sysUser.getUsername());
										sysUser.setRljCertStatus(DingEnum.CER_STATUS_3.getType());
										continue;
									}
									if ("1019".equals(employCheckResultItem.getCheckRemark())) {
										log.info("认证返回1019按成功处理：{},{}", sysUser.getRealname(), sysUser.getUsername());
										sysUser.setRljCertStatus(DingEnum.CER_STATUS_1.getType());
										continue;
									}
									if ("1020".equals(employCheckResultItem.getCheckRemark())) {
										log.info("认证返回1020按认证失败处理：{},{}", sysUser.getRealname(), sysUser.getUsername());
										sysUser.setRljCertStatus(DingEnum.CER_STATUS_2.getType());
										continue;
									}
									log.info("认证失败:" + employCheckResultItem.getCheckRemark());
									return R.failed("认证失败:人力家认证失败");
								}
							}
						}
					} else {
						return R.failed("人力家接口调用异常");
					}

				} else if (SubjectTypeEnum.TYPE_SHUIBANGYUN.getCode().equals(subType)) {

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

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

					TaxHelperAddMemberModel model = new TaxHelperAddMemberModel(config);
					model.setIdCard(userUpdateInput.getIdCardNumber());
					model.setType(Integer.parseInt(deptSub.getSubjectUserType()));
					model.setPhone(sysUser.getUsername());
					model.setName(sysUser.getRealname());
					model.setNotifyUrl("http://localhost:8808");

					model.setEnterpriseCode(sysDept.getTaxCode());
					if (StringUtils.isEmpty(model.getEnterpriseCode())) {
						return R.failed("未配置企业的统一社会信用代码");
					}
					TaxHelperAddMemberRequest request = new TaxHelperAddMemberRequest(model);
					TaxHelperResponse response = taxHelperService.addMembers(request);

					// 记录认证结果
					SysCertResultRecord record = new SysCertResultRecord();
					record.setCode(response.getCode());
					record.setCreateTime(LocalDateTime.now());
					record.setDeptId(sysDept.getDeptId());
					record.setMessage(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage() : "无");
					record.setStatus(null);
					record.setSubjectType(1);
					record.setMethod("增员");
					record.setUserId(sysUser.getUserId());
					sysCertResultRecordMapper.insert(record);

					if (response.success()) {
						sysUser.setCertStatus(TaxHelperCertStatus.ADD_MEMBER.getCode());
					} else {
						log.info("税邦云增员失败：{},{}，原因是：{}", sysUser.getRealname(), sysUser.getUsername(), response.getMessage());
						userUpdateInput.setIdCardNumber(null);
						return R.failed("税邦云增员失败");
					}
				}
			}
		}

		sysUser.setAvatar(userUpdateInput.getAvatar());
		if (StringUtils.isNotEmpty(userUpdateInput.getIdCardNumber())) {
			sysUser.setIdCardNumber(userUpdateInput.getIdCardNumber());
		}
		// 姓名去除空格（包括字符之间的所有空格都会去除）
		sysUser.setRealname(StrUtil.cleanBlank(userUpdateInput.getRealname()));
		sysUser.setUserSign(userUpdateInput.getUserSign());
		if (StringUtils.isNotEmpty(userUpdateInput.getTaxHelperAgreementSignature())) {
			sysUser.setTaxHelperAgreementSignature(StringUtils.equals(SignatureStatusEnum.SIGNED.name(), userUpdateInput
					.getTaxHelperAgreementSignature()) ? 1 : 0);
		}
		sysUserService.updateById(sysUser);

		return R.ok();
	}


	/**
	 * 修改意见反馈
	 *
	 * @param wmFeedback 意见反馈
	 * @return R
	 */
	@ApiOperation(value = "修改意见反馈", notes = "修改意见反馈")
	@SysLog("修改意见反馈")
	@PostMapping("/saveFeedBack")
	public R saveFeedBack(@RequestBody WmFeedback wmFeedback) {
		return R.ok(wmFeedbackService.save(wmFeedback));
	}


	/**
	 * 新增任务内容表
	 *
	 * @return R
	 */
	@ApiOperation(value = "分享名片接口", notes = "分享名片接口")
	@SysLog("分享名片接口")
	@GetMapping("/shareUserCard")
	public R shareUserCard(String imgUrl) throws FileNotFoundException {
		int socre = 0;
		SysUser sysUser = sysUserService.getById(SecurityUtils.getUser().getId());

		if (sysUser == sysUser) {
			List<SysUser> listUsers = sysUserService.getUserByPlatId(sysUser.getPlatId());
			if (listUsers.size() > 0) {
				for (SysUser sysU : listUsers) {
					WmWkArticleShare wmWkArticleShare = new WmWkArticleShare();
					wmWkArticleShare.setShareUserid(sysU.getUserId() + "");
					wmWkArticleShare.setShareType("1");
					wmWkArticleShare.setCreateTime(LocalDateTime.now());
					wmWkArticleShare.setArctileId(imgUrl);
					wmWkArticleShareService.save(wmWkArticleShare);


					WmTask wmTask = new WmTask();
					wmTask.setTaskFrom("1");
					wmTask.setTaskUserId(sysU.getUserId() + "");  //任务提交人
					wmTask.setLookintoDate(LocalDateTime.now());       //调研时间
					wmTask.setTaskStatus("1");
					wmTask.setSubmitStatus("0");
					wmTask.setDrugEntId(sysU.getDrugEntId());//任务状态
					wmTask.setTaskTypeId("7");
					wmTask.setShareImgUrl(imgUrl);

					SysDept sysDept = sysDeptService.getById(sysU.getDeptId());
					WmTaskType wmTaskType = new WmTaskType();
					wmTaskType.setDurgentId(sysU.getDrugEntId());
					WmTaskType wmTaskType1 = wmTaskTypeService.getById("7");
					wmTaskType.setTaskTypeName(wmTaskType1.getTaskTypeName());
					wmTaskType.setTaskEntId(sysDept.getLevel2Id() + "");
					socre = wmTaskTypeService.getWmTaskTypeByEnt(wmTaskType);
					System.out.println("获取任务得分：" + socre);
					if (socre < 0) {
						return R.failed("获取任务积分失败");
					}
					wmTask.setScore(socre);

					WmScorePackage wmScorePackage = new WmScorePackage();
					if (SecurityUtils.getRoles().contains(6)) {
						wmScorePackage.setZbId(sysU.getUserId() + "");
					} else {
						wmScorePackage.setXxdbId(sysU.getUserId() + "");
					}

					wmScorePackage.setDrugEntId(sysU.getDrugEntId());
					WmScorePackage tWmScorePackage = wmScorePackageService.getPackageScoreByTaskInfo(wmScorePackage);
					try {
						String packageEntId = wmScorePackageService.getPackageScoreEntByTaskInfo(wmScorePackage);
						wmTask.setScorePackageLevel1Id(packageEntId);
					} catch (Exception ex) {

					}
					System.out.println("获取积分包ID：" + tWmScorePackage);
					if (null == tWmScorePackage) {
						//return R.failed("获取积分包失败");
					} else {
						wmTask.setScorePackageId(tWmScorePackage.getId());
						wmTask.setTaskRuleId(tWmScorePackage.getTaskRuleId());
					}

					wmTask.setTaskContentId(wmWkArticleShare.getId() + "");

					if (SecurityUtils.getRoles().contains(5)) {
						wmTask.setTaskUserType("5");
					}

					wmTask.setCreateTime(LocalDateTime.now());

					if (SecurityUtils.getRoles().contains(6)) {
						wmTask.setTaskUserType("6");
					}

					wmTask.setDeptId(sysU.getDeptId() + "");
					wmTask.setSubmitStatus("0");
					boolean isSave = wmTaskService.save(wmTask);   //保存任务

					//判断任务是否完成
					if (isSave && null != tWmScorePackage) {
						WmScorePackage wmScorePackage1 = wmScorePackageService.getById(tWmScorePackage.getId());
						if (null != wmScorePackage1) {
							WmTask wmTask1 = new WmTask();
							wmTask1.setScorePackageId(tWmScorePackage.getId());
							wmTask1.setDrugEntId(sysU.getDrugEntId());
							List<WmTask> wmTaskList = wmTaskService.list(Wrappers.query(wmTask1));
							int totalCount = 0;
							for (WmTask wmtask : wmTaskList) {
								totalCount += wmtask.getScore();
							}

							if (totalCount >= wmScorePackage1.getScore()) {
								wmScorePackage1.setPackageFinishStatus("1");
							}
							wmScorePackage1.setIsConduct("1");
							wmScorePackageService.updateById(wmScorePackage1);
						}
					} else {
						return R.failed("任务保存失败");
					}
				}
			}
		}
		Map<String, String> map = new HashMap<>();
		map.put("score", socre + "");
		return R.ok(map);
	}

	private boolean isZbRole(List<SysRole> sysRoles, int roleId) {
		for (SysRole sysRole : sysRoles) {
			if (sysRole.getRoleId() == roleId) {
				return true;
			}
		}
		return false;
	}


	private LocalDateTime getLocalDateTime(String monthStr, String type) {
		DateFormat format = new SimpleDateFormat("yyyy-MM");
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

		try {
			Date date1 = format.parse(monthStr);
			Instant instant = date1.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDateTime date = instant.atZone(zoneId).toLocalDateTime();
			LocalDateTime firstday = date.with(TemporalAdjusters.firstDayOfMonth());
			LocalDateTime lastDay = date.with(TemporalAdjusters.lastDayOfMonth())
					.withHour(23)
					.withMinute(59)
					.withSecond(59);

			if ("start".equals(type)) {
				return firstday;
			} else {
				return lastDay;
			}

		} catch (Exception ex) {

		}

		return null;

	}


	/**
	 * 分页查询
	 *
	 * @param page           分页对象
	 * @param wmScorePackage 积分包
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/h5PackagePage")
	public R h5PackagePage(Page page, WmScorePackage wmScorePackage) {
		String id = wmScorePackage.getId();
		if (StringUtils.isBlank(id)) {
			return R.failed("积分包ID不能为空");
		}
		wmScorePackage.setId(null);

		String[] ids = id.split(" +");
		List<String> listIds = new ArrayList<>();
		listIds.addAll(Arrays.asList(ids));
		WmTask wmTask = new WmTask();
		wmTask.setExtIds(listIds);
		return R.ok(wmTaskService.getH5PackageList(page, wmTask));
	}


	/**
	 * 分页查询
	 *
	 * @param page   分页对象
	 * @param wmTask 任务
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/h5TaskPage")
	public R h5TaskPage(Page page, WmTask wmTask) {
		if (StringUtils.isBlank(wmTask.getId())) {
			return R.failed("积分包ID不能为空");
		}

		String id = wmTask.getId();
		wmTask.setId(null);
		wmTask.setScorePackageId(id);
		return R.ok(wmTaskService.getH5TaskList(page, wmTask));
	}


	/**
	 * 分页查询
	 *
	 * @param taskId 积分包
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getH5To")
	public R getH5To(String taskId) {
		WmTask wmTask = wmTaskService.getById(taskId);
		if (null != wmTask) {
			BufferedImage bufferedImage = null;
			try {
				bufferedImage = Html2ImageByJsWrapper.renderHtml2Image(upmsConfig.getApiUrl()
						+ "/h5/#/pages/task/task-detail/index?id=" + wmTask.getId(), upmsConfig.getServerUrl());
			} catch (IOException e) {
				e.printStackTrace();
			}

			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			ImageOutputStream imOut = null;
			try {
				imOut = ImageIO.createImageOutputStream(bs);
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				ImageIO.write(bufferedImage, "png", imOut);
			} catch (IOException e) {
				e.printStackTrace();
			}
			InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
			String path = sysFileService.uploadImgByByte(inputStream);
			wmTask.setTaskInfoImg(path);
			wmTaskService.updateById(wmTask);
		}
		return R.ok();
	}


	/**
	 * @param longitude
	 * @param latitude
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getPointSignInfo")
	public R getPointSignInfo(String longitude, String latitude) {
		List<Map<String, Object>> mapList = new ArrayList<>();

		// 医院
		WmDaHospital qWmDaHospital = new WmDaHospital();
		qWmDaHospital.setLongitude(longitude);
		qWmDaHospital.setLatitude(latitude);

		List<WmDaHospital> wmDaHospitalList = wmDaHospitalService.listByPoint(qWmDaHospital);
		if (wmDaHospitalList.size() > 0) {
			for (WmDaHospital wmDaHospital : wmDaHospitalList) {
				Map<String, Object> map = new HashMap<>();
				map.put("signEntId", wmDaHospital.getId());
				map.put("signEntName", wmDaHospital.getYymc());
				map.put("longitude", wmDaHospital.getLongitude());
				map.put("latitude", wmDaHospital.getLatitude());
				map.put("signEntType", "1");
				mapList.add(map);
			}
		}

		// 商业公司
		WmDaDistribution qwmDaDistribution = new WmDaDistribution();
		qwmDaDistribution.setLatitude(latitude);
		qwmDaDistribution.setLongitude(longitude);

		List<WmDaDistribution> wmDaDistributions = wmDaDistributionService.listByPoint(qwmDaDistribution);
		if (wmDaDistributions.size() > 0) {
			for (WmDaDistribution wmDaDistribution : wmDaDistributions) {
				Map<String, Object> map = new HashMap<>();
				map.put("signEntId", wmDaDistribution.getId());
				map.put("signEntName", wmDaDistribution.getGsmc());
				map.put("longitude", wmDaDistribution.getLongitude());
				map.put("latitude", wmDaDistribution.getLatitude());
				map.put("signEntType", "2");
				mapList.add(map);

			}
		}

		// 药店
		WmDaPharmacy qWmDaPharmacy = new WmDaPharmacy();
		qWmDaPharmacy.setLatitude(latitude);
		qWmDaPharmacy.setLongitude(longitude);
		List<WmDaPharmacy> pharmacyList = wmDaPharmacyService.listByPoint(qWmDaPharmacy);
		if (CollectionUtil.isNotEmpty(pharmacyList)) {
			pharmacyList.forEach(wmDaPharmacy -> {
				Map<String, Object> map = new HashMap<>();
				map.put("signEntId", wmDaPharmacy.getId());
				map.put("signEntName", wmDaPharmacy.getPharmacyName());
				map.put("longitude", wmDaPharmacy.getLongitude());
				map.put("latitude", wmDaPharmacy.getLatitude());
				map.put("signEntType", "3");
				mapList.add(map);
			});
		}

		return R.ok(mapList);
	}

	/**
	 * 小程序去掉通知--不再提示
	 *
	 * @return
	 */
	@ApiOperation(value = "不再提示", notes = "不再提示")
	@SysLog("小程序去掉通知")
	@PostMapping("/removeNotice")
	public R removeNotice(@RequestBody NoticeApiInput input) {
		if (StringUtils.isEmpty(input.getUserId())) {
			return R.failed("参数异常，请求失败");
		}
		if (StringUtils.isEmpty(input.getType())) {
			return R.failed("参数异常，请求失败");
		}
		if ("1".equals(input.getType())) {
			redisTemplate.delete(CacheConstants.USER_NOTICE_KEY + input.getUserId());
		}
		if ("2".equals(input.getType())) {
			redisTemplate.delete(CacheConstants.USER_ADD_NOTICE_KEY + input.getUserId());
		}
		return R.ok();
	}

	/**
	 * 小程序去掉通知--不再提示
	 *
	 * @return
	 */
	@ApiOperation(value = "获取登录人积分包", notes = "获取登录人积分包")
	@SysLog("获取登录人积分包")
	@GetMapping("/getPackageListByTaskType")
	public R getPackageListByTaskType(String type) {
		if (StringUtils.isEmpty(type)) {
			return R.failed("参数异常，请求失败");
		}
		//获取用户基本信息
		if (null == SecurityUtils.getUser().getId()) {
			return R.failed("请求失败");
		}

		SysUser sysUser = sysUserService.getById(SecurityUtils.getUser().getId());

		WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
		wmScorePackageStatus.setUserId(sysUser.getUserId() + "");
		wmScorePackageStatus.setTaskAddFlag("1");
		wmScorePackageStatus.setStatus("2");
		wmScorePackageStatus.setDelFlag("0");
		wmScorePackageStatus.setEnableFlag("0");
		List<WmScorePackageStatus> statusList = wmScorePackageStatusService.
				list(Wrappers.query(wmScorePackageStatus));

		List<Map<String, Object>> listMap = new ArrayList<>();

		for (WmScorePackageStatus item : statusList) {
			WmScorePackage wmScorePackage = wmScorePackageService.getById(item.getPackageId());
			if (null != wmScorePackage) {
				if ("0".equals(wmScorePackage.getTaskAddFlag())) {
					continue;
				}
				if ("1".equals(wmScorePackage.getEnableFlag())) {
					continue;
				}
				if ("2".equals(wmScorePackage.getPackageType2())) {
					continue;
				}
				if ("3".equals(wmScorePackage.getPackageType1())) {
					continue;
				}
				/**
				 * 过滤有效任务类型
				 */
				WmScoreTaskType taskType = new WmScoreTaskType();
				taskType.setTaskTypeId(type);
				taskType.setScoreId(wmScorePackage.getId());
//				List<WmScoreTaskType> taskTypes = wmScoreTaskTypeService.
//						list(Wrappers.query(taskType));
				int total = wmScoreTaskTypeService.count(Wrappers.query(taskType));

				if (total != 0) {
					Map<String, Object> map = new HashMap<>();
					map.put("label", wmScorePackage.getScorePackageName());
					map.put("value", wmScorePackage.getId());
					listMap.add(map);
				}

			}
		}

		return R.ok(listMap);
	}


	/**
	 * 获取登录人积分包（药品生产商发包或者cso单独发包）
	 *
	 * @param type    积分包类型
	 * @param albumId 产品相册id
	 * @return 积分包列表
	 */
	@ApiOperation(value = "获取登录人积分包", notes = "药品生产商发包或者cso单独发包")
	@SysLog("获取登录人积分包（药品生产商发包或者cso单独发包")
	@GetMapping("/getPackageListByTaskTypeAndAlbumId")
	public R getPackageListByTaskTypeAndAlbumId(String type, Integer albumId) {
		if (StringUtils.isEmpty(type) || albumId == null) {
			return R.failed("参数异常，请求失败");
		}
		//获取用户基本信息
		if (null == SecurityUtils.getUser().getId()) {
			return R.failed("请求失败");
		}

		SysUser sysUser = sysUserService.getById(SecurityUtils.getUser().getId());

		// 获取相册信息
		WmWkAlbum album = wmWkAlbumService.getById(albumId);
		// 获取相册的关联的药品
		WmDaDrugEntDrugtable daDrugEntDrugtable = wmDaDrugEntDrugtableService.getById(album.getGlyp());
		// 获取关联药品的生产企业
		String drugProducer = daDrugEntDrugtable.getDrugEntName();
		//筛选积分包
		WmScorePackageStatus wmScorePackageStatus = new WmScorePackageStatus();
		wmScorePackageStatus.setUserId(sysUser.getUserId() + "");
		wmScorePackageStatus.setTaskAddFlag("1");
		wmScorePackageStatus.setStatus("2");
		wmScorePackageStatus.setDelFlag("0");
		wmScorePackageStatus.setEnableFlag("0");
		List<WmScorePackageStatus> statusList = wmScorePackageStatusService.
				list(Wrappers.query(wmScorePackageStatus));

		List<Map<String, Object>> listMap = new ArrayList<>();

		for (WmScorePackageStatus item : statusList) {
			WmScorePackage wmScorePackage = wmScorePackageService.getOne(Wrappers.<WmScorePackage>lambdaQuery()
					.eq(WmScorePackage::getId, item.getPackageId()));
			// Map<String, Object> tmp = wmScorePackageService.getOne(Wrappers.<WmScorePackage>lambdaQuery()
			// 		.eq(WmScorePackage::getId, item.getPackageId()));
			// WmScorePackage wmScorePackage = BeanUtil.copyProperties(tmp,WmScorePackage.class);
			if (null != wmScorePackage) {
				if ("0".equals(wmScorePackage.getTaskAddFlag())) {
					continue;
				}
				if ("1".equals(wmScorePackage.getEnableFlag())) {
					continue;
				}
				if ("2".equals(wmScorePackage.getPackageType2())) {
					continue;
				}
				if ("3".equals(wmScorePackage.getPackageType1())) {
					continue;
				}
				if (ArrayUtils.isEmpty(wmScorePackage.getDrugProducerList())) {
					continue;
				}
				boolean flag = false;
				for (String name : wmScorePackage.getDrugProducerList()) {
					if (StringUtils.equals(name, drugProducer)) {
						flag = true;
						break;
					}
				}

				if (!flag) {
					continue;
				}

				/**
				 * 过滤有效任务类型
				 */
				WmScoreTaskType taskType = new WmScoreTaskType();
				taskType.setTaskTypeId(type);
				taskType.setScoreId(wmScorePackage.getId());
				int total = wmScoreTaskTypeService.count(Wrappers.query(taskType));

				if (total != 0) {
					Map<String, Object> map = new HashMap<>();
					map.put("label", wmScorePackage.getScorePackageName());
					map.put("value", wmScorePackage.getId());
					listMap.add(map);
				}

			}
		}
		return R.ok(listMap);
	}

	/**
	 * 获取阅读人openid
	 *
	 * @param authCode 授权code
	 * @return 获取结果
	 */
	private String getReaderOpenId(String authCode) {
		//获取小程序openid
		log.info("小程序登录AUTH_CODE:{}", authCode);
		Map<String, Object> resultMap = GetOpenIDUtil.oauth2GetOpenid(authCode.trim(),upmsConfig.getWechatEnv());
		log.warn("小程序登录结果信息:{}", resultMap);
		return (String) resultMap.get("openid");
	}

	/**
	 * 分享阅读任务方法
	 *
	 * @param id               文章或者相册id
	 * @param shareUserId      分享人id
	 * @param openUserId       打开人获取openid授权码
	 * @param type             操作类型：share->分享， open->打开
	 * @param packageId        积分包id
	 * @param sharePicUrl      分享图片链接
	 * @param taskCategoryName 任务类别名称
	 * @return 结果
	 */
	private R<?> shareAndReadTaskMethod(String id, String shareUserId, String openUserId, String type, String packageId,
										String sharePicUrl, String taskCategoryName) {

		LocalDateTime now = LocalDateTime.now();
		int score = 0;
		String msg = "";
		WmWkAlbum wmWkAlbum = null;
		WmWkArticle wmWkArticle = null;
		WmScorePackageStatus scorePackageStatus = null;

		if (StringUtils.isEmpty(id) || StringUtils.isEmpty(packageId)) {
			return R.ok();
		}

		if (StringUtils.isEmpty(shareUserId)) {
			return R.failed("分享人ID不能为空");
		}

		WmScorePackage tWmScorePackage = wmScorePackageService.getById(packageId);
		if (null == tWmScorePackage) {
			return R.failed("积分包异常，请选择其他积分包");
		}
		if ("0".equals(tWmScorePackage.getTaskAddFlag())) {
			return R.ok();
		}
		if (StringUtils.isEmpty(tWmScorePackage.getRuleId())) {
			return R.failed("积分包未配置积分规则");
		}

		if ("article".equalsIgnoreCase(taskCategoryName)) {
			wmWkArticle = wmWkArticleService.getById(id);
		} else if ("album".equalsIgnoreCase(taskCategoryName)) {
			wmWkAlbum = wmWkAlbumService.getById(id);
		}

		// 获取分享人
		SysUser sysUser = sysUserService.getById(shareUserId);

		if (null != sysUser) {
			UserVO userVO = sysUserService.selectUserVoById(sysUser.getUserId());
			if (null != userVO) {

				if (!StringUtils.equalsAny(type, "share", "open")) {
					return R.failed("操作类型错误");
				}

				// 校验相册和文章转发次数限制
				if ("share".equals(type)) {
					String info = null;
					if ("album".equalsIgnoreCase(taskCategoryName)) {
						info = checkAlbumLimit(wmWkAlbum, sysUser);
					} else if ("article".equalsIgnoreCase(taskCategoryName)) {
						info = checkArticleLimit(wmWkArticle, sysUser);
					}
					if (StringUtils.isNotEmpty(info)) {
						return R.failed(info);
					}
				}

				if ("1".equals(tWmScorePackage.getPackageType1())) {
					boolean fullFlag = wmTaskService.checkUserTaskSubScore(String.valueOf(userVO.getUserId()));
					if (fullFlag) {
						String value = sysPublicParamService.getSysPublicParamKeyToValue("USER_TASK_SUB_SCORE");
						String info = StringUtils.isEmpty(value) ? "每日最多提交3万积分" : "每日最多提交" + Integer.parseInt(value) + "积分";
						log.warn("系统当前限制积分上限：【{}】，提示：【{}】", value, info);
						return R.failed(info + "，积分+0");
					}
				}

				List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(
						Wrappers.<WmScorePackageStatus>lambdaQuery()
								.eq(WmScorePackageStatus::getUserId, String.valueOf(userVO.getUserId()))
								.eq(WmScorePackageStatus::getStatus, "2")
								.eq(WmScorePackageStatus::getTaskAddFlag, "1")
								.eq(WmScorePackageStatus::getPackageId, tWmScorePackage.getId())
								.eq(WmScorePackageStatus::getDelFlag, "0")
								.eq(WmScorePackageStatus::getEnableFlag, "0")
				);

				if (CollectionUtils.isEmpty(statusList)) {
					return R.ok();
				}

				if (statusList.size() != 1) {
					log.warn("获取积分包异常，任务保存失败9002：{}", tWmScorePackage.getId());
					return R.failed("获取积分包异常，任务保存失败");
				}

				scorePackageStatus = statusList.get(0);

				WmWkArticleShare wmWkArticleShare = new WmWkArticleShare();
				wmWkArticleShare.setShareUserid(userVO.getUserId() + "");
				wmWkArticleShare.setShareType("1");
				wmWkArticleShare.setCreateTime(LocalDateTime.now());
				wmWkArticleShare.setArctileId(id);

				WmTask wmTask = new WmTask();
				log.info("获取积分包ID：{}", tWmScorePackage.getId());
				// 根据任务类型获取积分值
				WmTaskType wmTaskType = new WmTaskType();
				wmTaskType.setRuleId(tWmScorePackage.getRuleId());
				if ("share".equalsIgnoreCase(type)) {
					if ("article".equalsIgnoreCase(taskCategoryName)) {
						wmTask.setTaskTypeId("9");
					} else if ("album".equalsIgnoreCase(taskCategoryName)) {
						wmTask.setTaskTypeId("8");
					}
				} else if ("open".equalsIgnoreCase(type)) {
					if ("article".equalsIgnoreCase(taskCategoryName)) {
						wmTask.setTaskTypeId("10");
					} else if ("album".equalsIgnoreCase(taskCategoryName)) {
						wmTask.setTaskTypeId("11");
					}
				}
				wmTaskType.setTaskTypeName(wmTaskTypeService.getById(wmTask.getTaskTypeId()).getTaskTypeName());
				score = wmTaskTypeService.getWmTaskTypeByEnt(wmTaskType);

				log.info("任务类型预设积分：{}", score);
				if (score < 0) {
					return R.failed("获取任务积分失败");
				}
				wmTask.setScore(score);


				boolean needToCheckLimit = tWmScorePackage.getScore() > 3000;
				if ("open".equals(type)) {
					List<WmWkArticleShare> wmWkArticleShareList = wmWkArticleShareService.list(Wrappers.
							<WmWkArticleShare>lambdaQuery()
							.eq(WmWkArticleShare::getArctileId, id)
							.eq(WmWkArticleShare::getShareType, "1")
							.orderByDesc(WmWkArticleShare::getCreateTime));
					if (CollectionUtils.isNotEmpty(wmWkArticleShareList)) {
						List<String> stringList = wmWkArticleShareList.stream()
								.map(articleShare -> String.valueOf(articleShare.getId())).collect(Collectors.toList());
						List<WmTask> wmTaskList = wmTaskService.list(Wrappers.<WmTask>lambdaQuery()
								.in(WmTask::getTaskContentId, stringList)
								.orderByDesc(WmTask::getCreateTime));
						if (CollectionUtils.isNotEmpty(wmTaskList)) {
							Optional<WmTask> first = wmTaskList.stream()
									.filter(t -> StringUtils.isNotEmpty(t.getShareImgUrl()))
									.findFirst();
							first.ifPresent(task -> wmTask.setShareImgUrl(task.getShareImgUrl()));
						}
					}

					// 获取打开用户的openid
					if (StringUtils.isEmpty(openUserId)) {
						log.info("openUserId为null，任务积分为0。");
						wmTask.setScore(0);
					} else {
						String readerOpenId = getReaderOpenId(openUserId.trim());
						if (readerOpenId.contains("null")) {
							log.info("获取阅读者openid失败，积分值为0");
							wmTask.setScore(0);
						} else {
							// 过滤文章分享list，如果阅读者已经阅读过同一个分享人分享的的同一篇文章，就不再记录分数
							List<WmWkArticleShare> shares = wmWkArticleShareList
									.stream()
									.filter(s -> readerOpenId.equals(s.getOpenUser()) && shareUserId.equals(s.getShareUserid()))
									.collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(shares)) {
								log.info("同一个分享存在多次打开记录:{}", shares);
								wmTask.setScore(0);
							}
							//  记录阅读者openid
							wmWkArticleShare.setOpenUser(readerOpenId);

						}
					}

					// 校验打开结果
					if (needToCheckLimit) {
						if ("article".equalsIgnoreCase(taskCategoryName)) {
							needToCheckLimit = checkArticleOpenLimit(wmWkArticle, sysUser, wmTask);
						} else if ("album".equalsIgnoreCase(taskCategoryName)) {
							needToCheckLimit = checkAlbumOpenLimit(wmWkAlbum, sysUser, wmTask);
						}
					}
				}

				// 记录分享记录
				wmWkArticleShareService.save(wmWkArticleShare);

				wmTask.setTaskFrom("1");
				wmTask.setTaskUserId(String.valueOf(userVO.getUserId()));  //任务提交人
				wmTask.setLookintoDate(now);       //调研时间
				wmTask.setUpdateTime(now);
				wmTask.setDrugEntId(userVO.getDrugEntId());
				wmTask.setShareImgUrl(sharePicUrl);
				wmTask.setScorePackageId(tWmScorePackage.getId());
				wmTask.setTaskRuleId(tWmScorePackage.getTaskRuleId());
				wmTask.setTaskContentId(String.valueOf(wmWkArticleShare.getId()));
				wmTask.setCreateTime(now);
				wmTask.setDeptId(String.valueOf(userVO.getDeptId()));

				if (isZbRole(userVO.getRoleList(), 5)) {
					wmTask.setTaskUserType("5");
				}

				if (isZbRole(userVO.getRoleList(), 6)) {
					wmTask.setTaskUserType("6");
				}


				// 判断是否保存前最后校验一遍文章分享和文章阅读以及产品分享和产品分享阅读所做的积分值是否在比例范围之内
				// （初始设定为30%，积分包值小于3000不做校验）
				if (needToCheckLimit && null != scorePackageStatus) {
					String value = sysPublicParamService.getSysPublicParamKeyToValue("SHARE_READ_TASK_SCORE_UPPER_LIMIT_RATIO");
					value = StringUtils.isEmpty(value) ? "0.3" : value;
					log.warn("系统当前分享类及分享阅读类积分上限：【{}】", value);
					int limit = (int) (Integer.parseInt(scorePackageStatus.getUserScore()) * Double.parseDouble(value));
					List<WmTask> taskList = wmTaskService.list(Wrappers.<WmTask>lambdaQuery()
							// 两对分享阅读任务
							.in(WmTask::getTaskTypeId, Arrays.asList("8", "9", "10", "11"))
							// 同一个积分包
							.eq(WmTask::getScorePackageId, tWmScorePackage.getId())
							// 分享人
							.eq(WmTask::getTaskUserId, shareUserId)
							// 审核不通过
							.ne(WmTask::getTaskStatus, "4")
					);

					int sum = taskList.stream().mapToInt(WmTask::getScore).sum();
					log.info("当前积分包值限制上限为:{},当前任务积分和为:{}", limit, sum);
					if (sum >= limit) {
						log.warn("完成任务积分值已经超过上限，设置为0");
						wmTask.setScore(0);
						msg = String.format("转发类任务所得积分不得大于积分包值的%d%s",
								new BigDecimal(value).multiply(new BigDecimal("100"))
										.setScale(0, BigDecimal.ROUND_HALF_UP).intValue(), "%");
					}
				}

				// 校验结果为0积分的自动审核不通过
				boolean autoRejectFlag = wmTask.getScore() == 0;

				wmTask.setTaskStatus(autoRejectFlag ? "4" : "2"); //任务状态
				wmTask.setSubmitStatus(autoRejectFlag ? "1" : "0");
				boolean isSave = wmTaskService.save(wmTask);   //保存任务


				//判断任务是否完成
				if (isSave) {
					WmScorePackage wmScorePackage1 = wmScorePackageService.getById(tWmScorePackage.getId());
					//判断任务是否完成
					if (null != wmScorePackage1) {
						// 查询出 审核通过和审核中的任务
						List<WmTask> wmTaskList = wmTaskService.list(Wrappers.<WmTask>lambdaQuery()
								.eq(WmTask::getScorePackageId, tWmScorePackage.getId())
								// 查询出 审核通过和审核中的任务
								.ne(WmTask::getTaskStatus, "4")
								.eq(WmTask::getRealFlag, "0"));
						// 判断定量还是定额 1- 定额   2-定量
						if ("1".equals(wmScorePackage1.getPackageType1())) {

							int totalCount = 0;
							for (WmTask wmtask : wmTaskList) {
								totalCount += wmtask.getScore();
							}

							if (totalCount >= wmScorePackage1.getScore()) {
								wmScorePackage1.setTaskAddFlag("0");
								scorePackageStatus.setTaskAddFlag("0");
								wmScorePackageStatusService.updateById(scorePackageStatus);
							}
						} else if ("2".equals(wmScorePackage1.getPackageType1())) {
							score = 0;

							List<WmTask> userTaskList = wmTaskList.stream()
									.filter(item -> item.getTaskUserId().equals(String.valueOf(userVO.getUserId())))
									.collect(Collectors.toList());

							if (userTaskList.size() >= scorePackageStatus.getTaskNum()) {
								scorePackageStatus.setTaskAddFlag("0");
								wmScorePackageStatusService.updateById(scorePackageStatus);
								// 改变大包状态
								WmScorePackageStatus queryAll = new WmScorePackageStatus();
								queryAll.setPackageId(tWmScorePackage.getId());
								queryAll.setStatus("2");
								queryAll.setTaskAddFlag("0");
								List<WmScorePackageStatus> statusAll = wmScorePackageStatusService.
										list(Wrappers.query(queryAll));
								if (new BigDecimal(wmScorePackage1.getUserNum())
										.compareTo(new BigDecimal(statusAll.size())) <= 0) {
									wmScorePackage1.setTaskAddFlag("0");
								}
							}

						}

						wmScorePackage1.setIsConduct("1");
						wmScorePackageService.updateById(wmScorePackage1);

					}

				} else {
					return R.failed("任务保存失败");
				}
			}
		}

		if ("album".equalsIgnoreCase(taskCategoryName)) {
			if ("share".equalsIgnoreCase(type)) {
				wmWkAlbum.setForwardNum(wmWkAlbum.getForwardNum() + 1);
			}
			wmWkAlbumService.updateById(wmWkAlbum);
			wmWkAlbum.setScore(String.valueOf(score));

			return R.ok(wmWkAlbum, msg);
		} else if ("article".equalsIgnoreCase(taskCategoryName)) {
			if ("share".equalsIgnoreCase(type)) {
				wmWkArticle.setForwardNum(wmWkArticle.getForwardNum() + 1);
			}
			wmWkArticleService.updateById(wmWkArticle);
			wmWkArticle.setScore(String.valueOf(score));
			return R.ok(wmWkArticle, msg);
		}

		return R.ok(null, msg);
	}


	/**
	 * 文章打开判断
	 *
	 * @param article 文章
	 * @param user    分享用户
	 * @param task    任务
	 */
	private Boolean checkArticleOpenLimit(WmWkArticle article, SysUser user, WmTask task) {
		Assert.notNull(article);
		LocalDateTime now = LocalDateTime.now();
		final String cacheKey = CacheConstants.ARTICLE_PERSONAL_SHARE_KEY + DateUtil.format(now, "yyyyMMdd:")
				+ user.getUserId() + ":" + article.getId();
		Integer times = (Integer) redisTemplate.opsForValue().get(cacheKey);
		if (null != times && times >= upmsConfig.getMaxShareTimes()) {
			log.info("{}:{}已经转发文章{}次数:{}", user.getUserId(), user.getRealname(), article.getId(), times);
			task.setScore(0);
			return false;
		}
		return true;
	}

	/**
	 * 相册打开判断
	 *
	 * @param album 相册
	 * @param user  分享用户
	 * @param task  任务
	 */
	private Boolean checkAlbumOpenLimit(WmWkAlbum album, SysUser user, WmTask task) {
		Assert.notNull(album);
		if (StringUtils.isNotEmpty(album.getGlyp())) {
			List<WmDaDrugEntDrugtable> drugTableList =
					wmDaDrugEntDrugtableService.listByIds(Arrays.asList(album.getGlyp().split(",")));
			if (CollectionUtils.isNotEmpty(drugTableList)) {
				String date = DateUtil.today() + ":";
				log.info("DateUtil.today():{}", date);
				for (WmDaDrugEntDrugtable drug : drugTableList) {
					if (StringUtils.isEmpty(drug.getDrugEntId())) {
						continue;
					}
					String key = CacheConstants.DRUG_ENT_PERSONAL_SHARE_KEY1 + date
							+ drug.getDrugEntId() + CacheConstants.DRUG_ENT_PERSONAL_SHARE_KEY2 + user.getUserId();
					log.info("key:{}", key);
					Integer times = (Integer) redisTemplate.opsForValue().get(key);
					if (times != null && times >= upmsConfig.getMaxShareTimes()) {
						task.setScore(0);
						return false;
					}
				}
			}
		}
		return true;
	}

	/**
	 * 校验文章转发限制
	 *
	 * @param wmWkArticle 文章
	 * @param sysUser     转发人
	 * @return 校验信息
	 */
	private String checkArticleLimit(WmWkArticle wmWkArticle, SysUser sysUser) {
		Assert.notNull(wmWkArticle);
		LocalDateTime now = LocalDateTime.now();
		final String cacheKey = CacheConstants.ARTICLE_PERSONAL_SHARE_KEY + DateUtil.format(now, "yyyyMMdd:")
				+ sysUser.getUserId() + ":" + wmWkArticle.getId();
		Integer times = (Integer) redisTemplate.opsForValue().get(cacheKey);
		if (null != times) {
			log.info("{}:{}已经转发文章{}次数:{}", sysUser.getUserId(), sysUser.getRealname(), wmWkArticle.getId(), times);
			if (times++ >= upmsConfig.getMaxShareTimes()) {
				return "您当日转发的该文章次数已超过20次，转发将不再获得积分";
			}
		} else {
			log.info("{}:{}已经首次转发文章:{}", sysUser.getUserId(), sysUser.getRealname(), wmWkArticle.getId(), times);
			times = 1;
		}
		redisTemplate.opsForValue()
				.set(cacheKey, times, Duration.between(now, LocalDateTime.of(now.toLocalDate(), LocalTime.MAX)));
		return null;
	}

	/**
	 * 校验相册转发限制
	 *
	 * @param wmWkAlbum 相册
	 * @param sysUser   分享人
	 * @return 校验结果信息
	 */
	private String checkAlbumLimit(WmWkAlbum wmWkAlbum, SysUser sysUser) {

		Assert.notNull(wmWkAlbum);
		if (StringUtils.isNotEmpty(wmWkAlbum.getGlyp())) {
			List<WmDaDrugEntDrugtable> drugTableList =
					wmDaDrugEntDrugtableService.listByIds(Arrays.asList(wmWkAlbum.getGlyp().split(",")));
			if (CollectionUtils.isNotEmpty(drugTableList)) {
				/**
				 * 2020-12-13 修改
				 * 需求有逻辑BUG
				 */
				String date = DateUtil.today() + ":";
				System.err.println("DateUtil.today():" + date);
				for (int i = 0; i < drugTableList.size(); i++) {
					WmDaDrugEntDrugtable drug = drugTableList.get(i);
					if (StringUtils.isEmpty(drug.getDrugEntId())) {
						continue;
					}
					String key = CacheConstants.DRUG_ENT_PERSONAL_SHARE_KEY1 + date
							+ drug.getDrugEntId() + CacheConstants.DRUG_ENT_PERSONAL_SHARE_KEY2 + sysUser.getUserId();
					System.err.println("key" + key);
					if (redisTemplate.hasKey(key)) {
						int times = Integer.parseInt(redisTemplate.opsForValue().get(key).toString());
						if (times >= upmsConfig.getMaxShareTimes()) {
							return "您当日转发的该药企产品相册次数已超过20次，转发将不再获得积分";
						}
						times++;
						redisTemplate.opsForValue().set(key, times, CacheConstants.SHARE_TIME, TimeUnit.DAYS);
					} else {
						redisTemplate.opsForValue().set(key, 1, CacheConstants.SHARE_TIME, TimeUnit.DAYS);
					}

				}
			}
		}
		return null;
	}
}
