/*
 *
 *      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.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.dto.DeptTree;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDeptRelation;
import com.qunzhixinxi.hnqz.admin.api.vo.TreeUtil;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptRelationMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmRelationMapper;
import com.qunzhixinxi.hnqz.admin.service.SysDeptRelationService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.common.data.datascope.DataScope;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author hnqz
 * @since 2018-01-20
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

	private final SysDeptRelationService sysDeptRelationService;

	private final WmRelationMapper wmRelationMapper;

	private final SysDeptRelationMapper sysDeptRelationMapper;

	private final SysDeptMapper deptMapper;

	@Override
	public List convertToName() {
		return deptMapper.getDeptConvertToName();
	}

	@Override
	public List getChildDept(SysDept sysDept) {
		return deptMapper.getChildDept(sysDept);
	}

	@Override
	public List getParentDept(SysDept sysDept) {
		return deptMapper.getParentDept(sysDept);
	}

	@Override
	public SysDept selectByDeptId(Integer deptId) {
		SysDept sysDept1 = new SysDept();
		sysDept1.setDeptId(deptId);
		return deptMapper.selectDistinctDeptId(sysDept1);
	}

	@Override
	public List<SysDept> selectByName(String entname) {
		return deptMapper.selectByName(entname);
	}

	/**
	 * 添加信息部门
	 *
	 * @param dept 部门
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer saveDept(SysDept dept) {
		SysDept sysDept = new SysDept();
		BeanUtils.copyProperties(dept, sysDept);
		this.save(sysDept);
		sysDeptRelationService.insertDeptRelation(sysDept);
		return dept.getDeptId();
	}


	/**
	 * 删除部门
	 *
	 * @param id 部门 ID
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDeptById(Integer id) {
		// 级联删除部门
		List<Integer> idList = sysDeptRelationService
				.list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, id)).stream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());

		if (CollUtil.isNotEmpty(idList)) {
			this.removeByIds(idList);
		}

		//删除组织机构
		sysDeptRelationService.deleteDeptById(id);

		// 删除部门级联关系
		sysDeptRelationService.deleteAllDeptRealtion(id);
		return Boolean.TRUE;
	}


	/**
	 * 更新部门
	 *
	 * @param sysDept 部门信息
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateDeptById(SysDept sysDept) {
		// 更新部门状态
		this.updateById(sysDept);
		// 更新部门关系
		SysDeptRelation relation = new SysDeptRelation();
		relation.setAncestor(sysDept.getParentId());
		relation.setDescendant(sysDept.getDeptId());
		sysDeptRelationService.updateDeptRealtion(relation);
		return Boolean.TRUE;
	}

	@Override
	public List<SysDept> listScope(SysDept sysDept) {
		return deptMapper.selectListByScope(Wrappers.query(sysDept), new DataScope());
	}

	@Override
	public List<SysDept> selectDeptByName(SysDept sysDept) {
		List<SysDept> deptList = new ArrayList<>();
		if (SecurityUtils.getRoles().contains(1) || SecurityUtils.getRoles().contains(2)) {
			List<SysDept> sysDeptList = deptMapper.selectListByDept(sysDept);
			return sysDeptList;
		} else {
			sysDept.setDeptId(SecurityUtils.getUser().getDeptId());
			deptList = deptMapper.selectDeptByName(sysDept);
		}
		return deptList;
	}

	@Override
	public SysDept selectDeptId(SysDept sysDept) {
		return deptMapper.selectById(sysDept.getDeptId());
	}

	@Override
	public SysDept selectDeptById(SysDept sysDept) {
		return this.getById(sysDept.getDeptId());
	}

	/**
	 * 查询全部部门树
	 *
	 * @return 树
	 */
	@Override
	public List<DeptTree> selectTreeAddUser(SysDept sysDept) {
		// 查询数据权限内部门
		List<Integer> roles = SecurityUtils.getRoles();
//		List<SysDept> deptList = new ArrayList<>();
//		sysDept.setDeptId(SecurityUtils.getUser().getDeptId());
//		List<SysDept> list1 = deptMapper.selectDeptByIds(sysDept);
//		deptList.add(list1.get(0));
//		sysDept.setParentId(SecurityUtils.getUser().getDeptId());
//		List<SysDept> list2 = deptMapper.selectDeptByParentId(sysDept);
//		deptList.addAll(list2);
//		List<Integer> ids2 = deptList.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
//		if(roles.contains(1)||roles.contains(2)) {
//			for (Integer id : ids2){
//				SysDept sysDept1 = new SysDept();
//				sysDept1.setParentId(id);
//				List<SysDept> list = deptMapper.selectDeptByParentId(sysDept1);
//				deptList.addAll(list);
//			}
//		}
		List<SysDept> deptList = new ArrayList<>();

		if (roles.contains(1) || roles.contains(2)) {
			deptList = deptMapper.selectDeptList(sysDept);
		} else {
			SysDeptRelation sysDeptRelation = new SysDeptRelation();
			sysDeptRelation.setAncestor(SecurityUtils.getUser().getDeptId());
			List<SysDeptRelation> sysDeptRelationList = sysDeptRelationMapper.selectDeptRelationsList(sysDeptRelation);
			List<Integer> ids = sysDeptRelationList.stream().map(p -> p.getDescendant()).collect(Collectors.toList());
			for (Integer id : ids) {
				SysDept sysDept1 = new SysDept();
				sysDept1.setDeptId(id);
				SysDept sysDept2 = this.getById(sysDept1.getDeptId());

				if (null != sysDept2) {
					deptList.add(sysDept2);
				}
			}
		}
		// 权限内部门
		final boolean[] isFisrt = {true};
		List<DeptTree> collect = deptList.stream().filter(dept -> dept.getDeptId().intValue() > 0)
				.sorted(Comparator.comparingInt(SysDept::getSort)).map(dept -> {
					DeptTree node = new DeptTree();
					node.setId(dept.getDeptId());

					if (isFisrt[0]) {
//						node.setParentId(dept.getAncestor());
						isFisrt[0] = false;
					} else {
//						node.setParentId(dept.getAncestor());
					}
					node.setName(dept.getName());

					// 有权限不返回标识
//					if (deptList.contains(dept.getDeptId())) {
//						node.setIsLock(Boolean.FALSE);
//					}
					return node;
				}).collect(Collectors.toList());
		return TreeUtil.build(collect, 0);
	}


	/**
	 * 查询全部部门树
	 *
	 * @return 树
	 */
	@Override
	public List<DeptTree> selectTree(SysDept sysDept) {
		List<SysDept> deptList = deptMapper.selectDeptList(sysDept);

		List<DeptTree> collect = deptList.stream().filter(dept -> dept.getDeptId().intValue() > 0)
				.sorted(Comparator.comparingInt(SysDept::getSort)).map(dept -> {
					DeptTree node = new DeptTree();
					node.setId(dept.getDeptId());
//					node.setParentId(dept.getParentId());
					node.setName(dept.getName());

					// 有权限不返回标识
					if (deptList.contains(dept.getDeptId())) {
						node.setIsLock(Boolean.FALSE);
					}
					return node;
				}).collect(Collectors.toList());
		return TreeUtil.build(collect, 0);


//		List<Integer> roles=SecurityUtils.getRoles();
//		List<SysDept> deptList = new ArrayList<>();
//		List<SysDept> deptList1 = new ArrayList<>();
//		sysDept.setParentId(SecurityUtils.getUser().getDeptId());
//		List<SysDept> list2 = deptMapper.selectDeptByParentId(sysDept);
//		deptList1.addAll(list2);
//		SysDept sysDept4 = new SysDept();
//		sysDept4.setDeptId(SecurityUtils.getUser().getDeptId());
//		sysDept4.setLevel(3);
//		SysDept sysDept5 = deptMapper.selectDistinctDeptId(sysDept4);
//		// 查询数据权限内部门
//		List<Integer> ids2 = deptList1.stream().map(p -> p.getDeptId()).collect(Collectors.toList());
//
//		List<Integer> temp=new ArrayList<>();
//		temp.addAll(ids2);
//
//		temp.add(1);
//		if(roles.contains(1)||roles.contains(2)) {
//			for (Integer id : ids2){
//				SysDept sysDept1 = new SysDept();
//				sysDept1.setParentId(id);
//				List<SysDept> list = deptMapper.selectDeptByParentId(sysDept1);
//				deptList.addAll(list);
//			}
//		}
//
//		if(roles.contains(3))
//		{
//			SysDept se1=deptMapper.selectByDeptId(SecurityUtils.getUser().getDeptId());
//			if(null!=se1)
//			{
//				temp.add(se1.getDeptId());
//			}
//		}
//		if(roles.contains(4))
//		{
//			SysDept se1=deptMapper.selectByDeptId(SecurityUtils.getUser().getDeptId());
//			if(null!=se1)
//			{
//				temp.add(se1.getDeptId());
//				temp.add(se1.getParentId());
//			}
//			SysDept se2=this.selectByDeptId(se1.getParentId());
//			if(null!=se2)
//			{
//				if (sysDept5.getLevel()==4) {
//					temp.add(se2.getParentId());
//				}
//			}
//		}
//
//		if(roles.contains(5))
//		{
//			SysDept se1=deptMapper.selectByDeptId(SecurityUtils.getUser().getDeptId());
//
//			if(null!=se1)
//			{
//				temp.add(se1.getDeptId());
//				temp.add(se1.getParentId());
//			}
//
//			SysDept se2=deptMapper.selectByDeptId(se1.getParentId());
//
//			if(null!=se2)
//			{
//				temp.add(se2.getDeptId());
//				temp.add(se2.getParentId());
//			}
//			SysDept se3=deptMapper.selectByDeptId(se2.getParentId());
//			if(null!=se3)
//			{
//				temp.add(se3.getDeptId());
//				temp.add(se3.getParentId());
//			}
//		}
//		if(roles.contains(3))
//		{
//		for (Integer id : temp) {
//			SysDept sysDept1 = new SysDept();
//			if (id == 1 || id.equals(SecurityUtils.getUser().getDeptId())) {
//				sysDept1.setDeptId(id);
//				List<SysDept> sysDeptList = deptMapper.selectDeptByIds(sysDept1);
//				deptList.addAll(sysDeptList);
//			} else if (id != 1 && !id.equals(SecurityUtils.getUser().getDeptId())) {
//				sysDept1.setDeptId(id);
//				sysDept1.setParentId(SecurityUtils.getUser().getDeptId());
//				List<SysDept> sysDeptList = deptMapper.selectDeptLists(sysDept1);
//				deptList.addAll(sysDeptList);
//			}
//		}
//		}
//		if(roles.contains(4)) {
//			for (Integer id : temp) {
//				SysDept sysDept1 = new SysDept();
//				sysDept1.setDeptId(id);
//				List<SysDept> sysDeptList = deptMapper.selectDeptByIds(sysDept1);
//				deptList.addAll(sysDeptList);
//			}
//		}
//		if(roles.contains(1))
//		{
//			for (Integer id : temp) {
//				SysDept sysDept1 = new SysDept();
//				if (id == 1 || id.equals(SecurityUtils.getUser().getDeptId())) {
//					sysDept1.setDeptId(id);
//					List<SysDept> sysDeptList = deptMapper.selectDeptByIds(sysDept1);
//					deptList.addAll(sysDeptList);
//				} else if (id != 1 && !id.equals(SecurityUtils.getUser().getDeptId())) {
//					sysDept1.setDeptId(id);
//					sysDept1.setParentId(SecurityUtils.getUser().getDeptId());
//					List<SysDept> sysDeptList = deptMapper.selectDeptLists(sysDept1);
//					deptList.addAll(sysDeptList);
//				}
//			}
//		}
//		if(roles.contains(2))
//		{
//			for (Integer id : temp) {
//				SysDept sysDept1 = new SysDept();
//				if (id == 1 || id.equals(SecurityUtils.getUser().getDeptId())) {
//					sysDept1.setDeptId(id);
//					List<SysDept> sysDeptList = deptMapper.selectDeptByIds(sysDept1);
//					deptList.addAll(sysDeptList);
//				} else if (id != 1 && !id.equals(SecurityUtils.getUser().getDeptId())) {
//					sysDept1.setDeptId(id);
//					sysDept1.setParentId(SecurityUtils.getUser().getDeptId());
//					List<SysDept> sysDeptList = deptMapper.selectDeptLists(sysDept1);
//					deptList.addAll(sysDeptList);
//				}
//			}
//		}
//		// 权限内部门
//		List<DeptTree> collect = deptList.stream().filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
//				.sorted(Comparator.comparingInt(SysDept::getSort)).map(dept -> {
//					DeptTree node = new DeptTree();
//					node.setId(dept.getDeptId());
//					node.setParentId(dept.getParentId());
//					node.setName(dept.getName());
//
//					// 有权限不返回标识
//					if (deptList.contains(dept.getDeptId())) {
//						node.setIsLock(Boolean.FALSE);
//					}
//					return node;
//				}).collect(Collectors.toList());
//		return TreeUtil.build(collect, 0);

	}


	/**
	 * 查询所有关联服务企业
	 */
	@Override
	public List<SysDept> getAllParentDept(SysDept sysDept) {
		List<SysDept> deptList = deptMapper.getAllParentDept(sysDept);
		//一个机构同时是一级cso和二级cso时，可以自己给自己发包
		Map<Integer, SysDept> partsMap = deptList.stream().collect(
				Collectors.toMap(SysDept::getLevel, Function.identity(), (dto1, dto2) -> dto1));
		//没有药企，有一级cso和二级cso时，这个时候不返回二级cso
		if ((!partsMap.containsKey(2)) && partsMap.containsKey(3) && partsMap.containsKey(4)) {
			deptList.remove(partsMap.get(4));
		}
		//二级CSO只展示上级一级CSO
		if (partsMap.containsKey(2) && partsMap.containsKey(3) && partsMap.containsKey(4)) {
			SysDept sysDept1 = this.getById(SecurityUtils.getUser().getDeptId());
			if (sysDept1.getLevel() == 4) {
				deptList.remove(partsMap.get(2));
			}
		}
		return deptList;
	}

	@Override
	public String selectEntCodeByLevelId(long levelId, int level) {
		return deptMapper.selectEntCodeByLevelId(levelId, level);
	}

}
