package com.testor.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.common.constant.StatusEnum;
import com.testor.common.util.StreamUtils;
import com.testor.module.notice.model.domain.TSysOrg;
import com.testor.module.sys.dao.NewSysOrgDao;
import com.testor.module.sys.model.domain.TSysConfig;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.model.vo.SysOrgVo;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.module.sys.service.TSysConfigService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import io.jsonwebtoken.lang.Collections;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class NewSysOrgServiceImpl extends SuperServiceImpl<NewSysOrgDao, NewSysOrg> implements NewSysOrgService {
    @Autowired
    private NewSysOrgDao sysOrgDao;
    @Autowired
    private TSysConfigService tSysConfigService;

    public NewSysOrgServiceImpl() {
    }

    @Override
    public List<NewSysOrg> getChildrenById(String orgId) {
        QueryWrapper<NewSysOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0")
                .eq("is_dept", "0")
                .and(i -> i.eq("org_id", orgId).or().like("parent_ids", "," + orgId))
                .orderByAsc("tree_level", "tree_sort");
        return this.list(queryWrapper);
    }

    @Override
    public List<NewSysOrg> childrenHiddenDanger(String orgId) {
        QueryWrapper<NewSysOrg> queryWrapper = new QueryWrapper<>();
        String dbgkOrgId = "1335dbc3f81b4919bf59014fede4819d";
        NewSysOrg org = this.getOne(new QueryWrapper<NewSysOrg>().eq("org_id", orgId));
        if(org.getParentIds().contains(dbgkOrgId)){
            //东北港口
            queryWrapper.ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                    .eq(SysOrg.IS_DEPT, "0")
                    .like("parent_ids", dbgkOrgId)
                    .or().eq("org_id",dbgkOrgId)
                    .orderByAsc("tree_level", "tree_sort");
        }else{
            if(org.getTreeLevel().compareTo(BigDecimal.valueOf(4))==0){
                queryWrapper.ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                        .eq(SysOrg.IS_DEPT, "0")
                        .like("parent_ids", org.getParentId())
                        .or().eq("org_id",org.getParentId())
                        .orderByAsc("tree_level", "tree_sort");
            }else{
                queryWrapper.ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                        .eq(SysOrg.IS_DEPT, "0")
                        .like("parent_ids", org.getOrgId())
                        .or().eq("org_id",org.getOrgId())
                        .orderByAsc("tree_level", "tree_sort");
            }

        }
        return this.list(queryWrapper);
    }

    @Override
    public List<String> getIdsChildrenById(String orgId) {
        return getChildrenById(orgId).stream().map(NewSysOrg::getOrgId).collect(Collectors.toList());
    }

    @Override
    public List<NewSysOrg> getSubInstitutions(String orgId) {
        QueryWrapper<NewSysOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0")
                .eq("is_dept", "0")
                .like("parent_ids", "," + orgId)
                .orderByAsc("tree_level", "tree_sort");
        return this.list(queryWrapper);
    }

    @Override
    public List<String> getSubInstitutionIds(String orgId) {
        return getSubInstitutions(orgId).stream().map(NewSysOrg::getOrgId).collect(Collectors.toList());
    }

    public String getOrgFullPathName(String orgId) {
        StringBuilder fullName = new StringBuilder();
        NewSysOrg sysOrg = (NewSysOrg) this.getById(orgId);
        if (sysOrg == null || StringUtils.isBlank(sysOrg.getParentIds())) {
            return "";
        }
        List<String> pIds = Collections.arrayToList(StringHelper.split(sysOrg.getParentIds(), ","));
        int size = pIds.size();
        if (2 <= size) {
            Iterator var6 = pIds.iterator();

            while (var6.hasNext()) {
                String pid = (String) var6.next();
                if (!"0".equals(pid)) {
                    NewSysOrg pOrg = (NewSysOrg) this.getById(pid);
                    if (ObjectHelper.isNotEmpty(pOrg)) {
                        fullName.append(pOrg.getOrgName()).append("/");
                    }
                }
            }
        }

        fullName.append(sysOrg.getOrgName());
        return fullName.toString();
    }

    public List<NewSysOrg> getOrgListByParentId(String parentId) {
        QueryWrapper<NewSysOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0")
                .eq("is_dept", "0")
                .eq("parent_id", parentId)
                .orderByAsc("tree_level", "tree_sort");
        return this.list(queryWrapper);
    }

    @Override
    public List<String> getOrgIdListByParentId(String parentId) {
        List<NewSysOrg> orgListByParentId = getOrgListByParentId(parentId);
        return orgListByParentId.stream().map(NewSysOrg::getOrgId).collect(Collectors.toList());
    }


    public List<SysOrg> getOrgAllByLoginUser() {
        return this.sysOrgDao.getOrgAllByLoginUser(ContextUtils.getLoginUser().getParentIds(), ContextUtils.getLoginUser().getOrgId());
    }

    public List<NewSysOrg> getChildrenDept(String orgId) {
        QueryWrapper<NewSysOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0")
                .eq("is_dept", "1")
                .eq("parent_id", orgId)
                .orderByAsc("tree_level", "tree_sort");
        return this.list(queryWrapper);
    }

    @Override
    public NewSysOrg getSysOrgByCode(String code) {
        return this.getOne(new LambdaQueryWrapper<NewSysOrg>().eq(NewSysOrg::getOrgCode, code));
    }

    @Override
    public List<NewSysOrg> getOrgByIds(List<String> orgIds) {
        return this.list(new LambdaQueryWrapper<NewSysOrg>().in(NewSysOrg::getOrgId, orgIds).ne(NewSysOrg::getStatus, StatusEnum.DELETE.getCode()));
    }

    @Override
    public List<String> getChildDeptIdByParentId(String orgId) {
        return getChildrenDept(orgId).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
    }

    @Override
    public String getDeptIdByName(String name) {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        List<NewSysOrg> childrenDept = getChildrenDept(orgId);
        Map<String, String> map = StreamUtils.toMap(childrenDept, NewSysOrg::getOrgName, NewSysOrg::getOrgId);
        return map.get(name);
    }

    @Override
    public String getOrgNatureById(String orgId) {
        NewSysOrg byId = this.getById(orgId);
        String nature = byId.getNature();
        if (StringUtils.isBlank(nature)) {
            nature = String.valueOf(byId.getTreeLevel());
        }
        return nature;
    }

    @SneakyThrows
    @Override
    public SysOrgVo lookOrg(String orgId){
        if (StringUtils.isBlank(orgId)) {
            orgId = ContextUtils.getLoginUser().getOrgId();
        }
        NewSysOrg sysOrg = this.getById(orgId);
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("机构不存在");
        }
        String parentIdsString = sysOrg.getParentIds() + "," + orgId;
        //截取0后的父级id
        String[] parentIds = parentIdsString.substring(2).split(",");
        List<NewSysOrg> sysOrgList = this.lambdaQuery().in(SysOrg::getOrgId, parentIds).list();
        //赋值部门名称
        Map<String, String> sysOrgMap = sysOrgList.stream().collect(Collectors.toMap(SysOrg::getOrgId, SysOrg::getOrgName));
        SysOrgVo sysOrgVo = new SysOrgVo();
        sysOrgVo.setOrgId(sysOrg.getOrgId());
        sysOrgVo.setOrgName(sysOrg.getOrgName());
        sysOrgVo.setNature(StringUtils.isNotBlank(sysOrg.getNature()) ? sysOrg.getNature() : String.valueOf(sysOrg.getTreeLevel()));

        StringBuilder path = new StringBuilder();
        StringBuilder subSectorPath = new StringBuilder();
        StringBuilder subSectorPathIds = new StringBuilder();
        for (int i = 0; i < parentIds.length; i++) {
            if (i > 0) {
                subSectorPath.append("/");
                subSectorPathIds.append(",");
                path.append("/");
            }
            if (i+1 < parentIds.length) {
                subSectorPath.append(sysOrgMap.get(parentIds[i + 1]));
                subSectorPathIds.append(parentIds[i + 1]);
            }else {
                subSectorPath.append(sysOrgMap.get(parentIds[i]));
                subSectorPathIds.append(parentIds[i]);
            }
            path.append(sysOrgMap.get(parentIds[i]));
        }
        sysOrgVo.setPath(path.toString());
        sysOrgVo.setParentIds(StringUtils.join(parentIds, ","));
        sysOrgVo.setSubSectorPath(subSectorPath.toString());
        sysOrgVo.setSubSectorPathIds(subSectorPathIds.toString());
        return sysOrgVo;
    }

    @Override
    public String findOrgPathNameByOrgId(String orgId) {

        String fullName = "";
        NewSysOrg sysOrg = this.getById(orgId);
        if (sysOrg == null || StringUtils.isBlank(sysOrg.getParentIds())) {
            return "";
        }
        String paid = StringUtils.substringAfter(sysOrg.getParentIds(), ",");
        paid = StringUtils.substringAfter(paid, ",");
        List<String> pIds = Collections.arrayToList(StringHelper.split(paid, ","));
        for (String pid : pIds) {
            NewSysOrg pOrg = this.getById(pid);
            if (ObjectHelper.isNotEmpty(pOrg)) {
                fullName = fullName + pOrg.getOrgName() + "/";
            }
        }
        //return StringUtils.substringBeforeLast(fullName, "/");
        fullName = fullName + sysOrg.getOrgName();
        return fullName;

    }

    @Override
    public Integer getOrgTypeByOrgId(String orgId) {
        TSysConfig tSysConfig = tSysConfigService.getOne(new QueryWrapper<TSysConfig>().like("config_value", orgId).eq("status",0));
        if (ObjectHelper.isNotEmpty(tSysConfig)) {
            String configKey = tSysConfig.getConfigKey();
            if (configKey.equals("sys.beiliang.depts")) {
                return 1;
            }else if (configKey.equals("sys.beiliang.orgs")) {
                return 2;
            }
        }
       return 0;
    }

    @Override
    public List<NewSysOrg> getOrgByOrgName(String orgName) {
        return list(new QueryWrapper<NewSysOrg>().eq("org_name", orgName).eq("status", "0"));
    }

    @Override
    public List<String> dbgkChildOrgIds() {
        return baseMapper.dbgkChildOrgIds();
    }

    @Override
    public TSysOrg selectOrgByUserId(String userId) {
        return sysOrgDao.selectOrgByUserId(userId);
    }
}
