/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */
package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.entity.input.WmDept;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.*;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.data.datascope.DataScope;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * 档案-代理商
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:42
 */
@Service
@AllArgsConstructor
public class WmDaAgentServiceImpl extends ServiceImpl<WmDaAgentMapper, WmDaAgent> implements WmDaAgentService {
	private final SysDeptService sysDeptService;
	private final SysUserService sysUserService;
	private final SysUserMapper sysUserMapper;
	private final WmDaAgentMapper wmDaAgentMapper;
	private final WmDaDrugEntMapper wmDaDrugEntMapper;
	private final SysDeptRelationService sysDeptRelationService;
	private final SysDeptRelationMapper sysDeptRelationMapper;
	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmRelationMapper wmRelationMapper;
	private final WmRelationService wmRelationService;
	private final WmTaskTypeMapper wmTaskTypeMapper;
	private final WmTaskTypeEntRefMapper wmTaskTypeEntRefMapper;
	private final SysDeptMapper sysDeptMapper;
	private final SysDeptSubMapper sysDeptSubMapper;

	public String getDeptBuildName(String deptId) {
		String buildName = "";
		SysDept sysDept = sysDeptService.getById(deptId);
		if (null != sysDept) {
			//buildName=sysDept.getName();
			SysDept sysDeptP1 = sysDeptService.getById(sysDept.getParentId());
			if (null != sysDeptP1) {
				buildName = sysDeptP1.getName();
				if (null != sysDeptP1.getParentId() && sysDeptP1.getParentId() > 1) {
					SysDept sysDeptP2 = sysDeptService.getById(sysDeptP1.getParentId());
					if (null != sysDeptP2) {
						buildName = sysDeptP2.getName() + "-" + buildName;

						if (null != sysDeptP2.getParentId() && sysDeptP2.getParentId() > 1) {
							SysDept sysDeptP3 = sysDeptService.getById(sysDeptP2.getParentId());
							if (null != sysDeptP3) {
								buildName = sysDeptP3.getName() + "-" + buildName;
								if (null != sysDeptP3.getParentId() && sysDeptP3.getParentId() > 1) {
									SysDept sysDeptP4 = sysDeptService.getById(sysDeptP3.getParentId());
									if (null != sysDeptP4) {
										buildName = sysDeptP4.getName() + "-" + buildName;
									}
								}
							}
						}
					}
				}
			}
		}
		return buildName;
	}

	public List<WmDaAgent> selectByScope(Wrapper<WmDaAgent> queryWrapper) {
		return wmDaAgentMapper.selectListByScope(queryWrapper, new DataScope());
	}

	/**
	 * @Modify: start
	 * @Version: v2021.4.16
	 * @Author: ryz
	 * @Date: 2021/4/26
	 * sysDept.setTaxCode(wmDaAgent.getZjNumber());
	*/
	public boolean saveAgent(WmDaAgent wmDaAgent) {
		wmDaAgent.setCreateTime(LocalDateTime.now());
		boolean isSave = super.save(wmDaAgent);
		List<SysDept> list = sysDeptMapper.selectByName(wmDaAgent.getGsmc());
		if (isSave) {
			if (SecurityUtils.getRoles().contains(3)) {
				if (list.size() == 0) {
					SysDept sysDept = new SysDept();
					sysDept.setName(wmDaAgent.getGsmc());
					sysDept.setTaxCode(wmDaAgent.getZjNumber());
					sysDept.setSubjectType(wmDaAgent.getSubjectType());
					sysDept.setLevel(3);
					sysDeptService.save(sysDept);
					wmDaAgent.setDeptId(String.valueOf(sysDept.getDeptId()));
					wmDaAgentMapper.updateById(wmDaAgent);
				} else {
					wmDaAgent.setDeptId(String.valueOf(list.get(0).getDeptId()));
					wmDaAgentMapper.updateById(wmDaAgent);
				}
				List<SysDeptRelation> newList = new ArrayList<>();
				SysDeptRelation sysDeptRelation = new SysDeptRelation();
				sysDeptRelation.setAncestor(SecurityUtils.getUser().getDeptId());
				sysDeptRelation.setDescendant(Integer.valueOf(wmDaAgent.getDeptId()));
				newList.add(sysDeptRelation);
				SysDeptRelation sysDeptRelation1 = new SysDeptRelation();
				sysDeptRelation1.setAncestor(Integer.valueOf(wmDaAgent.getDeptId()));
				sysDeptRelation1.setDescendant(Integer.valueOf(wmDaAgent.getDeptId()));
				newList.add(sysDeptRelation1);
				return sysDeptRelationService.saveBatch(newList);
			} else if (SecurityUtils.getRoles().contains(4)) {
				if (list.size() == 0) {
					SysDept sysDept = new SysDept();
					sysDept.setName(wmDaAgent.getGsmc());
					sysDept.setLevel(4);
					sysDept.setTaxCode(wmDaAgent.getZjNumber());
					sysDept.setSubjectType(wmDaAgent.getSubjectType());
					sysDeptService.save(sysDept);
					wmDaAgent.setDeptId(String.valueOf(sysDept.getDeptId()));
					wmDaAgentMapper.updateById(wmDaAgent);
				} else {
					wmDaAgent.setDeptId(String.valueOf(list.get(0).getDeptId()));
					wmDaAgentMapper.updateById(wmDaAgent);
				}
				List<SysDeptRelation> newList = new ArrayList<>();
				SysDeptRelation sysDeptRelation = new SysDeptRelation();
				sysDeptRelation.setAncestor(SecurityUtils.getUser().getDeptId());
				sysDeptRelation.setDescendant(Integer.valueOf(wmDaAgent.getDeptId()));
				newList.add(sysDeptRelation);
				SysDeptRelation sysDeptRelation1 = new SysDeptRelation();
				sysDeptRelation1.setAncestor(Integer.valueOf(wmDaAgent.getDeptId()));
				sysDeptRelation1.setDescendant(Integer.valueOf(wmDaAgent.getDeptId()));
				newList.add(sysDeptRelation1);
				return sysDeptRelationService.saveBatch(newList);
			}
		}
		return false;
	}

	@Override
	public IPage<WmDaAgent> listPage(Page page, WmDaAgent wmDaAgent) {
		QueryWrapper queryWrapper = Wrappers.query();
		if (null != wmDaAgent.getGsmc()) {
			queryWrapper.like("gsmc", wmDaAgent.getGsmc());
		}
		if (null != wmDaAgent.getZjNumber()) {
			queryWrapper.like("zj_number", wmDaAgent.getZjNumber());
		}
//		if(null!=wmDaAgent.getTemp2())
//		{
//			QueryWrapper queryWrapper1=Wrappers.query();
//			List<SysDept> sysDeptList=sysDeptService.list(queryWrapper1.eq(true,"level2_id",wmDaAgent.getTemp2()));
//			List<String> stringList=new ArrayList<>();
//			for (SysDept sysDept:sysDeptList) {
//				stringList.add(sysDept.getDeptId()+"");
//			}
//			queryWrapper.in("dept_id",stringList);
//		}
		if (SecurityUtils.getRoles().contains(4)) {
			wmDaAgent.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
			WmDaAgent wmDaAgent1 = wmDaAgentMapper.selectDeptId(wmDaAgent);
			WmRelation wmRelation = new WmRelation();
			if (wmDaAgent1 != null) {
				wmRelation.setUpId(Integer.parseInt(wmDaAgent1.getDeptId()));
			} else {
				wmRelation.setUpId(null);
			}
			List<WmRelation> taskList = wmRelationMapper.selectUpIdList(wmRelation);
			List<Integer> ids2 = taskList.stream().map(p -> p.getDownId()).collect(Collectors.toList());
			if (taskList.size() != 0) {
				List<WmDaAgent> newList = new ArrayList<>();
				for (Integer id : ids2) {
					WmDaAgent wmDaAgent3 = new WmDaAgent();
					wmDaAgent3.setDeptId(String.valueOf(id));
					WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectDeptId(wmDaAgent3);
					newList.add(wmDaAgent2);
				}
				queryWrapper.like("ext_drug_ent", newList.get(0).getExtDrugEnt());
				page.setRecords(newList);
			} else {
				return null;
			}
		} else if (SecurityUtils.getRoles().contains(3)) {
			WmRelation wmRelation = new WmRelation();
			wmRelation.setUpId(SecurityUtils.getUser().getDeptId());
			List<WmRelation> taskList = wmRelationMapper.selectUpIdList(wmRelation);
			List<Integer> ids2 = taskList.stream().map(p -> p.getDownId()).collect(Collectors.toList());
			if (taskList.size() != 0) {
				List<WmDaAgent> newList = new ArrayList<>();
				for (Integer id : ids2) {
					WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectById(id);
					newList.add(wmDaAgent2);
				}
				page.setRecords(newList);
			} else {
				return null;
			}
		}
		return wmDaAgentMapper.selectPageByScope(page, queryWrapper, new DataScope());

	}

	@Override
	public IPage selectWmManagementList(Page page, WmDaAgent wmDaAgent) {
//		OrderItem orderItem = new OrderItem();
//		orderItem.setColumn("create_time");
//		orderItem.setAsc(false);
//		page.addOrder(orderItem);
		QueryWrapper queryWrapper = Wrappers.query();
		if (null != wmDaAgent.getGsmc()) {
			queryWrapper.like("gsmc", wmDaAgent.getGsmc());
		}
		if (null != wmDaAgent.getZjNumber()) {
			queryWrapper.like("zjNamber", wmDaAgent.getZjNumber());
		}
//		List<WmDaAgent> wmDaAgentList = wmDaAgentMapper.selectWmManagementList(wmDaAgent);
//		List<String> ids = wmDaAgentList.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
//		List<SysDept> sysDeptList = new ArrayList<>();
//		for (String id : ids) {
//			SysDept sysDept = sysDeptService.getById(id);
//			if (sysDept != null) {
//				sysDeptList.add(sysDept);
//			}
//		}
//		List<Integer> deptList = sysDeptList.stream().filter(task -> 3 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());
//		List<Integer> deptList1 = sysDeptList.stream().filter(task -> 5 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());
//		List<SysDept> sysDeptList1 = new ArrayList<>();
//		for (Integer id : deptList) {
//			SysDept sysDept = sysDeptService.getById(id);
//			sysDeptList1.add(sysDept);
//		}
//		for (Integer id : deptList1) {
//			SysDept sysDept = sysDeptService.getById(id);
//			sysDeptList1.add(sysDept);
//		}
//		List<Integer> ids1 = sysDeptList1.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
//		List<WmDaAgent> wmDaAgentList1 = new ArrayList<>();
//		for (Integer id : ids1) {
//			WmDaAgent wmDaAgent1 = new WmDaAgent();
//			wmDaAgent1.setDeptId(String.valueOf(id));
//			WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectDeptId(wmDaAgent1);
//			wmDaAgentList1.add(wmDaAgent2);
//		}
//		Page<WmDaAgent> page1 = new Page<>();
//		int current = new Long(page.getCurrent()).intValue();
//		int size = new Long(page.getSize()).intValue();
//
//		int count = wmDaAgentList1.size();
//		List<WmDaAgent> pageList = new ArrayList<>();
//		//计算当前页第一条数据的下标
//		int currId = current > 1 ? (current - 1) * size : 0;
//		for (int i = 0; i < size && i < count - currId; i++) {
//			pageList.add(wmDaAgentList1.get(currId + i));
//		}
//		page1.setSize(size);
//		page1.setCurrent(current);
//		page1.setTotal(count);
//		//计算分页总页数
//		page1.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
//		page1.setRecords(pageList);
		return wmDaAgentMapper.selectWmManagementPage(page, wmDaAgent);
	}

	@Override
	public R insert(WmDaAgent wmDaAgent) {
		WmDaAgent query = new WmDaAgent();
		query.setGsmc(wmDaAgent.getGsmc());
		List<WmDaAgent> list1 = wmDaAgentMapper.selectList(Wrappers.query(query));
		WmDaAgent wmDaAgent1 = new WmDaAgent();
		wmDaAgent1.setZjNumber(wmDaAgent.getZjNumber());
		List<WmDaAgent> list2 = wmDaAgentMapper.selectList(Wrappers.query(wmDaAgent1));

		if (list1.size() > 0) {
			return R.failed("企业名称已存在");
		}
		if (list2.size() > 0) {
			return R.failed("统一社会信用代码已经存在");
		}
		wmDaAgent.setTenantId(1);
		wmDaAgent.setDelFlag(0 + "");
		wmDaAgent.setCreateTime(LocalDateTime.now());
		List<WmDaDrugEnt> listEnts = new ArrayList<>();
		if (wmDaAgent.getExtDrugEnt() != null) {
			String[] ents = wmDaAgent.getExtDrugEnt().split(",");
			listEnts = wmDaDrugEntService.listByIds(Arrays.asList(ents));
		}
		List<String> ids = listEnts.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
		String temp1 = "";
		if (listEnts.size() > 0) {
			for (WmDaDrugEnt wmD : listEnts) {
				temp1 += wmD.getEntname() + ",";
			}
			temp1 = temp1.substring(0, temp1.length() - 1);
		}
		wmDaAgent.setTemp1(temp1);
		wmDaAgent.setCreateTime(LocalDateTime.now());
		wmDaAgent.setManagement(String.valueOf(1));
		wmDaAgent.setPgqx(1 + "");
		super.save(wmDaAgent);
		List<SysDept> list3 = sysDeptMapper.selectByName(wmDaAgent.getGsmc());
		if (list3.size() == 0) {
			SysDept sysDept = new SysDept();/**
			 * @Modify: start
			 * @Version: 2021.4.16
			 * @Author: ryz
			 * @Date: 2021/4/20
			 */

			sysDept.setTaxCode(wmDaAgent.getZjNumber());
			sysDept.setSubjectType(wmDaAgent.getSubjectType());
			sysDept.setDeptPermissions(wmDaAgent.getDeptPermissions());
			if (wmDaAgent.getQylx().contains("0")) {
				sysDept.setName(wmDaAgent.getGsmc());
				sysDept.setLevel(3);
				sysDeptService.save(sysDept);
			} else {
				sysDept.setName(wmDaAgent.getGsmc());
				sysDept.setLevel(5);
				sysDeptService.save(sysDept);
			}

			for (String subType : wmDaAgent.getSubjectType()) {
				SysDeptSub deptSub = new SysDeptSub();
				deptSub.setDeptId(sysDept.getDeptId());
				deptSub.setSubjectType(subType);
				deptSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
				sysDeptSubMapper.insert(deptSub);
			}
			/**
			 * @Modify: end
			*/


			wmDaAgent.setDeptId(String.valueOf(sysDept.getDeptId()));
			List<WmDaDrugEnt> newList1 = new ArrayList<>();
			for (String id : ids) {
				WmDaDrugEnt wmDaDrugEnt = new WmDaDrugEnt();
				wmDaDrugEnt.setDeptId(id);
				WmDaDrugEnt wmDaDrugEnt1 = wmDaDrugEntMapper.selectDeptId(wmDaDrugEnt);
				newList1.add(wmDaDrugEnt1);
			}
			List<String> ids2 = newList1.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
			List<SysDeptRelation> newList2 = new ArrayList<>();
			for (String id : ids2) {
				SysDeptRelation sysDeptRelation = new SysDeptRelation();
				sysDeptRelation.setAncestor(Integer.parseInt(id));
				sysDeptRelation.setDescendant(sysDept.getDeptId());
				newList2.add(sysDeptRelation);
			}
			SysDeptRelation sysDeptRelation = new SysDeptRelation();
			sysDeptRelation.setAncestor(sysDept.getDeptId());
			sysDeptRelation.setDescendant(sysDept.getDeptId());
			newList2.add(sysDeptRelation);
			sysDeptRelationService.saveBatch(newList2);
		} else {
			wmDaAgent.setDeptId(String.valueOf(list3.get(0).getDeptId()));
			List<WmDaDrugEnt> newList1 = new ArrayList<>();
			for (String id : ids) {
				WmDaDrugEnt wmDaDrugEnt = new WmDaDrugEnt();
				wmDaDrugEnt.setDeptId(id);
				WmDaDrugEnt wmDaDrugEnt1 = wmDaDrugEntMapper.selectDeptId(wmDaDrugEnt);
				newList1.add(wmDaDrugEnt1);
			}
			List<String> ids2 = newList1.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
			List<SysDeptRelation> newList2 = new ArrayList<>();
			for (String id : ids2) {
				SysDeptRelation sysDeptRelation = new SysDeptRelation();
				sysDeptRelation.setAncestor(Integer.parseInt(id));
				sysDeptRelation.setDescendant(list3.get(0).getDeptId());
				newList2.add(sysDeptRelation);
			}
			SysDeptRelation sysDeptRelation = new SysDeptRelation();
			sysDeptRelation.setAncestor(list3.get(0).getDeptId());
			sysDeptRelation.setDescendant(list3.get(0).getDeptId());
			newList2.add(sysDeptRelation);
			sysDeptRelationService.saveBatch(newList2);
		}
		this.updateById(wmDaAgent);
		List<WmRelation> newList = new ArrayList<>();
		for (String upId : ids) {
			WmRelation wmRelation = new WmRelation();
			wmRelation.setUpId(Integer.parseInt(upId));
			wmRelation.setDownId(Integer.parseInt(wmDaAgent.getDeptId()));
			newList.add(wmRelation);
		}
		wmRelationService.saveBatch(newList);
		if (wmDaAgent.getQylx().equals("0")) {
			WmTaskTypeEntRef wmTaskTypeEntRef = new WmTaskTypeEntRef();
			wmTaskTypeEntRef.setAgentId(wmDaAgent.getId());
			wmTaskTypeEntRef.setDrugentId("");
			WmTaskType wmTaskType = new WmTaskType();
			wmTaskType.setDurgentId(wmDaAgent.getDrugEntId());
			wmTaskType.setLevel1Id(wmDaAgent.getId());
			wmTaskType.setDelFlag("0");
			List<WmTaskType> list = wmTaskTypeMapper.selectList(Wrappers.query(wmTaskType));
			if (list.size() > 0) {
				return R.failed("一代积分规则已分配");
			} else {
				if (null != wmDaAgent) {
					wmTaskTypeEntRef.setDeptId(wmDaAgent.getDeptId());
				}
				int isSave = wmTaskTypeEntRefMapper.insert(wmTaskTypeEntRef);

				WmTaskType wmTaskTypeQ = new WmTaskType();
				wmTaskTypeQ.setTaskTypeLevel("1");
				wmTaskTypeQ.setStatus("0");
				wmTaskTypeQ.setDelFlag("0");

				List<WmTaskType> tempList = wmTaskTypeMapper.selectList(Wrappers.query(wmTaskTypeQ));

				for (WmTaskType wmTaskType1 : tempList) {
					WmTaskType newOne = wmTaskType1;
					newOne.setId(null);
					newOne.setLevel1Id(wmTaskTypeEntRef.getAgentId());
					newOne.setTaskTypeLevel("2");
					newOne.setTaskEntId(wmTaskTypeEntRef.getAgentId());
					newOne.setRuleId(wmTaskTypeEntRef.getAgentId());
					newOne.setDeptId(wmDaAgent.getDeptId() + "");
					newOne.setCreateTime(LocalDateTime.now());
					newOne.setStatus("0");
					newOne.setBaseId(wmTaskType1.getId());
					wmTaskTypeMapper.insert(newOne);
				}
			}
		}
		return R.ok();
	}

	@Override
	public R updateByPrimaryKeySelective(WmDaAgent wmDaAgent) {
		WmDaAgent query = new WmDaAgent();
		query.setGsmc(wmDaAgent.getGsmc());
		List<WmDaAgent> list1 = wmDaAgentMapper.selectList(Wrappers.query(query));

		if (list1.size() > 1) {
			return R.failed("企业名称已存在");
		}
		wmDaAgent.setUpdateTime(LocalDateTime.now());

		List<WmDaAgent> agentList = new ArrayList<>();
		if (wmDaAgent.getDeptLevel() != null && wmDaAgent.getDeptLevel().equals(4)) {
			// 如果是4-二级代理商，则根据extDrugEnt查询代理商列表
			if (StringUtils.isNotBlank(wmDaAgent.getExtDrugEnt())) {
				String[] ents = wmDaAgent.getExtDrugEnt().split(",");
				agentList = this.listByIds(Arrays.asList(ents));
				if (CollectionUtil.isNotEmpty(agentList)) {
					List<String> gsmcList = agentList.stream().map(WmDaAgent::getGsmc).collect(Collectors.toList());
					wmDaAgent.setTemp1(String.join(",", gsmcList));
				}
			}
		} else if (wmDaAgent.getQylx().equals("0")) {
			if (null != wmDaAgent.getExtDrugEnt()) {
				String[] ents = wmDaAgent.getExtDrugEnt().split(",");
				List<WmDaDrugEnt> listEnts = wmDaDrugEntService.listByIds(Arrays.asList(ents));
				String temp1 = "";
				if (listEnts.size() > 0) {
					for (WmDaDrugEnt wmD : listEnts) {
						temp1 += wmD.getEntname() + ",";
					}
					temp1 = temp1.substring(0, temp1.length() - 1);
				}
				wmDaAgent.setTemp1(temp1);
			}
		}
		List<WmDaDrugEnt> listEnts = new ArrayList<>();
		if (wmDaAgent.getExtDrugEnt() != null) {
			String[] ents = wmDaAgent.getExtDrugEnt().split(",");
			listEnts = wmDaDrugEntService.listByIds(Arrays.asList(ents));
		} else {
			wmDaAgent.setExtDrugEnt("");
			wmDaAgent.setTemp1("");
		}

		// 关联上级(上级可能是药企的情况，也可能是代理商的情况)
		// 药企或代理商id
		List<String> ids = null;
		// 对应的部门id
		List<String> deptIds = null;
		if (CollectionUtil.isNotEmpty(agentList)) {
			ids = agentList.stream().map(WmDaAgent::getId).collect(Collectors.toList());
			deptIds = agentList.stream().map(WmDaAgent::getDeptId).collect(Collectors.toList());
		} else {
			ids = listEnts.stream().map(p -> p.getId()).collect(Collectors.toList());
			deptIds = listEnts.stream().map(WmDaDrugEnt::getDeptId).collect(Collectors.toList());
		}
		List<WmRelation> newList = new ArrayList<>();
//		List<WmDaDrugEnt> newList1 = new ArrayList<>();
		List<SysDeptRelation> newList2 = new ArrayList<>();

		WmDaAgent wmDaAgent1 = wmDaAgentMapper.selectOne(Wrappers.query(query));
		for (String upId : ids) {
			WmRelation wmRelation = new WmRelation();
			wmRelation.setUpId(Integer.parseInt(upId));
			wmRelation.setDownId(Integer.parseInt(wmDaAgent1.getId()));
			newList.add(wmRelation);
			wmRelationMapper.deleteByPrimaryKey(Long.valueOf(wmRelation.getDownId()));
		}
		wmRelationService.saveBatch(newList);

		for (String id : deptIds) {
			SysDeptRelation sysDeptRelation = new SysDeptRelation();
			sysDeptRelation.setAncestor(Integer.parseInt(id));
			sysDeptRelation.setDescendant(Integer.parseInt(wmDaAgent.getDeptId()));
			newList2.add(sysDeptRelation);
		}
		sysDeptRelationMapper.deleteByPrimaryKey(Long.valueOf(wmDaAgent.getDeptId()));
		SysDeptRelation sysDeptRelation = new SysDeptRelation();
		sysDeptRelation.setAncestor(Integer.parseInt(wmDaAgent.getDeptId()));
		sysDeptRelation.setDescendant(Integer.parseInt(wmDaAgent.getDeptId()));
		if (!newList2.contains(sysDeptRelation)) {
			newList2.add(sysDeptRelation);
		}
		sysDeptRelationService.saveBatch(newList2);

		wmDaAgentMapper.updateById(wmDaAgent);
		SysDept sysDept1 = new SysDept();
		sysDept1.setDeptId(Integer.parseInt(wmDaAgent.getDeptId()));
		SysDept sysDept = sysDeptMapper.selectDept(sysDept1);
		sysDept.setDelFlag(wmDaAgent.getEnableFlag());
		sysDept.setName(wmDaAgent.getGsmc());
		sysDept.setDeptId(Integer.parseInt(wmDaAgent.getDeptId()));
//		sysDept.setSubjectType(wmDaAgent.getSubjectType());

		/**
		 * @Modify: start
		 * @Author: ryz
		 * @Date: 2021/4/19
		 */
		sysDept.setTaxCode(wmDaAgent.getZjNumber());

		if(!Arrays.equals(sysDept.getSubjectType(),wmDaAgent.getSubjectType())){

			sysDeptSubMapper.update(new SysDeptSub(), Wrappers.<SysDeptSub>lambdaUpdate()
					.eq(SysDeptSub::getDeptId,sysDept.getDeptId())
					.set(SysDeptSub::getEnableFlag, SubjectTypeEnum.ENABLE_FLAG_FALSE.getCode()));

			for (String subType : wmDaAgent.getSubjectType()) {
				SysDeptSub condition = new SysDeptSub();
				condition.setDeptId(sysDept.getDeptId());
				condition.setSubjectType(subType);
				SysDeptSub existSub = sysDeptSubMapper.selectOne(Wrappers.query(condition));
				if(null != existSub){
					existSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
					sysDeptSubMapper.updateById(existSub);
				}else {
					existSub = new SysDeptSub();
					existSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
					existSub.setDeptId(sysDept.getDeptId());
					existSub.setSubjectType(subType);
					sysDeptSubMapper.insert(existSub);
				}
			}

		}
		/**
		 * @Modify: end
		 */
		sysDept.setSubjectType(wmDaAgent.getSubjectType());
		sysDept.setDeptPermissions(wmDaAgent.getDeptPermissions());
		sysDeptMapper.updateByPrimaryKeySelective(sysDept);
		SysUser sysUser1 = new SysUser();
		sysUser1.setDeptId(Integer.parseInt(wmDaAgent.getDeptId()));
		List<SysUser> sysUserList = sysUserMapper.selectUserById(sysUser1);
		List<Integer> id1 = sysUserList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
		for (Integer id : id1) {
			SysUser sysUser = new SysUser();
			sysUser.setUserId(id);
			sysUser.setDelFlag(wmDaAgent.getEnableFlag());
			sysUserMapper.updateByPrimaryKeySelective(sysUser);
		}
		return R.ok();
	}

	@Override
	public WmDaAgent selectDeptId(WmDaAgent wmDaAgent) {
		wmDaAgent.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
		return wmDaAgentMapper.selectDeptId(wmDaAgent);
	}

	@Override
	public List<Map<String, String>> selectDeptId1() {
		if (SecurityUtils.getRoles().contains(3)) {
			WmDaDrugEnt wmDaDrugEnt = new WmDaDrugEnt();
			wmDaDrugEnt.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
			List<Map<String, String>> map1 = wmDaDrugEntMapper.selectDeptId1(wmDaDrugEnt);
			return map1;
		} else if (SecurityUtils.getRoles().contains(4)) {
			WmDaAgent wmDaAgent = new WmDaAgent();
			wmDaAgent.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
			List<Map<String, String>> map1 = wmDaAgentMapper.selectDeptId1(wmDaAgent);
			return map1;
		}
		return null;
	}

	@Override
	public List selectWmDaDrugEntByDeptId(Integer deptId) {
		return wmDaAgentMapper.selectWmDaDrugEntByDeptId(deptId);
	}

	@Override
	public List selectWmDaDrugEntByDeptIds(Integer deptId) {
		return wmDaAgentMapper.selectWmDaDrugEntByDeptIds(deptId);
	}

	@Override
	public List selectWmDaAgentByRelationId(Integer deptId) {
		return wmDaAgentMapper.selectWmDaAgentByRelationId(deptId);
	}

	@Override
	public List selectWmDaAgentByRelationIds(Integer deptId) {
		return wmDaAgentMapper.selectWmDaAgentByRelationIds(deptId);
	}

	@Override
	public List selectWmDaAgentByDeptId(String deptId) {
		return wmDaAgentMapper.selectWmDaAgentByDeptId(deptId);
	}

	@Override
	public List selectWmDaAgentByDeptIds(String deptId) {
		return wmDaAgentMapper.selectWmDaAgentByDeptIds(deptId);
	}


	@Override
	public WmDaAgent selectByDeptId(Integer deptId) {
		return wmDaAgentMapper.selectByDeptIds(deptId);
	}

	@Override
	public List selectByDrugIds(Integer id) {
		return wmDaAgentMapper.selectByDrugIds(id);
	}

	@Override
	public List selectByRelationId(Integer id) {
		return wmDaAgentMapper.selectByRelationId(id);
	}

	@Override
	public List selectByRelationIds(Integer id) {
		return wmDaAgentMapper.selectByRelationIds(id);
	}

	@Override
	public List selectByDrugId(Integer id) {
		return wmDaAgentMapper.selectByDrugId(id);
	}

	@Override
	public List selectEntNameByDrugIds(Integer id) {
		return wmDaAgentMapper.selectEntNameByDrugIds(id);
	}

	@Override
	public List listByDept() {
		List<WmDept> wmDeptList = new ArrayList<>();
//		if(SecurityUtils.getRoles().contains(9)){
//			WmDept wmDept = new WmDept();
//			SysDept sysDept = sysDeptMapper.selectById(SecurityUtils.getUser().getDeptId());
//			wmDept.setDeptId(sysDept.getDeptId());
//			wmDept.setName(sysDept.getName());
//			wmDeptList.add(wmDept);
//			return wmDeptList;
//		}
		if (SecurityUtils.getRoles().contains(1) || SecurityUtils.getRoles().contains(2)) {
			SysDept sysDept = new SysDept();
			List<SysDept> sysDeptList = sysDeptMapper.selectListByDept(sysDept);
			for (int i = 0; i < sysDeptList.size(); i++) {
				WmDept wmDept = new WmDept();
				wmDept.setDeptId(Integer.parseInt(String.valueOf(sysDeptList.get(i).getDeptId())));
				wmDept.setName(sysDeptList.get(i).getName());
				wmDeptList.add(wmDept);
			}
			return wmDeptList;
		} else {
			SysDeptRelation sysDeptRelation = new SysDeptRelation();
			sysDeptRelation.setAncestor(SecurityUtils.getUser().getDeptId());
			List<SysDeptRelation> sysDeptRelationList = sysDeptRelationMapper.selectDeptRelationsList(sysDeptRelation);
			List<WmDaAgent> wmDaAgentList = new ArrayList<>();
			List<WmDaDrugEnt> wmDaDrugEntList = new ArrayList<>();
			List<SysDept> sysDeptList = new ArrayList<>();
			if (sysDeptRelationList.size() > 0) {
				List<Integer> ids = sysDeptRelationList.stream().map(p -> p.getDescendant()).collect(Collectors.toList());
				for (Integer id : ids) {
					SysDept sysDept = sysDeptService.getById(id);
					if (null != sysDept) {
						sysDeptList.add(sysDept);
					}
				}
				List<Integer> ids1 = sysDeptList.stream().filter(task -> 2 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());
				List<Integer> ids2 = sysDeptList.stream().filter(task -> 3 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());
				List<Integer> ids3 = sysDeptList.stream().filter(task -> 4 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());
				List<Integer> ids4 = sysDeptList.stream().filter(task -> 5 == task.getLevel()).map(p -> p.getDeptId()).collect(Collectors.toList());

				for (Integer id : ids1) {
					WmDaDrugEnt wmDaDrugEnt1 = wmDaDrugEntMapper.selectByDeptId(id);
					if (Integer.parseInt(wmDaDrugEnt1.getEnableFlag()) == 0) {
						wmDaDrugEntList.add(wmDaDrugEnt1);
					}
				}
				WmDaAgent wmDaAgent1 = new WmDaAgent();
				for (Integer id : ids2) {
					wmDaAgent1.setDeptId(String.valueOf(id));
					WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectByDeptId(wmDaAgent1);
					if (Integer.parseInt(wmDaAgent2.getEnableFlag()) == 0) {
						wmDaAgentList.add(wmDaAgent2);
					}
				}
				for (Integer id : ids3) {
					wmDaAgent1.setDeptId(String.valueOf(id));
					WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectByDeptId(wmDaAgent1);
					if (Integer.parseInt(wmDaAgent2.getEnableFlag()) == 0) {
						wmDaAgentList.add(wmDaAgent2);
					}
				}
				for (Integer id : ids4) {
					wmDaAgent1.setDeptId(String.valueOf(id));
					WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectByDeptId(wmDaAgent1);
					if (Integer.parseInt(wmDaAgent2.getEnableFlag()) == 0) {
						wmDaAgentList.add(wmDaAgent2);
					}
				}
				for (int i = 0; i < wmDaDrugEntList.size(); i++) {
					WmDept wmDept = new WmDept();
					wmDept.setDeptId(Integer.parseInt(wmDaDrugEntList.get(i).getDeptId()));
					wmDept.setName(wmDaDrugEntList.get(i).getEntname());
					wmDeptList.add(wmDept);
				}
				for (int i = 0; i < wmDaAgentList.size(); i++) {
					WmDept wmDept = new WmDept();
					wmDept.setDeptId(Integer.parseInt(wmDaAgentList.get(i).getDeptId()));
					wmDept.setName(wmDaAgentList.get(i).getGsmc());
					wmDeptList.add(wmDept);
				}
			}
			return wmDeptList;
		}
	}

	@Override
	public List selectNameByDeptId(Integer deptId) {
//		SysDept sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept deptIds = sysDeptMapper.selectDeptId(sysDept1);
		SysDept deptIds = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		List wmDaDrugEnts = null;
		if (deptIds.getLevel() == 2) {
			wmDaDrugEnts = wmDaDrugEntMapper.selectByUserDeptId(SecurityUtils.getUser().getDeptId());
		} else if (deptIds.getLevel() == 3 || deptIds.getLevel() == 4) {
			wmDaDrugEnts = wmDaAgentMapper.selectByUserDeptId(SecurityUtils.getUser().getDeptId());
		}
		return wmDaDrugEnts;
	}

	@Override
	public int updateUserByDeptId(WmDaAgent wmDaAgent) {
//		SysDept sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept deptIds = sysDeptMapper.selectDeptId(sysDept1);
		SysDept deptIds = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		WmDaDrugEnt wmDaDrugEnt = new WmDaDrugEnt();
		Integer wmDaDrugEnts = null;
		if (deptIds.getLevel() == 2) {
			deptIds.setName(wmDaAgent.getGsmc());
			sysDeptService.updateById(deptIds);
			wmDaDrugEnt.setId(wmDaAgent.getId());
			wmDaDrugEnt.setEntname(wmDaAgent.getGsmc());
			wmDaDrugEnt.setEntcode(wmDaAgent.getZjNumber());
			wmDaDrugEnt.setManagement(wmDaAgent.getManagement());
			wmDaDrugEnts = wmDaDrugEntMapper.updateById(wmDaDrugEnt);
		} else if (deptIds.getLevel() == 3 || deptIds.getLevel() == 4) {
			deptIds.setName(wmDaAgent.getGsmc());
			sysDeptService.updateById(deptIds);
			wmDaDrugEnts = wmDaAgentMapper.updateById(wmDaAgent);
		} else if (wmDaDrugEnts == null) {
			return -1;
		}
		return wmDaDrugEnts;
	}

	/**
	 * 根据sys_dept表的level字段查询
	 *
	 * @param deptLevel
	 * @return
	 */
	@Override
	public List<WmDaAgent> listAgentByDeptLevel(String deptLevel) {
		return wmDaAgentMapper.listAgentByDeptLevel(deptLevel);
	}

	/**
	 * 根据deptRelation查询
	 *
	 * @param deptId
	 * @return
	 */
	@Override
	public List<WmDaAgent> listAgentByDeptRelation(Integer deptId) {
		return wmDaAgentMapper.listAgentByDeptRelation(deptId);
	}
//	@Override
//	public List selectByCsoIds(Integer id) {
//		return wmDaAgentMapper.selectByCsoIds(id);
//	}


}
