/*
 *      Copyright (c) 2018-2028, Chill Zhuang 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 dreamlu.net 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: Chill 庄骞 (smallchill@163.com)
 */
package org.security.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.security.system.cache.SysCache;
import org.security.system.vo.DeptVO;
import org.security.system.wrapper.DeptWrapper;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.security.system.entity.Department;
import org.security.system.entity.Dept;
import org.security.system.mapper.DeptMapper;
import org.security.system.service.IDepartmentService;
import org.security.system.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@Slf4j
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
	@Autowired
	private IDepartmentService departmentService;

	private static final String TENANT_ID = "tenantId";
	private static final String PARENT_ID = "parentId";

	@Override
	public List<DeptVO> lazyList(String tenantId, Long parentId, Map<String, Object> param) {
		// 设置租户ID
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		String paramTenantId = Func.toStr(param.get(TENANT_ID));
		if (Func.isNotEmpty(paramTenantId) && AuthUtil.isAdministrator()) {
			tenantId = paramTenantId;
		}
		// 判断点击搜索但是没有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() == 1) {
			parentId = 0L;
		}
		// 判断数据权限控制,非超管角色只可看到本级及以下数据
		if (Func.toLong(parentId) == 0L && !AuthUtil.isAdministrator()) {
			Long deptId = Func.firstLong(AuthUtil.getDeptId());
			Dept dept = SysCache.getDept(deptId);
			if (dept.getParentId() != 0) {
				parentId = dept.getParentId();
			}
		}
		// 判断点击搜索带有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() > 1 && Func.toLong(parentId) == 0L) {
			parentId = null;
		}
		return baseMapper.lazyList(tenantId, parentId, param);
	}


	@Override
	public List<DeptVO> tree(String tenantId) {
		return ForestNodeMerger.merge(baseMapper.tree(tenantId));
	}

	@Override
	public List<DeptVO> lazyTree(String tenantId, Long parentId) {
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		return ForestNodeMerger.merge(baseMapper.lazyTree(tenantId, parentId));
	}

	@Override
	public String getDeptIds(String tenantId, String deptNames) {
		List<Dept> deptList = baseMapper.selectList(Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId).in(Dept::getDeptName, Func.toStrList(deptNames)));
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public String getDeptIdsByFuzzy(String tenantId, String deptNames) {
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId);
		queryWrapper.and(wrapper -> {
			List<String> names = Func.toStrList(deptNames);
			names.forEach(name -> wrapper.like(Dept::getDeptName, name).or());
		});
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public List<String> getDeptNames(String deptIds) {
		return baseMapper.getDeptNames(Func.toLongArray(deptIds));
	}

	@Override
	public List<Dept> getDeptChild(Long deptId) {
		return baseMapper.selectList(Wrappers.<Dept>query().lambda().like(Dept::getAncestors, deptId));
	}

	@Override
	public boolean removeDept(String ids) {
		Integer cnt = baseMapper.selectCount(Wrappers.<Dept>query().lambda().in(Dept::getParentId, Func.toLongList(ids)));
		if (cnt > 0) {
			throw new ServiceException("请先删除子节点!");
		}
		departmentService.removeByIds(Func.toLongList(ids));
		return removeByIds(Func.toLongList(ids));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(Dept dept) {
		if (Func.isEmpty(dept.getParentId())) {
			dept.setTenantId(AuthUtil.getTenantId());
			dept.setParentId(BladeConstant.TOP_PARENT_ID);
			dept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
		}
		if (dept.getParentId() > 0) {
			Dept parent = getById(dept.getParentId());
			if (Func.toLong(dept.getParentId()) == Func.toLong(dept.getId())) {
				throw new ServiceException("父节点不可选择自身!");
			}
			dept.setTenantId(parent.getTenantId());
			String ancestors = parent.getAncestors() + StringPool.COMMA + dept.getParentId();
			dept.setAncestors(ancestors);
		}
		dept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
		saveOrUpdate(dept);
		Department department = new Department();
		department.setId(String.valueOf(dept.getId()));
		department.setDeptName(dept.getDeptName());
		department.setAncestors(dept.getAncestors());
		department.setFullName(dept.getFullName());
		department.setDeptCategory(String.valueOf(dept.getDeptCategory()));
		department.setParentId(String.valueOf(dept.getParentId()));
		department.setCreatedBy(String.valueOf(AuthUtil.getUserId()));
		department.setCreatedTime(new Date());
		department.setUpdatedTime(new Date());
		department.setUpdatedBy(String.valueOf(AuthUtil.getUserId()));
		department.setDeptNo(String.valueOf(dept.getDeptCode()));
		List<Integer> list = Func.toIntList(dept.getAncestors());
		department.setDeptLevel(String.valueOf(list.size()));
		return departmentService.saveOrUpdate(department);
	}

	@Override
	public List<DeptVO> search(String deptName, Long parentId) {
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda();
		if (Func.isNotEmpty(deptName)) {
			queryWrapper.like(Dept::getDeptName, deptName);
		}
		if (Func.isNotEmpty(parentId) && parentId > 0L) {
			queryWrapper.eq(Dept::getParentId, parentId);
		}
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		return DeptWrapper.build().listNodeVO(deptList);
	}

	@Override
	public DeptVO getHeadDept(Long deptId) {
		log.info(">>>>>>>>>>>> 获取“" + deptId + "”所属总行开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
			throw new ServiceException(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.eq(Dept::getDeptCategory, "1")
			.in(Dept::getId, depts);
		List<Dept> branchs = baseMapper.selectList(wrapper);
		if (branchs.size() == 0) {
			log.error(">>>>>>>>>>>> 未能找到机构所属总行！");
			throw new ServiceException("未能找到机构所属总行！");
		} else if (branchs.size() > 1) {
			log.error(">>>>>>>>>>>> 该机构隶属于多个总行，请重新配置后再试！" + branchs.toString());
			throw new ServiceException("该机构隶属于多个总行，请重新配置后再试！" + branchs.toString());
		}
		log.info(">>>>>>>>>>>> 获取所属总行结束");
		return DeptWrapper.build().entityVO(branchs.get(0));
	}

	@Override
	public DeptVO getBranchDept(Long deptId) {
		log.info(">>>>>>>>>>>> 获取“" + deptId + "”所属分行开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
			throw new ServiceException(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.eq(Dept::getDeptCategory, "2")
			.in(Dept::getId, depts);
		List<Dept> branchs = baseMapper.selectList(wrapper);
		if (branchs.size() == 0) {
			log.error(">>>>>>>>>>>> 未能找到机构所属分行！");
			throw new ServiceException("未能找到机构所属分行！");
		} else if (branchs.size() > 1) {
			log.error(">>>>>>>>>>>> 该机构隶属于多个分行，请重新配置后再试！" + branchs.toString());
			throw new ServiceException("该机构隶属于多个分行，请重新配置后再试！" + branchs.toString());
		}
		log.info(">>>>>>>>>>>> 获取所属分行结束");
		return DeptWrapper.build().entityVO(branchs.get(0));
	}

	@Override
	public DeptVO getSubDept(Long deptId) {
		log.info(">>>>>>>>>>>> 获取“" + deptId + "”所属支行开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
			throw new ServiceException(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.eq(Dept::getDeptCategory, "3")
			.in(Dept::getId, depts);
		List<Dept> branchs = baseMapper.selectList(wrapper);
		if (branchs.size() == 0) {
			log.error(">>>>>>>>>>>> 未能找到机构所属支行！");
			throw new ServiceException("未能找到机构所属支行！");
		} else if (branchs.size() > 1) {
			log.error(">>>>>>>>>>>> 该机构隶属于多个支行，请重新配置后再试！" + branchs.toString());
			throw new ServiceException("该机构隶属于多个支行，请重新配置后再试！" + branchs.toString());
		}
		log.info(">>>>>>>>>>>> 获取所属支行结束");
		return DeptWrapper.build().entityVO(branchs.get(0));
	}

	@Override
	public List<DeptVO> getBranchDeptAll(Long deptId) {
		log.info(">>>>>>>>>>>> 获取“" + deptId + "”所属分行及其下属机构开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
			throw new ServiceException(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.eq(Dept::getDeptCategory, "2")
			.in(Dept::getId, depts);
		List<Dept> branchs = baseMapper.selectList(wrapper);
		if (branchs.size() == 0) {
			log.error(">>>>>>>>>>>> 未能找到机构所属分行！");
			throw new ServiceException("未能找到机构所属分行！");
		} else if (branchs.size() > 1) {
			log.error(">>>>>>>>>>>> 该机构隶属于多个分行，请重新配置后再试！" + branchs.toString());
			throw new ServiceException("该机构隶属于多个分行，请重新配置后再试！" + branchs.toString());
		}
		LambdaQueryWrapper<Dept> wrapper1 = Wrappers.<Dept>lambdaQuery()
			.like(Dept::getAncestors, branchs.get(0).getId());
		branchs.addAll(baseMapper.selectList(wrapper1));
		log.info(">>>>>>>>>>>> 获取分行及其下属机构结束");
		return DeptWrapper.build().listVO(branchs);
	}

	@Override
	public List<DeptVO> getSubDeptAll(Long deptId) {
		log.info(">>>>>>>>>>>> 获取“" + deptId + "”所属支行及其下属机构开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
			throw new ServiceException(">>>>>>>>>>>> 获取参数部门“" + deptId + "”失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.eq(Dept::getDeptCategory, "3")
			.in(Dept::getId, depts);
		List<Dept> branchs = baseMapper.selectList(wrapper);
		if (branchs.size() == 0) {
			log.error(">>>>>>>>>>>> 未能找到机构所属支行！");
			throw new ServiceException("未能找到机构所属支行！");
		} else if (branchs.size() > 1) {
			log.error(">>>>>>>>>>>> 该机构隶属于多个支行，请重新配置后再试！" + branchs.toString());
			throw new ServiceException("该机构隶属于多个支行，请重新配置后再试！" + branchs.toString());
		}
		LambdaQueryWrapper<Dept> wrapper1 = Wrappers.<Dept>lambdaQuery()
			.like(Dept::getAncestors, branchs.get(0).getId());
		branchs.addAll(baseMapper.selectList(wrapper1));
		log.info(">>>>>>>>>>>> 获取所属支行及其下属机构结束");
		return DeptWrapper.build().listVO(branchs);
	}

	@Override
	public Integer getDeptCategory(Long deptId) {
		if (Func.isNull(deptId)) {
			deptId = Long.valueOf(AuthUtil.getDeptId());
		}
		if (Func.isNull(deptId) || -1 == deptId) {
			log.error(">>>>>>>>>>>> 部门Id“" + deptId + "”有误！");
			throw new RuntimeException("部门Id“" + deptId + "”有误！");
		}
		log.info(">>>>>>>>>>>> 获取部门“" + deptId + "”的部门类型开始");
		Dept dept = baseMapper.selectById(deptId);
		if (Func.isNull(dept)) {
			log.error(">>>>>>>>>>>> 获取部门失败");
			throw new RuntimeException("获取部门失败");
		}
		List<String> depts = Arrays.stream(dept.getAncestors().split(StringPool.COMMA)).collect(Collectors.toList());
		depts.add(dept.getId().toString());
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>lambdaQuery()
			.in(Dept::getId, depts);
		List<Dept> deptList = baseMapper.selectList(wrapper);
		List<Dept> sortedList = deptList.stream()
			.filter(x -> null != x.getDeptCategory() && x.getDeptCategory() > 0 && x.getDeptCategory() <= 3)
			.sorted(Comparator.comparing(Dept::getDeptCategory).reversed())
			.collect(Collectors.toList());
		if (sortedList.isEmpty()) {
			log.error(">>>>>>>>>>>> 机构配置错误，请检查后再试");
			throw new RuntimeException("机构配置错误，请检查后再试！");
		}
		return sortedList.get(0).getDeptCategory();
	}

	@Override
	public boolean synSaveDeptData(List<Dept> deptList) {
		return this.saveOrUpdateBatch(deptList);
	}

}
