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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDeptRelation;
import com.qunzhixinxi.hnqz.admin.entity.WmDaAgent;
import com.qunzhixinxi.hnqz.admin.entity.WmDaDrugEnt;
import com.qunzhixinxi.hnqz.admin.entity.WmDeptTaskTypeConfig;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskType;
import com.qunzhixinxi.hnqz.admin.entity.WmTeam;
import com.qunzhixinxi.hnqz.admin.entity.dto.WmDeptTaskTypeConfigDTO;
import com.qunzhixinxi.hnqz.admin.entity.dto.WmDeptTaskTypeConfigJsonDTO;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.DeptLevelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.enums.ScorePackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptRelationMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaAgentMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaDrugEntMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDeptTaskTypeConfigMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTeamMapper;
import com.qunzhixinxi.hnqz.admin.service.WmDeptTaskTypeConfigService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskTypeService;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 部门任务类型配置服务
 *
 * @author lixuesong
 * @date 2021年12月03日 10:14
 */
@Slf4j
@AllArgsConstructor
@Service
public class WmDeptTaskTypeConfigServiceImpl extends ServiceImpl<WmDeptTaskTypeConfigMapper, WmDeptTaskTypeConfig> implements WmDeptTaskTypeConfigService {

	private final WmTaskTypeService wmTaskTypeService;

	private final WmScorePackageService wmScorePackageService;

	private final SysDeptRelationMapper sysDeptRelationMapper;

	private final WmDaDrugEntMapper wmDaDrugEntMapper;

	private final WmTaskMapper wmTaskMapper;

	private final SysDeptMapper sysDeptMapper;

	private final WmDaAgentMapper wmDaAgentMapper;

	private final WmTeamMapper wmTeamMapper;

	/**
	 * 兼职学术专员启用的任务类型
	 */
	private final String[] ENABLE_ZBDB_STATUS_ARR = {"医院拜访", "商业公司拜访", "药店拜访", "电子名片分享", "产品相册分享", "学术信息交流",
			"受众打开产品相册", "受众阅读文章"};

	/**
	 * 任务类型Map
	 */
	private static Map<String, List<String>> BASE_TASK_TYPE_MAP = new LinkedHashMap<>();

	static {
		List<String> meetingList = new ArrayList<String>() {{
			add("医院科室推广会");
			add("区域学术沙龙");
			add("城市卫星会");
			add("省级学科年会");
		}};
		BASE_TASK_TYPE_MAP.put("会议举办", meetingList);

		List<String> interviewList = new ArrayList<String>() {{
			add("一对一专访");
		}};
		BASE_TASK_TYPE_MAP.put("一对一专访", interviewList);

		List<String> customerList = new ArrayList<String>() {{
			add("医院拜访");
			add("商业公司拜访");
			add("药店拜访");
		}};
		BASE_TASK_TYPE_MAP.put("客户拜访", customerList);

		List<String> producrList = new ArrayList<String>() {{
			add("产品相册分享");
			add("受众打开产品相册");
			add("电子名片分享");
		}};
		BASE_TASK_TYPE_MAP.put("产品推广", producrList);

		List<String> academicList = new ArrayList<String>() {{
			add("学术信息交流");
			add("受众阅读文章");
		}};
		BASE_TASK_TYPE_MAP.put("学术信息交流", academicList);

		List<String> marketList = new ArrayList<String>() {{
			add("政策信息收集");
			add("竞品信息收集");
			add("库存信息收集");
			add("医院信息收集");
			add("商业公司信息收集");
			add("药物警戒相关信息收集（疗效等）");
			add("药店调查");
		}};
		BASE_TASK_TYPE_MAP.put("市场信息收集", marketList);

		List<String> medicineList = new ArrayList<String>() {{
			add("专家咨询");
			add("受试者管理");
			add("医学撰写");
			add("受试者招募");
			add("数据管理");
			add("统计分析");
			add("临床监察");
		}};
		BASE_TASK_TYPE_MAP.put("医药研发服务", medicineList);

		List<String> trainingList = new ArrayList<String>() {{
			add("医院患者教育培训");
			add("药店药师培训");
			add("商业公司培训");
		}};
		BASE_TASK_TYPE_MAP.put("培训", trainingList);
	}

	/**
	 * 保存任务类型配置
	 *
	 * @param wmDeptTaskTypeConfigDTO
	 */
	@Override
	public void saveDeptTaskTypeConfig(WmDeptTaskTypeConfigDTO wmDeptTaskTypeConfigDTO) {
		// 判断是否已存在
		int count = this.count(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
				.eq(WmDeptTaskTypeConfig::getDeptId, wmDeptTaskTypeConfigDTO.getDeptId()));
		// 批量设置任务类型id设置为基础类型id
		wmDeptTaskTypeConfigDTO.getConfigList().forEach(configJsonDTO -> {
			// 查询任务名称对应的基础任务类型id
			WmTaskType baseTaskType = wmTaskTypeService.getOne(Wrappers.<WmTaskType>lambdaQuery()
					.eq(WmTaskType::getTaskTypeLevel, "1")
					.eq(WmTaskType::getTaskTypeName, configJsonDTO.getTaskTypeName()));
			configJsonDTO.setTaskTypeId(baseTaskType.getId());
			// 判断并确保兼职任务类型未启用时不可选中
			if (!ArrayUtil.contains(ENABLE_ZBDB_STATUS_ARR, configJsonDTO.getTaskTypeName())) {
				configJsonDTO.setZbdbStatusEnable(false);
				configJsonDTO.setZbdbStatusSelect(false);
			}
		});
		if (count <= 0) {
			// 新增
			WmDeptTaskTypeConfig deptTaskTypeConfig = new WmDeptTaskTypeConfig();
			deptTaskTypeConfig.setDeptId(wmDeptTaskTypeConfigDTO.getDeptId());
			deptTaskTypeConfig.setTaskTypeJson(JSON.toJSONString(wmDeptTaskTypeConfigDTO.getConfigList()));
			deptTaskTypeConfig.setCreateTime(LocalDateTime.now());
			deptTaskTypeConfig.setCreateUser(SecurityUtils.getUser().getId());
			this.save(deptTaskTypeConfig);
		} else {
			// 更新
			WmDeptTaskTypeConfig deptTaskTypeConfig = new WmDeptTaskTypeConfig();
			deptTaskTypeConfig.setDeptId(wmDeptTaskTypeConfigDTO.getDeptId());
			deptTaskTypeConfig.setTaskTypeJson(JSON.toJSONString(wmDeptTaskTypeConfigDTO.getConfigList()));
			deptTaskTypeConfig.setUpdateTime(LocalDateTime.now());
			deptTaskTypeConfig.setUpdateUser(SecurityUtils.getUser().getId());
			this.update(Wrappers.<WmDeptTaskTypeConfig>lambdaUpdate()
					.eq(WmDeptTaskTypeConfig::getDeptId, deptTaskTypeConfig.getDeptId())
					.set(WmDeptTaskTypeConfig::getTaskTypeJson, JSON.toJSONString(wmDeptTaskTypeConfigDTO.getConfigList()))
					.set(WmDeptTaskTypeConfig::getUpdateTime, LocalDateTime.now())
					.set(WmDeptTaskTypeConfig::getUpdateUser, SecurityUtils.getUser().getId()));
		}
	}

	/**
	 * 查询任务类型配置
	 *
	 * @param deptId
	 * @return
	 */
	@Override
	public WmDeptTaskTypeConfigDTO getDeptTaskTypeConfig(Integer deptId) {
		// 查询出当前dept对应的药企/代理商id
		String durgentId = null;
		SysDept dept = sysDeptMapper.selectById(deptId);
		if (DeptLevelEnum.ENT.getVal().equals(dept.getLevel())) {
			WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntMapper.selectOne(Wrappers.<WmDaDrugEnt>lambdaQuery()
					.eq(WmDaDrugEnt::getDeptId, deptId)
					.eq(WmDaDrugEnt::getDelFlag, DelEnum.NOT_DEL.val()));
			durgentId = wmDaDrugEnt.getId();
		} else {
			WmDaAgent wmDaAgent = wmDaAgentMapper.selectOne(Wrappers.<WmDaAgent>lambdaQuery()
					.eq(WmDaAgent::getDeptId, deptId)
					.eq(WmDaAgent::getDelFlag, DelEnum.NOT_DEL.val()));
			durgentId = wmDaAgent.getId();
		}
		List<WmTaskType> taskTypeList = wmTaskTypeService.list(Wrappers.<WmTaskType>lambdaQuery()
				.eq(WmTaskType::getDeptId, deptId)
				.eq(WmTaskType::getRuleId, durgentId)
				.eq(WmTaskType::getTaskEntId, durgentId));

		WmDeptTaskTypeConfig deptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
				.eq(WmDeptTaskTypeConfig::getDeptId, deptId));

		WmDeptTaskTypeConfigDTO deptTaskTypeConfigDTO = new WmDeptTaskTypeConfigDTO();
		List<WmDeptTaskTypeConfigJsonDTO> deptTaskTypeConfigJsonDTOList = new ArrayList<>();
		deptTaskTypeConfigDTO.setDeptId(deptId);
		Map<String, WmDeptTaskTypeConfigJsonDTO> configMap = null;

		// 若配置任务类型不为空，则设置复选框的选择状态，否则设置复选框为默认状态
		if (deptTaskTypeConfig != null) {
			deptTaskTypeConfigDTO.setId(deptTaskTypeConfig.getId());
			List<WmDeptTaskTypeConfigJsonDTO> configJsonDTOList = JSON.parseArray(deptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
			configMap = configJsonDTOList.stream()
					.distinct()
					.collect(Collectors.toMap(WmDeptTaskTypeConfigJsonDTO::getTaskTypeName, wmDeptTaskTypeConfigJsonDTO -> wmDeptTaskTypeConfigJsonDTO));
		}
		// 以企业的任务类型数据为基础，进行任务类型配置数据的拼接
		if (CollectionUtil.isNotEmpty(taskTypeList)) {
			for (WmTaskType taskType : taskTypeList) {
				WmDeptTaskTypeConfigJsonDTO deptTaskTypeConfigJsonDTO = null;
				if (configMap != null) {
					// 若配置存在，则填充
					WmDeptTaskTypeConfigJsonDTO baseConfigJson = configMap.get(taskType.getTaskTypeName());
					deptTaskTypeConfigJsonDTO = BeanUtil.copyProperties(baseConfigJson, WmDeptTaskTypeConfigJsonDTO.class);
				} else {
					// 若配置不存在则，只设置默认值为未勾选状态
					deptTaskTypeConfigJsonDTO = new WmDeptTaskTypeConfigJsonDTO();
				}
				deptTaskTypeConfigJsonDTO.setTaskTypeId(taskType.getId());
				deptTaskTypeConfigJsonDTO.setTaskTypeName(taskType.getTaskTypeName());
				deptTaskTypeConfigJsonDTO.setScore(taskType.getScore());
				if (ArrayUtil.contains(ENABLE_ZBDB_STATUS_ARR, taskType.getTaskTypeName())) {
					deptTaskTypeConfigJsonDTO.setZbdbStatusEnable(true);
				} else {
					deptTaskTypeConfigJsonDTO.setZbdbStatusEnable(false);
				}
				deptTaskTypeConfigJsonDTOList.add(deptTaskTypeConfigJsonDTO);
			}
			deptTaskTypeConfigDTO.setConfigList(deptTaskTypeConfigJsonDTOList);
		}

		return deptTaskTypeConfigDTO;
	}

	/**
	 * 查询任务类型树
	 *
	 * @param taskTypeName
	 * @return
	 */
	@Override
	public List<Map<String, Object>> listConfigedTaskTypeTree(String taskTypeName) {
		Integer deptId = SecurityUtils.getUser().getDeptId();
		// 查询已配置的任务类型
		// 当前企业配置
		WmDeptTaskTypeConfig deptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
				.eq(WmDeptTaskTypeConfig::getDeptId, deptId));
		List<String> configTaskTypeIdList = null;
		if (deptTaskTypeConfig != null) {
			List<WmDeptTaskTypeConfigJsonDTO> configJsonDTOList = JSON.parseArray(deptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
			configTaskTypeIdList = configJsonDTOList.stream()
					.filter(WmDeptTaskTypeConfigJsonDTO::getQualifiedTask)
					.map(WmDeptTaskTypeConfigJsonDTO::getTaskTypeName)
					.collect(Collectors.toList());
		}
		// 查询上级
		SysDeptRelation ancestorDeptRelation = sysDeptRelationMapper.selectOne(Wrappers.<SysDeptRelation>lambdaQuery()
				.eq(SysDeptRelation::getDescendant, deptId)
				.ne(SysDeptRelation::getAncestor, deptId)
				.ne(SysDeptRelation::getAncestor, 1));
		List<String> ancestorConfigTaskTypeIdList = null;
		if (ancestorDeptRelation != null) {
			// 上级企业配置
			WmDeptTaskTypeConfig ancestorDeptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
					.eq(WmDeptTaskTypeConfig::getDeptId, ancestorDeptRelation.getAncestor()));
			if (ancestorDeptTaskTypeConfig != null) {
				List<WmDeptTaskTypeConfigJsonDTO> ancestorConfigJsonDTOList = JSON.parseArray(ancestorDeptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
				ancestorConfigTaskTypeIdList = ancestorConfigJsonDTOList.stream()
						.filter(configJsonDTO -> configJsonDTO.getQualifiedTask() && configJsonDTO.getAssociateLower())
						.map(WmDeptTaskTypeConfigJsonDTO::getTaskTypeName)
						.collect(Collectors.toList());
			}
		}
		if (CollectionUtil.isEmpty(configTaskTypeIdList) && CollectionUtil.isEmpty(ancestorConfigTaskTypeIdList)) {
			return new ArrayList<>();
		}

		// 查询出当前dept对应的任务类型（药企或药企给CSO的任务类型）
		String durgentId = null;
		SysDept dept = sysDeptMapper.selectById(deptId);
		if (DeptLevelEnum.ENT.getVal().equals(dept.getLevel())) {
			WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntMapper.selectOne(Wrappers.<WmDaDrugEnt>lambdaQuery()
					.eq(WmDaDrugEnt::getDeptId, deptId)
					.eq(WmDaDrugEnt::getDelFlag, DelEnum.NOT_DEL.val()));
			durgentId = wmDaDrugEnt.getId();
		} else {
			WmDaAgent wmDaAgent = wmDaAgentMapper.selectOne(Wrappers.<WmDaAgent>lambdaQuery()
					.eq(WmDaAgent::getDeptId, deptId)
					.eq(WmDaAgent::getDelFlag, DelEnum.NOT_DEL.val()));
			durgentId = wmDaAgent.getId();
		}
		// 查询企业对应的任务类型
		LambdaQueryWrapper<WmTaskType> taskTypeWrapper = Wrappers.lambdaQuery();
		taskTypeWrapper.eq(WmTaskType::getDeptId, deptId);
		taskTypeWrapper.eq(WmTaskType::getRuleId, durgentId);
		taskTypeWrapper.eq(WmTaskType::getTaskEntId, durgentId);
		if (org.apache.commons.lang.StringUtils.isNotBlank(taskTypeName)) {
			taskTypeWrapper.like(WmTaskType::getTaskTypeName, taskTypeName);
		}

		List<WmTaskType> taskTypeList = wmTaskTypeService.list(taskTypeWrapper);

		List<Map<String, Object>> resultList = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(taskTypeList)) {
			// 查询基础任务类型，用于匹配任务类型大类
			List<String> finalConfigTaskTypeIdList = configTaskTypeIdList;
			List<String> finalAncestorConfigTaskTypeIdList = ancestorConfigTaskTypeIdList;
			List<WmTaskType> filterTaskTypeList = taskTypeList.stream()
					.filter(wmTaskType ->
							(finalConfigTaskTypeIdList != null && finalConfigTaskTypeIdList.contains(wmTaskType.getTaskTypeName()))
									|| (finalAncestorConfigTaskTypeIdList != null && finalAncestorConfigTaskTypeIdList.contains(wmTaskType.getTaskTypeName()))
					)
					.collect(Collectors.toList());
			BASE_TASK_TYPE_MAP.forEach((key, val) -> {
				List<WmTaskType> childTypeList = filterTaskTypeList.stream()
						.filter(wmTaskType -> val.contains(wmTaskType.getTaskTypeName()))
						.collect(Collectors.toList());
				if (CollectionUtil.isNotEmpty(childTypeList)) {
					Map<String, Object> taskTypeMap = MapUtil.newHashMap(2);
					taskTypeMap.put("label", key);
					taskTypeMap.put("children", childTypeList);
					resultList.add(taskTypeMap);
				}
			});
		}
		return resultList;
	}

	/**
	 * 根据企业的任务类型配置查询任务列表
	 *
	 * @param taskTypeName 任务类型名称
	 * @param taskStatus   任务状态
	 * @return
	 */
	@Override
	public IPage<WmTask> listTaskByConfig(Page<WmTask> page, String taskTypeName, String[] taskStatus) {
		Integer deptId = SecurityUtils.getUser().getDeptId();
		Integer userId = SecurityUtils.getUser().getId();
		// 本级dept对应任务类型配置
		WmDeptTaskTypeConfig deptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
				.eq(WmDeptTaskTypeConfig::getDeptId, deptId));
		List<WmDeptTaskTypeConfigJsonDTO> filterConfigJsonDTOList = null;
		if (deptTaskTypeConfig != null) {
			// 查询该企业当前任务类型下 的任务类型配置数据
			List<WmDeptTaskTypeConfigJsonDTO> configJsonDTOList =
					JSON.parseArray(deptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
			if (StringUtils.isNotBlank(taskTypeName)) {
				filterConfigJsonDTOList = configJsonDTOList.stream()
						.filter(configJsonDTO -> configJsonDTO.getTaskTypeName().equals(taskTypeName) && configJsonDTO.getQualifiedTask()
								&& (configJsonDTO.getYydbStatusSelect() || configJsonDTO.getZbdbStatusSelect()))
						.collect(Collectors.toList());
			} else {
				filterConfigJsonDTOList = configJsonDTOList.stream()
						.filter(configJsonDTO -> configJsonDTO.getQualifiedTask()
								&& (configJsonDTO.getYydbStatusSelect() || configJsonDTO.getZbdbStatusSelect()))
						.collect(Collectors.toList());
			}
		}

		// 查询上级的deptId
		SysDeptRelation ancestorDeptRelation = sysDeptRelationMapper.selectOne(Wrappers.<SysDeptRelation>lambdaQuery()
				.eq(SysDeptRelation::getDescendant, deptId)
				.ne(SysDeptRelation::getAncestor, deptId)
				.ne(SysDeptRelation::getAncestor, 1));
		// 上级dept对应任务类型配置
		List<WmDeptTaskTypeConfigJsonDTO> filterAncestorConfigList = null;
		if (ancestorDeptRelation != null) {
			WmDeptTaskTypeConfig ancestorDeptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
					.eq(WmDeptTaskTypeConfig::getDeptId, ancestorDeptRelation.getAncestor()));
			if (ancestorDeptTaskTypeConfig != null) {
				List<WmDeptTaskTypeConfigJsonDTO> ancestorConfigJsonDTOList =
						JSON.parseArray(ancestorDeptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
				// 转换为key value形式
				if (StringUtils.isNotBlank(taskTypeName)) {
					filterAncestorConfigList = ancestorConfigJsonDTOList.stream()
							.filter(configJsonDTO -> configJsonDTO.getTaskTypeName().equals(taskTypeName)
									&& configJsonDTO.getQualifiedTask() && configJsonDTO.getAssociateLower()
									&& (configJsonDTO.getYydbStatusSelect() || configJsonDTO.getZbdbStatusSelect()))
							.collect(Collectors.toList());
				} else {
					filterAncestorConfigList = ancestorConfigJsonDTOList.stream()
							.filter(configJsonDTO -> configJsonDTO.getQualifiedTask() && configJsonDTO.getAssociateLower()
									&& (configJsonDTO.getYydbStatusSelect() || configJsonDTO.getZbdbStatusSelect()))
							.collect(Collectors.toList());
				}
			}
		}
		// 任务配置为空，则直接返回空page
		if (CollectionUtil.isEmpty(filterConfigJsonDTOList) && CollectionUtil.isEmpty(filterAncestorConfigList)) {
			return page;
		}

		// 根据不同任务类型的不同条件 拼接sql
		QueryWrapper<WmTask> taskWrapper = Wrappers.query();
		List<WmDeptTaskTypeConfigJsonDTO> finalFilterConfigJsonDTOList = filterConfigJsonDTOList;
		List<WmDeptTaskTypeConfigJsonDTO> finalFilterAncestorConfigList = filterAncestorConfigList;
		if (CollectionUtil.isNotEmpty(finalFilterConfigJsonDTOList) || CollectionUtil.isNotEmpty(finalFilterAncestorConfigList)) {
			taskWrapper.and(wrapper -> {
				// 当前企业直接发包的任务 条件
				if (CollectionUtil.isNotEmpty(finalFilterConfigJsonDTOList)) {
					for (WmDeptTaskTypeConfigJsonDTO configJsonDTO : finalFilterConfigJsonDTOList) {
						// 用户类型
						List<String> typeIdList = new ArrayList<>();
						if (configJsonDTO.getZbdbStatusSelect()) {
							typeIdList.add("4");
						}
						if (configJsonDTO.getYydbStatusSelect()) {
							typeIdList.add("3");
						}
						wrapper.or(wrapper2 -> {
							wrapper2.eq("t.task_type_id", configJsonDTO.getTaskTypeId());
							wrapper2.eq("t.dept_id", deptId);
							wrapper2.in("p.typeid", typeIdList);
							wrapper2.isNull("p.relation_score_id");
						});
					}
				}
				// 关联了上级企业的包的任务 条件
				if (CollectionUtil.isNotEmpty(finalFilterAncestorConfigList)) {
					for (WmDeptTaskTypeConfigJsonDTO configJsonDTO : finalFilterAncestorConfigList) {
						// 用户类型
						List<String> typeIdList = new ArrayList<>();
						if (configJsonDTO.getZbdbStatusEnable() && configJsonDTO.getZbdbStatusSelect()) {
							typeIdList.add("4");
						}
						if (configJsonDTO.getYydbStatusEnable() && configJsonDTO.getYydbStatusSelect()) {
							typeIdList.add("3");
						}
						wrapper.or(wrapper2 -> {
							wrapper2.eq("t.task_type_id", configJsonDTO.getTaskTypeId());
							wrapper2.eq("t.dept_id", deptId);
							wrapper2.in("p.typeid", typeIdList);
							wrapper2.isNotNull("p.relation_score_id");
						});
					}
				}
			});
		}
		taskWrapper.eq("t.del_flag", DelEnum.NOT_DEL.val());
		taskWrapper.eq("t.real_flag", "0");
		taskWrapper.in("t.task_status", taskStatus);
		// 如果是个人承接-按积分值，判断当前用户是否配置了团队负责人
		List<WmTeam> teamList = wmTeamMapper.selectList(Wrappers.<WmTeam>lambdaQuery()
				.eq(WmTeam::getDeptId, deptId)
				.eq(WmTeam::getEnableFlag, EnableEnum.ENABLE.val())
				.eq(WmTeam::getDelFlag, DelEnum.NOT_DEL.val())
				.apply("FIND_IN_SET({0}, leader)", String.valueOf(userId)));
		if (CollectionUtil.isNotEmpty(teamList)) {
			// 如果配置了，则只查询所在团队下发的积分包
			List<String> teamIdList = teamList.stream().map(wmTeam -> String.valueOf(wmTeam.getId())).collect(Collectors.toList());
			taskWrapper.in("p.package_user_scope", teamIdList);
		}
		taskWrapper.orderByDesc("t.lookinto_date");
		return wmTaskMapper.listWmTaskByWrapper(page, taskWrapper);
	}

	/**
	 * 根据企业的任务类型配置查询任务列表
	 *
	 * @param taskTypeName 任务类型名称
	 * @param taskStatus   任务状态
	 * @return
	 */
	@Deprecated
	@Override
	public IPage<WmTask> listTaskByDeptTaskType(Page<WmTask> page, String taskTypeName, String[] taskStatus) {
		Integer deptId = SecurityUtils.getUser().getDeptId();
		WmDeptTaskTypeConfig deptTaskTypeConfig = this.getOne(Wrappers.<WmDeptTaskTypeConfig>lambdaQuery()
				.eq(WmDeptTaskTypeConfig::getDeptId, deptId));
		if (deptTaskTypeConfig != null) {
			// 查询该企业当前任务类型下 的任务类型配置数据
			List<WmDeptTaskTypeConfigJsonDTO> configJsonDTOList =
					JSON.parseArray(deptTaskTypeConfig.getTaskTypeJson(), WmDeptTaskTypeConfigJsonDTO.class);
			WmDeptTaskTypeConfigJsonDTO taskTypeConfigJsonDTO = configJsonDTOList.stream()
					.filter(configJsonDTO -> configJsonDTO.getTaskTypeName().equals(taskTypeName))
					.findFirst()
					.get();
			// 查询任务名称对应的基础任务类型id
			WmTaskType baseTaskType = wmTaskTypeService.getOne(Wrappers.<WmTaskType>lambdaQuery()
					.eq(WmTaskType::getTaskTypeLevel, "1")
					.eq(WmTaskType::getTaskTypeName, taskTypeName)
					.eq(WmTaskType::getEnableFlag, EnableEnum.ENABLE.val()));
			// 根据是否勾选了关联下级，查询当前企业对应的积分包
			List<String> scorePackageIdList = new ArrayList<>();
			LambdaQueryWrapper<WmScorePackage> scorePackageWrapper = Wrappers.lambdaQuery();
			scorePackageWrapper.eq(WmScorePackage::getSendPackageDeptId, deptId);
			scorePackageWrapper.eq(WmScorePackage::getEnableFlag, EnableEnum.ENABLE.val());
			scorePackageWrapper.eq(WmScorePackage::getDelFlag, DelEnum.NOT_DEL.val());
			scorePackageWrapper.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_SCOTE_PACKAGE.val());
			scorePackageWrapper.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_TASK_PACKAGE.val());
			scorePackageWrapper.ge(WmScorePackage::getScorePackageStatus, ScorePackageStatusEnum.IN_PROGRESS.val());
			scorePackageWrapper.in(WmScorePackage::getTypeid, "3", "4");
			if (taskTypeConfigJsonDTO.getAssociateLower()) {
				// 配置了关联下级，则同时查询'对应机构下发的企业承接的任务，再下发给个人的积分包'
				List<WmScorePackage> scorePackageList = wmScorePackageService.list(scorePackageWrapper);
				if (CollectionUtil.isNotEmpty(scorePackageList)) {
					// 遍历查找所有下级积分包
					Set<String> ids = scorePackageList.stream().map(WmScorePackage::getId).collect(Collectors.toSet());
					getAllLowerScorePackages(ids, scorePackageList);

					// 过滤只要发给个人的包
					scorePackageIdList = scorePackageList.stream()
							.filter(scorePackage -> StringUtils.isBlank(scorePackage.getAcceptSug()))
							.map(WmScorePackage::getId).collect(Collectors.toList());
				}
			} else {
				// 未勾选关联下级，则全部任务中只显示未关联积分包的任务，就是从企业直接下发给医药代表的任务 是未关联积分包吗？代理商可以有吧???
				scorePackageWrapper.and(wrapper -> wrapper.isNull(WmScorePackage::getAcceptSug)
						.or()
						.apply("length(accept_sug) = 0"));
				List<WmScorePackage> scorePackageList = wmScorePackageService.list(scorePackageWrapper);
				if (CollectionUtil.isNotEmpty(scorePackageList)) {
					// 过滤只要发给个人的包
					scorePackageIdList = scorePackageList.stream()
							.filter(scorePackage -> StringUtils.isBlank(scorePackage.getAcceptSug()))
							.map(WmScorePackage::getId).collect(Collectors.toList());
				}
			}
			// 用户类型
			List<String> taskUserTypeList = new ArrayList<>();
			if (taskTypeConfigJsonDTO.getZbdbStatusEnable() && taskTypeConfigJsonDTO.getZbdbStatusSelect()) {
				taskUserTypeList.add("5");
			}
			if (taskTypeConfigJsonDTO.getYydbStatusEnable() && taskTypeConfigJsonDTO.getZbdbStatusSelect()) {
				taskUserTypeList.add("6");
			}

			if (CollectionUtil.isNotEmpty(scorePackageIdList) && CollectionUtil.isNotEmpty(taskUserTypeList)) {
				// 查询任务列表
				WmTask queryTask = new WmTask();
				queryTask.setTaskTypeId(baseTaskType.getId());
				queryTask.setScorePackageId(String.join(",", scorePackageIdList));
				queryTask.setTaskUserType(String.join(",", taskUserTypeList));
				queryTask.setTaskStatus(String.join(",", taskStatus));
				IPage<WmTask> taskPage = wmTaskMapper.listWmTaskByConfig(page, queryTask);
				return taskPage;
			}
		}

		return page;
	}

	/**
	 * 查询所有下级的积分包
	 *
	 * @param ids
	 * @param res
	 */
	private void getAllLowerScorePackages(Set<String> ids, List<WmScorePackage> res) {
		List<WmScorePackage> subList = wmScorePackageService.list(Wrappers.<WmScorePackage>lambdaQuery()
				.in(WmScorePackage::getRelationScoreId, ids)
				.eq(WmScorePackage::getDelFlag, DelEnum.NOT_DEL.val())
				.eq(WmScorePackage::getEnableFlag, EnableEnum.ENABLE.val()));

		if (CollectionUtil.isNotEmpty(subList)) {
			Set<String> idSet = subList.stream().map(WmScorePackage::getId).collect(Collectors.toSet());
			res.addAll(subList);
			getAllLowerScorePackages(idSet, res);
		}
	}
}
