package org.springblade.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.common.cache.SysCache;
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.springblade.modules.system.entity.Bzdz;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.excel.DeptExcel;
import org.springblade.modules.system.mapper.DeptMapper;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.vo.*;
import org.springblade.modules.system.wrapper.DeptWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
	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, String deptId) {
		return ForestNodeMerger.merge(baseMapper.tree(tenantId, deptId));
	}

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

	@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) {
		Long cnt = baseMapper.selectCount(Wrappers.<Dept>query().lambda().in(Dept::getParentId, Func.toLongList(ids)));
		if (cnt > 0L) {
			throw new ServiceException("请先删除子节点!");
		}
		return removeByIds(Func.toLongList(ids));
	}

	@Override
	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);
		return saveOrUpdate(dept);
	}

	@Override
	public List<DeptVO> search(String deptName, Long parentId) {
		String tenantId = AuthUtil.getTenantId();
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda();
		if (Func.isNotEmpty(tenantId)) {
			queryWrapper.eq(Dept::getTenantId, tenantId);
		}
		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 String getDeptIdByDeptname(String deptName) {
		return baseMapper.getDeptIdByDeptname(deptName);
	}

	@Override
	public List<DeptVO> getXfbm() {
		return baseMapper.getXfbm();
	}

	@Override
	public List<DeptListVo> getDeptList(Long userId) {
		return baseMapper.getDeptList(userId);
	}

	@Override
	public List<FjVO> getfJList(String deptId) {
		return baseMapper.getfJList(deptId);
	}

	@Override
	public List<PcsVO> getPcsList(String deptId, Long fjId) {
		return baseMapper.getPcsList(deptId, fjId);
	}

	@Override
	public List<SqVO> getSqList(String deptId, Long pcsId) {
		return baseMapper.getSqList(deptId, pcsId);
	}

	@Override
	public String selectSq(String deptId) {
		List<Dept> strings = baseMapper.selectSq(deptId);
		if (strings.size()!=0) {
			String s = new String();
			for (Dept d : strings) {
				s += d.getDeptName();
				s += ",";
			}
			int last = s.lastIndexOf(",");
			s = s.substring(0, last);
			return s;
		}
		return null;
	}

	@Override
	public String selectPcs(String deptId) {
		List<Dept> strings = baseMapper.selectPcs(deptId);
		String s = new String();
		for (Dept d:strings){
			s = d.getFullName();
		}
		return s;
	}

	@Override
	public Dept selectSsfjBm(String ssfjMc) {
		return baseMapper.selectSsfjBm(ssfjMc);
	}

	@Override
	public Dept selectSspcsBm(String sspcsMc, String ssfjMc) {
		return baseMapper.selectSspcsBm(sspcsMc, ssfjMc);
	}

	@Override
	public Dept selectSssqBm(String sssqMc, Long parentId) {
		return baseMapper.selectSssqBm(sssqMc, parentId);
	}

	@Override
	public List<Dept> getJsByFj(String deptId) {
		return baseMapper.getJsByFj(deptId);
	}

	@Override
	public List<Dept> getJsByPcs(Long parentId) {
		return baseMapper.getJsByPcs(parentId);
	}

	@Override
	public List<Dept> getJsBySq(Long parentId) {
		return baseMapper.getJsBySq(parentId);
	}

	@Override
	public List<Dept> getJsByFjDownPcs(String value) {
		return baseMapper.getJsByFjDownPcs(value);
	}

	@Override
	public List<Dept> getJsByPcsDownPcs(String deptId) {
		return baseMapper.getJsByPcsDownPcs(deptId);
	}

	@Override
	public List<Dept> getJsBySqDownPcs(Long parentId) {
		return baseMapper.getJsBySqDownPcs(parentId);
	}

	@Override
	public List<Dept> getJsByFjDownSq(String value) {
		return baseMapper.getJsByFjDownSq(value);
	}

	@Override
	public List<Dept> getJsByPcsDownSq(String value) {
		return baseMapper.getJsByPcsDownSq(value);
	}

	@Override
	public Dept getJsBySqDownSq(String deptId) {
		return baseMapper.getJsBySqDownSq(deptId);
	}

	@Override
	public List<Dept> getJsBySj(String deptId) {
		return baseMapper.getJsBySj(deptId);
	}

	@Override
	public List<Dept> getQsga(String deptId) {
		return baseMapper.getQsga(deptId);
	}

	@Override
	public Dept getJxcspc(Long id) {
		return baseMapper.getJxcspc(id);
	}

	@Override
	public Dept getJxcsjc(Long id) {
		return baseMapper.getJxcsjc(id);
	}

	@Override
	public IPage<DeptVOS> getQsyhcsjc(IPage<Object> page, DeptVOS deptVOS) {
		String str = "";
		String strEnd = "";
		if (deptVOS.getDatetime()!=null) {
			String[] datetime = deptVOS.getDatetime().split(",");
			str = datetime[0];
			strEnd = datetime[1];
		}
		return baseMapper.getQsyhcsjc(page,deptVOS,str,strEnd);
	}

	@Override
	public List<DeptVOS> getQsyhcsjcfj(String id, String datetime) {
		String str = "";
		String strEnd = "";
		if (datetime!=null) {
			String[] datetimes = datetime.split(",");
			str = datetimes[0];
			strEnd = datetimes[1];
		}
		return baseMapper.getQsyhcsjcfj(id,str,strEnd);
	}

	@Override
	public List<Bzdz> getLdByPcsbm(String deptId, String wzxxdz) {
		return baseMapper.getLdByPcsbm(deptId,wzxxdz);
	}

	@Override
	public Bzdz getLdInfoByLdbh(String xxzjbh,String deptId) {
		return baseMapper.getLdInfoByLdbh(xxzjbh,deptId);
	}

	@Override
	public void updateSSSqDmByxxzjbh(String xxzjbh, String sqId,String deptId) {
		baseMapper.updateSSSqDmByxxzjbh(xxzjbh, sqId,deptId);
	}

	@Override
	public boolean updateSSSqDmIsNUll(String xxzjbh) {
		try {
			String deptId = AuthUtil.getDeptId();
			baseMapper.updateSSSqDmIsNUll(xxzjbh,deptId);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateSSSqDmIsNUllnew(String dzbm, String sssqBm) {
		return baseMapper.updateSSSqDmIsNUllnew(dzbm,sssqBm);
	}

	@Override
	public void deleteByLdId(String id) {
		baseMapper.deleteByLdId(id);
	}

	@Override
	@Transactional
	public R updateBzdzGlsq(String ldIds, String sqId) {
		String deptId = AuthUtil.getDeptId();
		String[] split = ldIds.split(",");
		//获取社区部门信息
		Dept sq = this.getById(Long.parseLong(sqId));
		//循环创建楼栋信息到部门表中
		try {
			for (int i = 0; i < split.length; i++) {
				String xxzjbh = split[i];
//				Bzdz ldInfoByLdbh = this.getLdInfoByLdbh(xxzjbh,deptId);
//				Dept dept = new Dept();
//				dept.setId(Long.parseLong(ldInfoByLdbh.getDzbm()));
//				dept.setTenantId("000000");
//				dept.setParentId(Long.parseLong(sqId));
//				dept.setAncestors(sq.getAncestors()+","+sqId);
//				dept.setDeptCategory(16);//默认字典值 16 楼栋
//				dept.setDeptName(ldInfoByLdbh.getWzxxdz());
//				dept.setFullName(ldInfoByLdbh.getWzxxdz());
//				dept.setSort(i+1);
//				dept.setIsDeleted(0);
//				this.save(dept);
				//创建后修改标准地址信息
				this.updateSSSqDmByxxzjbh(xxzjbh,sqId,deptId);
			}
			return R.success("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	@Override
	public boolean updateId(Dept dept) {
		return baseMapper.updateId(dept);
	}

	@Override
	@Transactional
	public Long getParentId(DeptExcel deptExcel) {
		return baseMapper.getParentId(deptExcel);
	}

	@Override
	public Dept getDeptCategory(String deptId) {
		return baseMapper.getDeptCategory(deptId);
	}

	@Override
	public MjDeptVO getDeptDetail(String deptId) {
		return baseMapper.getDeptDetail(deptId);
	}

	@Override
	public List<Dept> getSqByPcs(MjDeptVO mjDeptVO) {
		return baseMapper.getSqByPcs(mjDeptVO);
	}

	@Override
	public int countDeptById(Long deptId) {
		return baseMapper.countDeptById(deptId);
	}

	@Override
	public Long getDeptByQhAndCategory(String xzqh) {
		return baseMapper.getDeptByQhAndCategory(xzqh);
	}

	@Override
	public List<ZdbVo> getShi() {
		return baseMapper.getShi();
	}

	@Override
	public List<ZdbVo> getXqShiZddm(String shiZddm) {
		return baseMapper.getXqShiZddm(shiZddm);
	}

	@Override
	public List<ZdbVo> getJdByXqZddm(String xqZddm) {
		return baseMapper.getJdByXqZddm(xqZddm);
	}

	@Override
	public List<ZdbVo> getSqByJdZddm(String jdZddm) {
		return baseMapper.getSqByJdZddm(jdZddm);
	}

	@Override
	public void updateXqParent(String shiZddm) {
		baseMapper.updateXqParent(shiZddm);
	}

	@Override
	public void updateJdParent(String xqzddm, String parents) {
		baseMapper.updateJdParent(xqzddm,parents);
	}

	@Override
	public void updateSqParent(String jdzddm, String parents) {
		baseMapper.updateSqParent(jdzddm, parents);
	}

	@Override
	public List<ZdVOSS> getDept(String deptId) {
		return baseMapper.getDept(deptId);
	}

	@Override
	public List<ZdldVo> getZdLdBySssqbm(String sssqBm) {
		return baseMapper.getZdLdBySssqbm(sssqBm);
	}

	@Override
	public List<ZdVO> getBmByDept(String deptId) {
		return baseMapper.getBmByDept(deptId);
	}

	@Override
	public Bzdz getSssqBmBydzbm(String dzbm) {
		return baseMapper.getSssqBmBydzbm(dzbm);
	}

	@Override
	public boolean updatePlsc(String[] dzbms, String sssqBm) {
		return baseMapper.updatePlsc(dzbms,sssqBm);
	}

	@Override
	public List<ZdVO> getDeptNameById(String deptId, Dept byId) {
		return baseMapper.getDeptNameById(deptId, byId);
	}

	@Override
	public Dept selectSjByFj(String deptId) {
		return baseMapper.selectSjByFj(deptId);
	}

	@Override
	public Dept selectSjByPcs(String deptId) {
		return baseMapper.selectSjByPcs(deptId);
	}

	@Override
	public Dept selectSjBySqmj(String deptId) {
		return baseMapper.selectSjBySqmj(deptId);
	}

	@Override
	public Dept getParentDept(String deptId) {
		return baseMapper.getParentDept(deptId);
	}

	@Override
	public boolean getBmxg(Dept dept) {
		return baseMapper.getBmxg(dept);
	}

	@Override
	public Dept getFjPcsBySq(Long sssqBm) {
		return baseMapper.getFjPcsBySq(sssqBm);
	}

	@Override
	public List<FjVOS> getfJLists(String deptId) {
		return baseMapper.getfJLists(deptId);
	}

	@Override
	public List<PcsVOS> getPcsLists(String deptId, String fjId) {
		return baseMapper.getPcsLists(deptId, fjId);
	}

	@Override
	public List<FjVOS> getSfjZdb(String deptId) {
		return baseMapper.getSfjZdb(deptId);
	}

	@Override
	public List<PcsVOS> getPcsZdb(String value) {
		return baseMapper.getPcsZdb(value);
	}

	@Override
	public int getDeptById(Long id) {
		return baseMapper.getDeptById(id);
	}

	@Override
	public List<ZdVO> getPcsByFjId(String deptId) {
		return baseMapper.getPcsByFjId(deptId);
	}

	@Override
	public boolean updateAncestors(String str, Long id, String ancestors) {
		return baseMapper.updateAncestors(str, id, ancestors);
	}

	@Override
	public boolean deleteByPcsId(String str) {
		return baseMapper.deleteByPcsId(str);
	}

	@Override
	public Dept getDeptCategoryByAccount(String username) {
		return baseMapper.getDeptCategoryByAccount(username);
	}

	@Override
	public Dept getSjByAccount(String deptId) {
		return baseMapper.getSjByAccount(deptId);
	}
}
