/*
 *    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.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
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.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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


/**
 * 档案-代理商
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wmdaagent")
@Api(value = "wmdaagent", tags = "档案-代理商管理")
public class WmDaAgentController {

	private final WmDaAgentService wmDaAgentService;

	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmRelationService wmRelationService;
	private final WmDaDrugEntMapper wmDaDrugEntMapper;
	private final SysDeptService sysDeptService;
	private final SysUserMapper sysUserMapper;
	private final SysDeptMapper deptMapper;
	private final WmTaskTypeEntRefMapper wmTaskTypeEntRefMapper;
	private final WmTaskTypeMapper wmTaskTypeMapper;
	private final WmRelationMapper wmRelationMapper;
	private final WmDaAgentMapper wmDaAgentMapper;
	private final SysDeptRelationMapper sysDeptRelationMapper;
	private final SysDeptMapper sysDeptMapper;
	private final SysDeptRelationService sysDeptRelationService;

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param wmDaAgent 档案-代理商
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('admin_wmdaagent_view')" )
	public R getWmDaAgentPage(Page page, WmDaAgent wmDaAgent) {
//		if(SecurityUtils.getRoles().contains(1) ||SecurityUtils.getRoles().contains(2))
//		{
//			//管理员和平台管理员不做处理
//		}else{
////			wmDaAgent.setDrugEntId(SecurityUtils.getUser().getDrugEntId());
//		}
//
//		OrderItem orderItem=new OrderItem();
//		orderItem.setColumn("create_time");
//		orderItem.setAsc(false);
//		page.addOrder(orderItem);
//		IPage<WmDaAgent>  answerPage= wmDaAgentService.listPage(page, wmDaAgent);
//		if (answerPage != null) {
//			List<WmDaAgent>	list = answerPage.getRecords();
//			if (list.size() > 0) {
//				for (WmDaAgent wmd : list) {
////				wmd.setUpdateUser(getBuildName(wmd.getDeptId(),"agent"));
//					if (null != wmd.getExtDrugEnt()) {
//						String[] ents = wmd.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);
//						}
//						wmd.setTemp1(temp1);
//					}
//
//				}
//			}
//			answerPage.setRecords(list);
//		}

		WmRelation wmRelation = new WmRelation();
		wmRelation.setUpId(SecurityUtils.getUser().getDeptId());
		List<WmRelation> wmRelationList = wmRelationMapper.selectUpIdList(wmRelation);
		List<WmDaAgent> wmDaAgentList = new ArrayList<>();
		wmDaAgent.setDeptId(SecurityUtils.getUser().getDeptId() + "");
		WmDaAgent wmDaAgent3 = wmDaAgentMapper.selectDeptId(wmDaAgent);
		if (wmDaAgent3 != null) {
			wmDaAgentList.add(wmDaAgent3);
		}
		if (wmRelationList.size() > 0) {
			List<Integer> ids = wmRelationList.stream().map(p -> p.getDownId()).collect(Collectors.toList());

			for (Integer id : ids) {
				WmDaAgent wmDaAgent1 = new WmDaAgent();
				wmDaAgent1.setDeptId(String.valueOf(id));
				WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectDeptId(wmDaAgent1);
				wmDaAgentList.add(wmDaAgent2);
			}
		}
		//每页数据条数
		Page<WmDaAgent> page1 = new Page<>();
		int current = new Long(page.getCurrent()).intValue();
		int size = new Long(page.getSize()).intValue();

		int count = wmDaAgentList.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(wmDaAgentList.get(currId + i));
		}
		page1.setSize(size);
		page1.setCurrent(current);
		page1.setTotal(count);
		//计算分页总页数
		page1.setPages(count % size == 0 ? count / size : count / size + 1);
		page1.setRecords(pageList);
		return R.ok(page1);
	}


	/**
	 * 通过id查询档案-代理商
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
//    @PreAuthorize("@pms.hasPermission('admin_wmdaagent_view')" )
	public R getById(@PathVariable("id") Integer id) {
		return R.ok(wmDaAgentService.getById(id));
	}


	@ApiOperation(value = "派工企业管理-新增", notes = "派工企业管理-新增")
	@SysLog("派工企业管理-新增")
	@PostMapping("/insert")
	public R insert(@RequestBody WmDaAgent wmDaAgent) {
		return wmDaAgentService.insert(wmDaAgent);
	}

	/**
	 * 新CSO管理-新增
	 *
	 * @param wmDaAgent CSO管理-新增
	 * @return R
	 */
	@ApiOperation(value = "CSO管理-新增", notes = "CSO管理-新增")
	@SysLog("CSO管理-新增")
	@PostMapping
	public R save(@RequestBody WmDaAgent wmDaAgent) {
		WmDaAgent query = new WmDaAgent();
		query.setGsmc(wmDaAgent.getGsmc());
		List<WmDaAgent> list1 = wmDaAgentService.list(Wrappers.query(query));
		WmDaAgent wmDaAgent4 = new WmDaAgent();
		wmDaAgent4.setZjNumber(wmDaAgent.getZjNumber());
		List<WmDaAgent> list5 = wmDaAgentMapper.selectList(Wrappers.query(wmDaAgent4));
		List<WmDaAgent> list3 = wmDaAgentMapper.selectByGsmcList(query);
		SysDeptRelation sysDeptRelation = new SysDeptRelation();
		if (list3.size() > 0) {
			sysDeptRelation.setAncestor(SecurityUtils.getUser().getDeptId());
			sysDeptRelation.setDescendant(Integer.parseInt(list3.get(0).getDeptId()));
		}
		List<SysDeptRelation> list4 = sysDeptRelationMapper.selectDeptRelation(sysDeptRelation);

		WmDaDrugEnt wmDaDrugEnt = new WmDaDrugEnt();
		wmDaDrugEnt.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
		WmDaDrugEnt wmDaDrugEnt1 = wmDaDrugEntMapper.selectDeptId(wmDaDrugEnt);
		if (list1.size() > 0 && list4.size() > 0) {
			return R.failed("代理商名称及关系已存在");
		}
		if (list5.size() < 1 && list1.size() > 0) {
			return R.failed("企业名称已经存在");
		}
		if (list5.size() > 0 && list1.size() < 1) {
			return R.failed("统一社会信用代码已经存在");
		}
		if (list1.size() < 1 && list4.size() < 1) {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
			if (sysDept.getLevel() == 4) {
				return R.failed("组织机构选择二级代理商不能继续添加代理商");
			}
			wmDaAgent.setDeptId(String.valueOf(sysDept.getDeptId()));
			wmDaAgent.setTenantId(1);
			wmDaAgent.setQylx(0 + "");
			wmDaAgent.setManagement("1");
			wmDaAgent.setPgqx(1 + "");
			if (wmDaDrugEnt1 != null) {
				wmDaAgent.setTemp1(wmDaDrugEnt1.getEntname());
			}
			WmDaAgent wmDaAgent1 = new WmDaAgent();
			wmDaAgent1.setDeptId(String.valueOf(sysDept.getDeptId()));
			WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectByDeptId(wmDaAgent1);
			if (wmDaDrugEnt1 == null && wmDaAgent2 != null) {
				wmDaAgent.setTemp1(wmDaAgent2.getGsmc());
			}
			if (wmDaAgentService.saveAgent(wmDaAgent)) {
				WmRelation wmRelation = new WmRelation();
				wmRelation.setDownId(Integer.parseInt(wmDaAgent.getDeptId()));
				wmRelation.setUpId(SecurityUtils.getUser().getDeptId());
				List<WmRelation> list2 = wmRelationService.list(Wrappers.query(wmRelation));
				if (list2.size() == 0) {
					wmRelationMapper.insert(wmRelation);
				}
				if (2 == sysDept.getLevel()) {
					WmTaskTypeEntRef wmTaskTypeEntRef = new WmTaskTypeEntRef();
					wmTaskTypeEntRef.setDrugentId(wmDaDrugEnt1.getId());
					wmTaskTypeEntRef.setAgentId(wmDaAgent.getId());
					wmTaskTypeEntRef.setDeptId(wmDaAgent.getDeptId());
					WmTaskType wmTaskType = new WmTaskType();
					wmTaskType.setDurgentId(wmDaDrugEnt1.getId());
					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(list3.get(0).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.setDurgentId(wmDaDrugEnt1.getId());
							newOne.setTaskTypeLevel("2");
							newOne.setRuleId(wmTaskTypeEntRef.getDrugentId() + wmTaskTypeEntRef.getAgentId());
							newOne.setTaskEntId(wmTaskTypeEntRef.getAgentId());
							newOne.setDeptId(wmDaAgent.getDeptId() + "");
							newOne.setCreateTime(LocalDateTime.now());
							newOne.setStatus("0");
							newOne.setBaseId(wmTaskType1.getId());
							wmTaskTypeMapper.insert(newOne);
						}
					}
					WmTaskTypeEntRef wmTaskTypeEntRef1 = new WmTaskTypeEntRef();
					wmTaskTypeEntRef1.setDrugentId("");
					wmTaskTypeEntRef1.setAgentId(wmDaAgent.getId());
					wmTaskTypeEntRef1.setDeptId(wmDaAgent.getDeptId());
					WmTaskType wmTaskType1 = new WmTaskType();
					wmTaskType1.setDurgentId(wmDaDrugEnt1.getId());
					wmTaskType1.setLevel1Id(wmDaAgent.getId());
					wmTaskType1.setDelFlag("0");
//					if (null != wmDaAgent) {
//						wmTaskTypeEntRef1.setDeptId(list3.get(0).getDeptId());
//					}
					int isSave = wmTaskTypeEntRefMapper.insert(wmTaskTypeEntRef1);

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

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

					for (WmTaskType wmTaskType2 : tempList) {
						WmTaskType newOne = wmTaskType2;
						newOne.setId(null);
						newOne.setLevel1Id(wmTaskTypeEntRef1.getAgentId());
						newOne.setTaskTypeLevel("2");
						newOne.setTaskEntId(wmTaskTypeEntRef1.getAgentId());
						newOne.setRuleId(wmTaskTypeEntRef1.getAgentId());
						newOne.setDeptId(wmDaAgent.getDeptId() + "");
						newOne.setCreateTime(LocalDateTime.now());
						newOne.setStatus("0");
						newOne.setBaseId(wmTaskType2.getId());
						wmTaskTypeMapper.insert(newOne);
					}
				} else if (3 == sysDept.getLevel()) {
					// 一级cso给二级cso配置积分规则
					WmDaAgent level1DaAgent = wmDaAgentService.getOne(Wrappers.<WmDaAgent>lambdaQuery()
							.eq(WmDaAgent::getDeptId, SecurityUtils.getUser().getDeptId()));
					WmTaskTypeEntRef wmTaskTypeEntRef1 = new WmTaskTypeEntRef();
					wmTaskTypeEntRef1.setDrugentId("");
					wmTaskTypeEntRef1.setAgentId(wmDaAgent.getId());
					wmTaskTypeEntRef1.setDeptId(wmDaAgent.getDeptId());
					wmTaskTypeEntRefMapper.insert(wmTaskTypeEntRef1);

					WmTaskType wmTaskTypeQ = new WmTaskType();
					wmTaskTypeQ.setTaskTypeLevel("1");
					wmTaskTypeQ.setStatus("0");
					wmTaskTypeQ.setDelFlag("0");
					List<WmTaskType> tempList = wmTaskTypeMapper.selectList(Wrappers.query(wmTaskTypeQ));

					for (WmTaskType wmTaskType2 : tempList) {
						WmTaskType newOne = wmTaskType2;
						newOne.setId(null);
						newOne.setLevel1Id(level1DaAgent.getId());
						newOne.setTaskTypeLevel("2");
						newOne.setTaskEntId(wmDaAgent.getId());
						newOne.setRuleId(wmDaAgent.getId());
						newOne.setDeptId(String.valueOf(wmDaAgent.getDeptId()));
						newOne.setCreateTime(LocalDateTime.now());
						newOne.setStatus("0");
						newOne.setBaseId(wmTaskType2.getId());
						wmTaskTypeMapper.insert(newOne);
					}
				}
			}
		}
		if (list1.size() > 0 && list4.size() < 1 && list5.size() > 0) {
			SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
			SysDeptRelation sysDeptRelation1 = new SysDeptRelation();
			sysDeptRelation1.setAncestor(SecurityUtils.getUser().getDeptId());
			sysDeptRelation1.setDescendant(Integer.parseInt(list3.get(0).getDeptId()));
			sysDeptRelationService.save(sysDeptRelation1);
			WmRelation wmRelation = new WmRelation();
			wmRelation.setDownId(Integer.valueOf(list1.get(0).getDeptId()));
			if (wmDaDrugEnt1 != null) {
				wmRelation.setUpId(Integer.parseInt(wmDaDrugEnt1.getDeptId()));
			} else {
				WmDaAgent wmDaAgent1 = new WmDaAgent();
				wmDaAgent1.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
				WmDaAgent wmDaAgent2 = wmDaAgentMapper.selectDeptId(wmDaAgent1);
				wmRelation.setUpId(Integer.valueOf(wmDaAgent2.getDeptId()));
				WmDaAgent wmDaAgent3 = wmDaAgentMapper.selectByGsmc(query);
				wmDaAgent3.setExtDrugEnt(list1.get(0).getExtDrugEnt() + "," + wmDaAgent2.getId());
				wmDaAgent3.setTemp1(list1.get(0).getTemp1() + "," + wmDaAgent2.getGsmc());
				wmDaAgentMapper.updateById(wmDaAgent3);
			}
			List<WmRelation> list2 = wmRelationService.list(Wrappers.query(wmRelation));
			if (list2.size() == 0) {
				wmRelationMapper.insert(wmRelation);
			}
			if (2 == sysDept.getLevel()) {
				WmTaskTypeEntRef wmTaskTypeEntRef = new WmTaskTypeEntRef();
				wmTaskTypeEntRef.setDrugentId(wmDaDrugEnt1.getId());
				wmTaskTypeEntRef.setAgentId(list3.get(0).getId());
				wmTaskTypeEntRef.setDeptId(list3.get(0).getDeptId());
				WmDaAgent wmDaAgent1 = wmDaAgentMapper.selectByGsmc(query);
				wmDaAgent1.setExtDrugEnt(list1.get(0).getExtDrugEnt() + "," + wmDaDrugEnt1.getId());
				wmDaAgent1.setTemp1(list1.get(0).getTemp1() + "," + wmDaDrugEnt1.getEntname());
				wmDaAgentMapper.updateById(wmDaAgent1);
				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.setDurgentId(SecurityUtils.getUser().getDrugEntId());
					newOne.setTaskTypeLevel("2");
					newOne.setRuleId(wmTaskTypeEntRef.getDrugentId() + wmTaskTypeEntRef.getAgentId());
					newOne.setTaskEntId(wmTaskTypeEntRef.getAgentId());
					newOne.setDeptId(list3.get(0).getDeptId() + "");
					newOne.setCreateTime(LocalDateTime.now());
					newOne.setStatus("0");
					newOne.setBaseId(wmTaskType1.getId());
					wmTaskTypeMapper.insert(newOne);
				}
			}
		}

		return R.ok();
	}

	/**
	 * CSO管理-修改
	 *
	 * @param wmDaAgent
	 * @return R
	 */
	@ApiOperation(value = "CSO管理-修改", notes = "CSO管理-修改")
	@SysLog("CSO管理-修改")
	@PutMapping
	public R updateById(@RequestBody WmDaAgent 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()));

		/**
		* @Modify: start
		* @Author: ryz
		* @Date: 2021/4/20
		 * CSO管理 不能修改结算渠道
		 *
		*/
//		sysDept.setSubjectType(wmDaAgent.getSubjectType());
		sysDept.setTaxCode(wmDaAgent.getZjNumber());
		/**
		* @Modify: end
		*/
		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(wmDaAgentService.updateById(wmDaAgent));
	}

	/**
	 * 派工企业管理-修改
	 *
	 * @param wmDaAgent 档案-代理商
	 * @return R
	 */
	@ApiOperation(value = "派工企业管理-修改", notes = "派工企业管理-修改")
	@SysLog("派工企业管理-修改")
	@PutMapping("/update")
	public R update(@RequestBody WmDaAgent wmDaAgent) {
		return R.ok(wmDaAgentService.updateByPrimaryKeySelective(wmDaAgent));
	}


	/**
	 * 通过id删除档案-代理商
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除档案-代理商", notes = "通过id删除档案-代理商")
	@SysLog("通过id删除档案-代理商")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_wmdaagent_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(wmDaAgentService.removeById(id));
	}

	/**
	 * 查询服务上级组织列表
	 *
	 * @param deptLevel
	 * @return
	 */
	@GetMapping("/listDrugEntOrAgent")
	public R listDrugEntOrAgent(String deptLevel) {
		// 根据deptLevel（对应sys_dept的level字段）查询服务上级组织，deptLevel=4查询一级代理商，deptLevel=3和其他情况查询药企
		final List<Map<String, String>> result = new ArrayList<>();
		if ("4".equals(deptLevel)) {
			// 查询一级代理商
			List<WmDaAgent> daAgentList = wmDaAgentService.listAgentByDeptLevel("3");
			if (CollectionUtil.isNotEmpty(daAgentList)) {
				daAgentList.forEach(wmDaAgent -> {
					Map<String, String> agentMap = new HashMap<>();
					agentMap.put("value", wmDaAgent.getId());
					agentMap.put("name", wmDaAgent.getGsmc());
					result.add(agentMap);
				});
			}
		} else {
			// 查询药企
			Wrapper<WmDaDrugEnt> queryWrapper = Wrappers.<WmDaDrugEnt>lambdaQuery()
					.eq(WmDaDrugEnt::getDelFlag, DelEnum.NOT_DEL.val())
					.eq(WmDaDrugEnt::getEnableFlag, EnableEnum.ENABLE.val());
			List<WmDaDrugEnt> drugEntList = wmDaDrugEntService.list(queryWrapper);
			if (CollectionUtil.isNotEmpty(drugEntList)) {
				drugEntList.forEach(daDrugEnt -> {
					Map<String, String> agentMap = new HashMap<>();
					agentMap.put("value", daDrugEnt.getId());
					agentMap.put("name", daDrugEnt.getEntname());
					result.add(agentMap);
				});
			}
		}
		return R.ok(result);
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/list")
	public R listDrugEnt(WmDaAgent wmDaAgent, String agentTypeId) {
		List<String> stringList = new ArrayList<>();
		if (null != agentTypeId && null != SecurityUtils.getUser().getDrugEntId()) {
			SysDept sysDept = new SysDept();
			if (null != SecurityUtils.getUser().getDrugEntId() && !"".equals(SecurityUtils.getUser().getDrugEntId()) && !"null".equals(SecurityUtils.getUser().getDrugEntId())) {
				sysDept.setLevel1Id(Integer.parseInt(SecurityUtils.getUser().getDrugEntId()));
			}
			List<SysDept> sysDeptList = deptMapper.selectList(Wrappers.query(sysDept));
			if (sysDeptList.size() > 0) {
				for (SysDept sys :
						sysDeptList) {
					if ("1".equals(agentTypeId)) {
						if (null != sys.getLevel2Id()) {
							stringList.add(sys.getLevel2Id() + "");
						}
					} else if ("2".equals(agentTypeId)) {
						if (null != sys.getLevel3Id()) {
							stringList.add(sys.getLevel3Id() + "");
						}
					}

				}
			}
		}


		wmDaAgent.setDelFlag("0");
		wmDaAgent.setEnableFlag("0");
		List<WmDaAgent> listWmDaAgent = null;
		String gsmc = null;
		if (null != wmDaAgent.getGsmc()) {
			gsmc = wmDaAgent.getGsmc();
			wmDaAgent.setGsmc(null);
			if (stringList.size() > 0) {
				listWmDaAgent = wmDaAgentService.selectByScope(Wrappers.query(wmDaAgent).lambda().like(WmDaAgent::getGsmc, gsmc).in(WmDaAgent::getId, stringList));
			} else {
				listWmDaAgent = wmDaAgentService.selectByScope(Wrappers.query(wmDaAgent).lambda().like(WmDaAgent::getGsmc, gsmc));
			}
		} else {
			if (stringList.size() > 0) {
				listWmDaAgent = wmDaAgentService.selectByScope(Wrappers.query(wmDaAgent).lambda().in(WmDaAgent::getId, stringList));
			} else {
				listWmDaAgent = wmDaAgentService.selectByScope(Wrappers.query(wmDaAgent));
			}
		}
//
//		if(null!=agentTypeId)
//		{
//			if()
//		}


		return R.ok(listWmDaAgent);
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/listNoScope")
	public R listNoScope(WmDaAgent wmDaAgent, String agentTypeId) {
		List<String> stringList = new ArrayList<>();
		if (null != agentTypeId && null != SecurityUtils.getUser().getDrugEntId()) {
			SysDept sysDept = new SysDept();
			if (!SecurityUtils.getRoles().contains(2)) {
				if (null != SecurityUtils.getUser().getDrugEntId() && !"".equals(SecurityUtils.getUser().getDrugEntId()) && !"null".equals(SecurityUtils.getUser().getDrugEntId())) {
					sysDept.setLevel1Id(Integer.parseInt(SecurityUtils.getUser().getDrugEntId()));
				}
			}

			List<SysDept> sysDeptList = deptMapper.selectList(Wrappers.query(sysDept));
			if (sysDeptList.size() > 0) {
				for (SysDept sys :
						sysDeptList) {
					if ("1".equals(agentTypeId)) {
						if (null != sys.getLevel2Id()) {
							stringList.add(sys.getLevel2Id() + "");
						}
					} else if ("2".equals(agentTypeId)) {
						if (null != sys.getLevel3Id()) {
							stringList.add(sys.getLevel3Id() + "");
						}
					}

				}
			}
		}


		wmDaAgent.setDelFlag("0");
		wmDaAgent.setEnableFlag("0");
		List<WmDaAgent> listWmDaAgent = null;
		String gsmc = null;
		if (null != wmDaAgent.getGsmc()) {
			gsmc = wmDaAgent.getGsmc();
			wmDaAgent.setGsmc(null);
			if (stringList.size() > 0) {
				listWmDaAgent = wmDaAgentService.list(Wrappers.query(wmDaAgent).lambda().like(WmDaAgent::getGsmc, gsmc).in(WmDaAgent::getId, stringList));
			} else {
				listWmDaAgent = wmDaAgentService.list(Wrappers.query(wmDaAgent).lambda().like(WmDaAgent::getGsmc, gsmc));
			}
		} else {
			if (stringList.size() > 0) {
				listWmDaAgent = wmDaAgentService.list(Wrappers.query(wmDaAgent).lambda().in(WmDaAgent::getId, stringList));
			} else {
				listWmDaAgent = wmDaAgentService.list(Wrappers.query(wmDaAgent));
			}
		}
//
//		if(null!=agentTypeId)
//		{
//			if()
//		}


		return R.ok(listWmDaAgent);
	}


//	private String getBuildName(String deptId,String type)
//	{
//		SysDept sysDept=sysDeptService.getById(deptId);
//		String buildName="";
//		if("user".equals(type))
//		{
//
//		}else if("agent".equals(type))
//		{
//			if(null!=sysDept) {
//				sysDept = sysDeptService.getById(sysDept.getParentId());
//			}
//		}
//
//		if(null!=sysDept&&sysDept.getLevel()==3)
//		{
//
//			if(null!=sysDept.getLevel1Id()&&!"".equals(sysDept.getLevel1Id()))
//			{
//				WmDaDrugEnt wmDaDrugEnt=wmDaDrugEntService.getById(sysDept.getLevel1Id());
//				if(null!=wmDaDrugEnt)
//				{
//					if(!"".equals(buildName))
//					{
//						buildName=buildName+"-"+wmDaDrugEnt.getEntname();
//					}else{
//						buildName=wmDaDrugEnt.getEntname();
//					}
//				}
//			}
//
//
//			if(null!=sysDept.getLevel2Id()&&!"".equals(sysDept.getLevel2Id()))
//			{
//				WmDaAgent wmDaAgent=wmDaAgentService.getById(sysDept.getLevel2Id());
//				if(null!=wmDaAgent)
//				{
//					if(!"".equals(buildName))
//					{
//						buildName=buildName+"-"+wmDaAgent.getGsmc();
//					}else{
//						buildName=wmDaAgent.getGsmc();
//					}
//				}
//			}
//
//
//		}
//
//		if(null!=sysDept&&sysDept.getLevel()==2)
//		{
//			if(null!=sysDept.getLevel1Id()&&!"".equals(sysDept.getLevel1Id()))
//			{
//				WmDaDrugEnt wmDaDrugEnt=wmDaDrugEntService.getById(sysDept.getLevel1Id());
//				if(null!=wmDaDrugEnt)
//				{
//					if(!"".equals(buildName))
//					{
//						buildName=buildName+"-"+wmDaDrugEnt.getEntname();
//					}else{
//						buildName=wmDaDrugEnt.getEntname();
//					}
//				}
//			}
//		}
//
//		return  buildName;
//	}

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param wmDaAgent 档案-代理商
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page1")
	public R getWmDaAgentPage1(Page page, WmDaAgent wmDaAgent) {
		return R.ok(wmDaAgentService.selectWmManagementList(page, wmDaAgent));
	}

	@ApiOperation(value = "查询档案-代理商", notes = "查询档案-代理商")
	@SysLog("查询档案-代理商")
	@GetMapping("/selectExtDrugEnt")
	public List selectExtDrugEnt() {
		return wmDaAgentService.selectDeptId1();
	}

	/**
	 * 获取cso列表
	 *
	 * @return cso列表 二期  业务平台
	 */
	@GetMapping("/listCso")
	public R listCso(Integer id) {
//		SysDept sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept sysDept = sysDeptMapper.selectDeptId(sysDept1);

		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		WmDaAgent anId = wmDaAgentService.selectByDeptId(sysDept.getDeptId());
		WmDaDrugEnt drId = wmDaDrugEntService.selectByDeptId(sysDept.getDeptId());
		List wmDaDrugEnts = null;
		if (sysDept.getLevel() == 2) {
			wmDaDrugEnts = wmDaAgentService.selectWmDaDrugEntByDeptId(sysDept.getDeptId());
		} else if (sysDept.getLevel() == 3) {
			wmDaDrugEnts = wmDaAgentService.selectWmDaDrugEntByDeptIds(sysDept.getDeptId());
		}
		return R.ok(wmDaDrugEnts);
	}

	/**
	 * 获取cso列表
	 *
	 * @return cso列表 二期  业务平台
	 */
	@GetMapping("/getCso")
	public R getCso(Integer id) {
//		SysDept sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept byId = sysDeptMapper.selectDeptId(sysDept1);

		SysDept byId = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		WmDaAgent anId = wmDaAgentService.selectByDeptId(byId.getDeptId());
		WmDaDrugEnt drId = wmDaDrugEntService.selectByDeptId(byId.getDeptId());
		List wmDaDrugEnts = null;
		if (byId.getLevel() == 2) {
			wmDaDrugEnts = wmDaAgentService.selectWmDaDrugEntByDeptId(byId.getDeptId());
		} else if (byId.getLevel() == 3 || byId.getLevel() == 4) {
			wmDaDrugEnts = wmDaAgentService.selectWmDaAgentByRelationId(byId.getDeptId());
		}
		return R.ok(wmDaDrugEnts);
	}

	/**
	 * 获取关联服务企业
	 *
	 * @return 关联服务企业 二期  业务平台
	 */
	@GetMapping("/listCsoById")
	public R listCsoById(WmScorePackage wmScorePackage) {
//		SysDept sysDept1 = new SysDept();
//		sysDept1.setDeptId(SecurityUtils.getUser().getDeptId());
//		SysDept byId = sysDeptMapper.selectDeptId(sysDept1);

		SysDept byId = sysDeptService.getById(SecurityUtils.getUser().getDeptId());

		List wmDaDrugEnts = null;
		//只有药企
		if (byId.getLevel() == 2) {
//			WmDaDrugEnt wmDaDrugEnt = wmDaDrugEntService.selectByDeptId(byId.getDeptId());
			wmDaDrugEnts = wmDaDrugEntService.selectEntNameByDeptId(byId.getDeptId());
		} else if (byId.getLevel() == 3) {
//			WmDaAgent anId = wmDaAgentService.selectByDeptId(byId.getDeptId());
			List<WmRelation> wmRelation = wmRelationMapper.selectByUpId(byId.getDeptId());
			if (CollectionUtil.isEmpty(wmRelation)) {
				// 如果为空，则直接返回当前自己的
				wmDaDrugEnts = wmDaDrugEntService.selectEntNameByByDeptIds(byId.getDeptId());
			} else {
				//获取上级药企和cso自己
				for (WmRelation wmRelation1 : wmRelation) {
					wmDaDrugEnts = wmDaDrugEntService.selectEntNameByByDeptIds(wmRelation1.getDownId());
//				wmDaDrugEnts = wmDaDrugEntService.selectEntNameByDeptId(byId.getDeptId());
				}
			}
		}
		return R.ok(wmDaDrugEnts);
	}

	/**
	 * 通过用户deptId查询用户信息
	 */
	@PostMapping("/getUserDeptId")
	public R getUserDeptId(Integer deptId) {
		return R.ok(wmDaAgentService.selectNameByDeptId(deptId));
	}

	/**
	 * 通过用户deptId修改用户信息
	 */
	@PostMapping("/updateUserByDeptId")
	public R updateUserByDeptId(@RequestBody WmDaAgent wmDaAgent) {
		return R.ok(wmDaAgentService.updateUserByDeptId(wmDaAgent));
	}

	/**
	 * 查询组织架构
	 */
	@GetMapping("/listByDept")
	public R listByDept() {

		return R.ok(wmDaAgentService.listByDept());
	}
}
