package com.boman.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.exception.CustomException;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.datascope.annotation.DataScope;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.SysDept;
import com.boman.domain.SysRole;
import com.boman.domain.SysUser;
import com.boman.domain.constant.CacheConstants;
import com.boman.domain.constant.UserConstants;
import com.boman.system.api.model.LoginUser;
import com.boman.system.domain.vo.TreeSelect;
import com.boman.system.mapper.SyncMapper;
import com.boman.system.mapper.SysDeptMapper;
import com.boman.system.mapper.SysRoleMapper;
import com.boman.system.service.ISysDeptService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.boman.common.core.utils.obj.ObjectUtils.isEmpty;
import static com.boman.domain.constant.CacheConstants.DEPT_LIST;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Resource
    private RedisService redisService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + SecurityUtils.getToken());
        SysUser sysUser = loginUser.getSysUser();
        Long deptId = sysUser.getDeptId();
/*        List<SysRole> roles = sysUser.getRoles();
        dept.setListByParentId(Boolean.TRUE);
        for (SysRole role : roles) {
            String dataScope = role.getDataScope();
            if (DATA_SCOPE_ALL.equals(dataScope)){
                dept.setListByParentId(Boolean.FALSE);
            }
        }*/
        if (StringUtils.isNotEmpty(dept.getDeptName()) || StringUtils.isNotEmpty(dept.getStatus())) {
            return deptMapper.selectDeptList(dept);
        }
        Long id = dept.getId();
        if (id != null) {
            dept.setParentId(id);
        }else {
            dept.setId(deptId);
        }
        List<SysDept> depts = deptMapper.selectDeptList(dept);
        // 这里的逻辑是：根据id获取到这个下面的所有子部门，每个部门判断是否有下一级别
        if (depts != null && depts.size() > 0) {
            List<SysDept> hasChirlds = deptMapper.validateHasChirld(depts);
            if (hasChirlds != null && hasChirlds.size() > 0) {
                Map<Long, SysDept> hasChirldMap = new HashMap<>();
                for (SysDept hasChirld : hasChirlds) {
                    hasChirldMap.put(hasChirld.getId(), hasChirld);
                }
                for (SysDept sysDept : depts) {
                    if (hasChirldMap.get(sysDept.getId()) == null) {
                        sysDept.setHasChildren(Boolean.FALSE);
                    }
                }
            } else {
                for (SysDept sysDept : depts) {
                    sysDept.setHasChildren(Boolean.FALSE);
                }
            }
        }
        return depts;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDepts(SysDept dept) {
        dept.setListByParentId(Boolean.TRUE);
        return deptMapper.selectDeptList(dept);
    }

    /**
     *查询部门全部数据,不带权限
     * @return
     */
    @Override
    public List<SysDept> selectDeptsList() {
        List<SysDept> sysDepts = deptMapper.selectDeptsList();
        return sysDepts;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListById(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param id 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long id) {
        return deptMapper.selectDeptById(id);
    }

    /**
     * 根据部门名称查询信息
     *
     * @param deptName
     * @return
     */
    @Override
    public List<SysDept> selectByDeptName(String deptName) {
        SysDept sysDept = deptMapper.selectDeptByDeptName(deptName);
        List<SysDept> sysDepts = listChildrenDepts(sysDept.getId());
        sysDepts.add(sysDept);
         return sysDepts;
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param id 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long id) {
        return deptMapper.selectNormalChildrenDeptById(id);
    }

    /**
     * 是否存在子节点
     *
     * @param id 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildById(Long id) {
        int result = deptMapper.hasChildById(id);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param id 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long id) {
        int result = deptMapper.checkDeptExistUser(id);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long id = StringUtils.isNull(dept.getId()) ? -1L : dept.getId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        redisService.deleteObject(DEPT_LIST);
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        redisService.deleteObject(DEPT_LIST);
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param id           被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long id, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(id);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param id 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long id) {
        return deptMapper.deleteDeptById(id);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 功能描述: 根据deptId查找部门下的所有部门
     *
     * @param deptId deptId
     * @return com.boman.domain.dto.AjaxResult
     */
    @Override
    public List<SysDept> listChildrenDepts(Long deptId) {
        //先去缓存拿数据
        List<SysDept> allDepts = redisService.getCacheList(CacheConstants.DEPT_LIST);
        if (allDepts != null && allDepts.size()>0){
            log.info("我从缓存中拿到部门集合");
        }else {
            allDepts = selectDepts(new SysDept());
            redisService.setCacheList(CacheConstants.DEPT_LIST,allDepts);
            log.info("我从数据库拿到部门集合");
        }
        SysDept sysDept = ObjectUtils.filterOne(allDepts, dept -> deptId.equals(dept.getId()));
        List<SysDept> returnData = Lists.newArrayListWithCapacity(16);
        if (null == sysDept) {
            return returnData;
        }

        List<SysDept> sysDepts = recursionChildrenDepts(allDepts, sysDept, returnData);
        SysDept selfDept = new SysDept();
        selfDept.setId(deptId);
        sysDepts.add(selfDept);
        return sysDepts;
    }

    private List<SysDept> recursionChildrenDepts(List<SysDept> allDepts, SysDept sysDept, List<SysDept> returnData) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(allDepts, sysDept);
        returnData.addAll(childList);
        for (SysDept tChild : childList) {
            if (hasChild(allDepts, tChild)) {
                recursionChildrenDepts(allDepts, tChild, returnData);
            }
        }

        return returnData;
    }

    @Override
    public List<JSONObject> syncData(int limit) throws Exception {
        List<JSONObject> datas = new ArrayList<>();
        try {
            SysDept sysDept = new SysDept();
            // 所有层级数据
            List<TreeSelect> depts = this.getDepts(sysDept);
            // 乡镇
            List<TreeSelect> regionDept = this.getRegionDept(depts);
            Map<String, Long> regionMap = new HashMap<>();
            for (TreeSelect treeSelect : regionDept) {
                regionMap.put(treeSelect.getLabel(), treeSelect.getId());
            }
            // 村
            Map<String, Long> repeatVillageMap = new HashMap<>();
            List<TreeSelect> villegeDept = this.getVillegeDept(depts, repeatVillageMap);
            Map<String, Long> villegeMap = new HashMap<>();


            for (TreeSelect treeSelect : villegeDept) {
                String deptName = treeSelect.getLabel();
                Long deptId = treeSelect.getId();
                if (villegeMap.containsKey(deptName)) {
                    System.out.println(deptName);
                }
                villegeMap.put(deptName, deptId);
            }

            List<JSONObject> vaccInfos = this.getVaccInfo(limit);
            for (JSONObject vanninfo : vaccInfos) {
                String idCard = vanninfo.getString("zjhm");
                String dz = vanninfo.getString("hjdxz");
                if (StringUtils.isBlank(dz)){
                    dz = vanninfo.getString("akmdz");
                }
                JSONObject update = new JSONObject();
                update.put("id_card", idCard);
                // 先判断村数据是否存在,如果村存在，则直接获取村的id，反之获取乡镇id
                Long deptId = this.getVillegeDeptId(dz, villegeMap, repeatVillageMap);
                if (deptId == null) {
                    deptId = this.getRegionDeptId(dz, regionMap);
                }
                update.put("dept_id", deptId);
                System.out.println(update.toJSONString());
                datas.add(update);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datas;
    }

    @Resource
    private SyncMapper syncMapper;

    private List<JSONObject> getVaccInfo(int limit) {
        String sql = "select zjhm,hjdxz,akmdz from hj_hj limit " + limit+", 100000";
        List<JSONObject> objs = syncMapper.selectBySql(sql);
        return objs;
    }

    private List<TreeSelect> getDepts(SysDept dept) {
        return buildDeptTreeSelect(this.selectDepts(dept));
    }

    private List<TreeSelect> getRegionDept(List<TreeSelect> depts) {
        return depts.get(0).getChildren();
    }

    private List<TreeSelect> getVillegeDept(List<TreeSelect> depts, Map<String, Long> repeatVillageMap) {
        List<TreeSelect> villegs = new ArrayList<>();
        List<TreeSelect> regions = depts.get(0).getChildren();
        for (TreeSelect region : regions) {
            if (region.getLabel().equals("王河镇") || region.getLabel().equals("五庙乡")
                    || region.getLabel().equals("黄铺镇") || region.getLabel().equals("水吼镇")) {
                List<TreeSelect> vills = region.getChildren();
                for (TreeSelect vill : vills) {
                    if (vill.getLabel().equals("和平村") || vill.getLabel().equals("红光村")) {
                        repeatVillageMap.put(region.getLabel() + vill.getLabel(), vill.getId());
                    } else {
                        villegs.add(vill);
                    }
                }
            } else {
                villegs.addAll(region.getChildren());
            }

        }

        return villegs;
    }

    private Long getRegionDeptId(String dz, Map<String, Long> villegeMap) {
        for (String deptName : villegeMap.keySet()) {
            if (dz.contains(deptName)) {
                return villegeMap.get(deptName);
            }
        }
        return null;

    }

    private Long getVillegeDeptId(String dz, Map<String, Long> villegeMap, Map<String, Long> repeatVillageMap) {
        if (dz.contains("和平村") || dz.contains("红光村")) {
            if (dz.contains("黄铺镇" + "和平村")) {
                return repeatVillageMap.get("黄铺镇" + "和平村");
            } else if (dz.contains("水吼镇" + "和平村")) {
                return repeatVillageMap.get("水吼镇" + "和平村");
            } else if (dz.contains("王河镇" + "红光村")) {
                return repeatVillageMap.get("王河镇" + "红光村");
            } else if (dz.contains("五庙乡" + "红光村")) {
                return repeatVillageMap.get("五庙乡" + "红光村");
            }
        } else {
            for (String deptName : villegeMap.keySet()) {
                if (dz.contains(deptName)) {
                    return villegeMap.get(deptName);
                }
            }
        }

        return null;

    }

    @Override
    public List<SysDept> getByParentId(Long deptId) {
        if (null == deptId || deptId <= 0) {
            return null;
        }

        return deptMapper.getByParentId(deptId);
    }

    /**
     * 功能描述: 只找父亲，不招爷爷
     *
     * @param parentId deptId
     * @return com.boman.domain.SysDept
     */
    @Override
    public SysDept getParentById(Long parentId) {
        return deptMapper.getParentById(parentId);
    }

    @Override
    public List<SysDept> listTowns(Long deptId) {
        String token = SecurityUtils.getToken();
        LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);

        List<SysRole> roles = loginUser.getSysUser().getRoles();
        List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());

        List<SysDept> townsDepts = new ArrayList<>(16);
        List<SysDept> allDepts = selectDeptsList();
        if (roleKeyList.contains("admin") || roleKeyList.contains("city") || roleKeyList.contains("yanshi")) {
            Long deptId1;
            if (null == deptId) deptId1 = 1L; // 查所有乡镇
            else deptId1 = deptId; // 查乡镇下的村

            for (SysDept allDept : allDepts) {
                if (isEmpty(allDept.getParentId())) continue;
                if (allDept.getParentId().equals(deptId1)) {
                    townsDepts.add(allDept);
                }
            }
        } else if (roleKeyList.contains("sys:town")) {
            if (null == deptId) {
                // 乡镇的登录进来，只能选择自己的乡镇，不可以选择其他的乡镇，因此只返回自己的乡镇
                townsDepts.add(loginUser.getSysUser().getDept());
            } else {
                for (SysDept allDept : allDepts) {
                    if (isEmpty(allDept.getParentId())) continue;
                    if (allDept.getParentId().equals(deptId)) {
                        townsDepts.add(allDept);
                    }
                }
            }
        }

        return townsDepts;
    }

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