package com.blueland.service.impl;


/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since
 */

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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blueland.constant.RedisConstant;
import com.blueland.core.util.RedisUtils;
import com.blueland.bo.*;
import com.blueland.core.util.StringUtil;
import com.blueland.dao.TucStaffDao;

import com.blueland.model.TUcOrg;
import com.blueland.service.IParameterService;
import com.blueland.service.ITucOrgService;
import com.blueland.service.SysRedisService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.blueland.dao.TucOrgDao;
import com.blueland.constant.Constant;
import com.blueland.core.util.HttpUtils;
import com.blueland.core.util.JsonUtil;

@Service
@Slf4j
public class TucOrgServiceImpl extends ServiceImpl<TucOrgDao, TUcOrg> implements ITucOrgService {
    @Autowired
    //TucOrg对应的DAO类,主要用于数据库的增删改查等操作
    private TucOrgDao tucOrgDao;
    @Autowired
    private TucStaffDao tucStaffDao;
    @Autowired
    private IParameterService iParameterService;

    @Autowired
    private SysRedisService sysRedisService;


    @Override
    public Page<Org> getOrgSubs(Org entity) {
        if (null == entity || StringUtils.isEmpty(entity.getOrgId())) {
            throw new RuntimeException("组织ID不能为空");
        }
        Page<Org> pageInfo = null;
        if (entity.getPageNum() == null) {
            entity.setPageNum(1);
        }
        if (entity.getPageSize() == null) {
            entity.setPageSize(5);
        }
        if (StringUtil.isEmpty(entity.getOrgType())) {
            entity.setOrgType(entity.getOrgType());
        }
        //不能加此逻辑，前端要求将禁用数据也查询出来
		/*if(StringUtil.isEmpty(entity.getOrgStatus())) {
			entity.setOrgStatus(UserCenterConsts.ZT_STATUS_QY);
		}*/
        Org org = new Org();
        org.setQueryOrg(entity.getQueryOrg());
        List<Org> topOrgList = getTopOrg(entity.getOrgType());

        boolean topFlag = false;
        for (Org topOrg : topOrgList) {
            if (entity.getOrgId().equals(topOrg.getOrgId())) {
                topFlag = true;
            }
        }
        if (topFlag) {
            org.setOrgType(entity.getOrgType());
            org.setOrgSubType(entity.getOrgType());
            org.setOrgName(entity.getOrgName());
            org.setOrgFullName(entity.getOrgFullName());
            org.setOrgStatus(entity.getOrgStatus());
            org.setPageNum(entity.getPageNum());
            org.setPageSize(entity.getPageSize());
            org.setSortColumns(entity.getSortColumns());
            org.setOrgWorkType(entity.getOrgWorkType());
            Page<Org> page = new Page<>(entity.getPageNum(), entity.getPageSize());
            Page<Org> list = tucOrgDao.findPage(page, org);
            return list;
        } else {
            QueryWrapper<TUcOrg> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TUcOrg::getOrgId, entity.getOrgId());
            queryWrapper.lambda().eq(TUcOrg::getOrgType, entity.getOrgType());
            queryWrapper.lambda().eq(TUcOrg::getOrgStatus, entity.getOrgStatus());
            TUcOrg exsitsOrg = tucOrgDao.selectOne(queryWrapper);
            if (null != exsitsOrg && 1 == exsitsOrg.getOrgLevel()) {
                org.setCompanyId(entity.getOrgId());
                org.setOrgType(entity.getOrgType());
                org.setOrgName(entity.getOrgName());
                org.setOrgFullName(entity.getOrgFullName());
                org.setOrgStatus(entity.getOrgStatus());
                org.setPageNum(entity.getPageNum());
                org.setPageSize(entity.getPageSize());
                org.setSortColumns(entity.getSortColumns());
                org.setOrgWorkType(entity.getOrgWorkType());
                Page<Org> page = new Page<>(entity.getPageNum(), entity.getPageSize());
                Page<Org> list = tucOrgDao.findPage(page, org);
                return list;
            } else {
                Page<Org> page = new Page<>(entity.getPageNum(), entity.getPageSize());
                pageInfo = tucOrgDao.getOrgChildPage(page, org);
            }
        }
        return pageInfo;
    }

    /***
     * 获取组织顶级节点(前端用)
     * @param orgType 组织类型
     * @return
     */
    @Override
    public List<Org> getTopOrg(String orgType) {
//		if(StringUtil.isEmpty(orgType)) {
//			throw new ServiceException("组织类型不能为空");
//		}
        Org topOrg = new Org();
        topOrg.setOrgParentId("0");
        topOrg.setOrgStatus("QY");
        topOrg.setOrgType(orgType);
        return getListNoPage(topOrg);
    }

    /***
     * 没有分页的组织列表(前端用)
     */
    @Override
    public List<Org> getListNoPage(Org entity) {
        return tucOrgDao.getListNoPage(entity);
    }

    @Override
    public Page<Org> getOrgPage(Org org) {
        Page<Org> page = new Page<>(org.getPageNum(), org.getPageSize());
        return this.baseMapper.getOrgPage(page, org);
    }


    /***
     * 查询组织,往下遍历(前端用)
     */
    @Override
    public List<Org> getOrgChildLst(Org org) {
        if (null == org || StringUtils.isEmpty(org.getOrgId())) {
            throw new RuntimeException("组织ID不能为空");
        }
        if (StringUtil.isEmpty(org.getOrgType())) {
            org.setOrgType(org.getOrgType());
        }
        //不能加此逻辑，前端需要查询禁用数据
		/*if(StringUtil.isEmpty(org.getOrgStatus())) {
			org.setOrgStatus(UserCenterConsts.ZT_STATUS_QY);
		}*/
        return tucOrgDao.getOrgChildLst(org);
    }

    /**
     * 根据组织ID获取下级组织
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Org> getOrgChildLst(String orgId) {
        if (StringUtil.isEmpty(orgId)) {
            return new ArrayList<Org>();
        }
        return tucOrgDao.getChildLstByOrgId(orgId);
    }

    @Override
    public List<Map<String, Object>> handleTreeData(Org entity, List<Org> orgList) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (ObjectUtil.isNotEmpty(entity.getOrgId())) {
            Org org = this.baseMapper.getByOgId(entity.getOrgId());
            if (ObjectUtil.isNotEmpty(org)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map = new HashMap<String, Object>();
                map.put("id", org.getOrgId());
                map.put("name", org.getOrgName());
                map.put("parentId", org.getOrgParentId());
                map.put("type", "org");
                this.getSonTree(org.getOrgId(), map, orgList);
                result.add(map);
            }
        } else {
            List<Org> topOrgList = getTopOrg(entity.getOrgType());
            for (Org topOrg : topOrgList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map = new HashMap<String, Object>();
                map.put("id", topOrg.getOrgId());
                map.put("name", topOrg.getOrgName());
                map.put("parentId", topOrg.getOrgParentId());
                map.put("type", "org");
                this.getSonTree(topOrg.getOrgId(), map, orgList);
                result.add(map);
            }
        }
        return result;
    }

    private Map<String, Object> getSonTree(String orgid, Map<String, Object> map, List<Org> itemList) {
        List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
        for (Org item : itemList) {
            if (map.get("id").toString().equals(item.getOrgParentId().toString())) {
                Map<String, Object> child = new HashMap<String, Object>();
                child.put("id", item.getOrgId());
                child.put("name", item.getOrgName());
                child.put("parentId", item.getOrgParentId());
                child.put("type", "org");
                children.add(child);
                this.getSonTree(orgid, child, itemList);
            }
        }
        map.put("children", children);
        return map;
    }

    @Override
    public List<Org> findOrgIdList(Org org) {
        // TODO Auto-generated method stub
        List<Org> orgList = tucOrgDao.findOrgIdList(org);
        return orgList;
    }


    @Override
    public Org findOrgById(String orgId) {
        Org org = tucOrgDao.getByOgId(orgId);
        return org;
    }

    @Override
    public List<TreeEntity> searchOrg(Org org) {
        return tucOrgDao.searchOrg(org);
    }

    /**
     * 功能描述:获取点击节点下一层级数据
     *
     * @param: [orgType 组织类型, type 选人组件类型, id 父id, orgId 组织id]
     * @return: java.util.List<com.blueland.model.TreeEntity>
     * @auther: lg 540923947@qq.com
     * @date: 2019/5/9 17:17
     */
    @Override
    public List<TreeEntity> getTree(String orgType, String type, String id, String orgId, String staffName) {
        Org org = new Org();
        org.setOrgStatus("QY");
        org.setSortColumns("org_sort");
        org.setOrgType(orgType);
        /**
         * 如果传了指定的部门id就取指定部门
         * 否则默顶级节点认为0
         */
        if (ObjectUtil.isNotEmpty(orgId)) {
            org.setOrgId(orgId);
        } else {
            if (StringUtil.isEmpty(id)) {
                org.setOrgParentId("0");
            } else {
                org.setOrgParentId(id);
            }
        }
        List<TreeEntity> list = tucOrgDao.searchOrg(org);
        if ("org".equals(type)) {
            list = this.judgeLeaf(list, orgType);
        } else if (("staff".equals(type) || "all".equals(type))
                && (ObjectUtil.isNotEmpty(staffName) || ObjectUtil.isNotEmpty(id))) {
//            if (Objects.equals("staff", type)) {
//                list = new ArrayList<>();
//            }
            TucStaffEntity tucStaffEntity = new TucStaffEntity();
            tucStaffEntity.setStaffStatus("QY");
            if (ObjectUtil.isNotEmpty(id)) {
                tucStaffEntity.setOrgId(id);
            }
            if (ObjectUtil.isNotEmpty(staffName)) {
                tucStaffEntity.setStaffName(staffName);
            }
            List<TreeEntity> staffTreeList = tucStaffDao.searchUser(tucStaffEntity);
            list.addAll(staffTreeList);
        }
        return list;
    }

    /**
     * 判断获取的组织下是否还存在组织（数据是否是叶节点）
     *
     * @param list
     * @return
     */
    @Override
    public List<TreeEntity> judgeLeaf(List<TreeEntity> list, String orgType) {
        Org org = new Org();
        org.setOrgStatus("QY");
        org.setOrgType(orgType);
        for (TreeEntity treeEntity : list) {
            org.setOrgParentId(treeEntity.getId());
            List<Org> tempList = tucOrgDao.findList(org);
            if (!tempList.isEmpty() && tempList.size() > 0) {
                treeEntity.setLeaf(false);
            } else {
                treeEntity.setLeaf(true);
            }
        }
        return list;
    }

    /**
     * 20200827 add
     * 获取 当前员工部门全名称
     *
     * @return
     */
    @Override
    public String getfulldeptname(String deptId) {
        String fulldeptname = "";
        if (ObjectUtil.isNotEmpty(deptId)) {
            Org org = new Org();
            org.setOrgStatus("QY");
            org.setDeptId(deptId);
            List<Org> dborgList = tucOrgDao.findList(org);
            Org dborg = null;
            if (null != dborgList && dborgList.size() > 0) {
                dborg = dborgList.get(0);
            }
            if (dborg != null) {
                String parentId = dborg.getOrgParentId();
                fulldeptname = dborg.getDeptName();
                if (deptId.length() <= 9) {
                    return fulldeptname;
                } else {
                    while (true) {
                        Org parent = tucOrgDao.getByOgId(parentId);
                        if (null != parent) {
                            parentId = parent.getOrgParentId();
                            fulldeptname = parent.getDeptName() + ">" + fulldeptname;
                            if (parent.getDeptId().length() == 9) {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return fulldeptname;
    }

    /**
     * 同步部门数据到CRM
     *
     * @param model
     * @author hpp
     * @Time 2020年12月3日 上午11:11:49
     */
    @Async
    @Override
    public void syncDept2CRM(Org model) {
        try {
            String deptcode = model.getDeptId();
            Map<String, String> params = new HashMap<String, String>();
            params.put("deptcode", deptcode);
            params.put("deptname", model.getDeptName());
            if (deptcode.startsWith("A01A01")) {
                params.put("tenantid", "BIO");
            } else {
                params.put("tenantid", "IVD");
            }
            ParameterEntity parameter = iParameterService.getBykey("crm_token");
            ParameterEntity crmUrl = iParameterService.getBykey("crmrender_url");
            System.out.println(JsonUtil.convertBeanToJsonStr(params));
            Map<String, Object> result = HttpUtils.getInstance().postForObject(
                    crmUrl.getPvalue() + "/api/deptduty/syncdept", JsonUtil.convertBeanToJsonStr(params), null,
                    Map.class, parameter.getPvalue());
//            log.info(JsonUtil.convertBeanToJsonStr(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有销售办事处
     *
     * @return
     * @author hpp
     * @Time 2020年12月7日 上午10:10:31
     */
    @Override
    public List<Map<String, String>> getAllSellorg(String tenantid) {
        String startDeptcode = "";
        if (Constant.TENANTID_BIO.equals(tenantid)) {
            startDeptcode = "A01A01";
        }
        return tucOrgDao.getOrgByWorktype(startDeptcode, Constant.ORGWORKTYPE_SELL);

    }

    @Override
    public Org get(Org bo) {
        return this.baseMapper.getOne(bo);
    }

    @Override
    public Org getByAppId(Org bo) {
        return this.baseMapper.getByAppId(bo);
    }

    @Override
    public List<Org> findList(Org bo) {
        return this.baseMapper.findList(bo);
    }

    @Override
    public Page<Org> findPage(Org bo) {
        Page<Org> page = new Page(bo.getPageNum(), bo.getPageSize());
        return this.baseMapper.findPage(page, bo);
    }

    @Override
    public String getTenantId(String deptId) {
        QueryWrapper<TUcOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TUcOrg::getDeptId, deptId);
        queryWrapper.lambda().eq(TUcOrg::getOrgStatus, Constant.QY);
        List<TUcOrg> list = this.baseMapper.selectList(queryWrapper);
        String appId = "";
        if (ObjectUtil.isNotEmpty(list) && ObjectUtil.isNotEmpty(list.get(0).getAppId())) {
            appId = list.get(0).getAppId();
        }
        return appId;
    }

    @Override
    public List<Org> selectOrgByDeptIds(List<String> deptIds) {
        List<Org> list = sysRedisService.getOrgList(deptIds);
        if (ObjectUtil.isEmpty(list)) {
            Org bo = new Org();
            bo.setOrgStatus(Constant.QY);
            bo.setDeptIds(deptIds);
            list = this.baseMapper.findList(bo);
        }
        return list;
    }

    @Override
    public List<Org> selectOrgByErpCodes(List<String> erpCodes) {
        Org bo = new Org();
        bo.setOrgStatus(Constant.QY);
        bo.setErpCodes(erpCodes);
        List<Org> list = this.baseMapper.findList(bo);
        return list;
    }

    @Override
    public Integer countOrgById(String id, String appId) {
        return this.baseMapper.countOrgById(id, appId);
    }

    @Override
    public List<TUcOrg> handleOrg(Org org) {
        List<TUcOrg> addList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(org)) {
//            String appId = this.baseMapper.getAppIdByParentId(org.getOrgParentId());
            ParameterEntity bo = new ParameterEntity();
            bo.setPkey(Constant.ORG_APP);
            List<ParameterEntity> configList = iParameterService.findList(bo);
            if (ObjectUtil.isNotEmpty(configList)) {
                for (ParameterEntity entity : configList) {
                    // 部门id长度小于配置的长度，直接跳出当次循环
                    if (org.getDeptId().length() < entity.getPvalue().length()) {
                        continue;
                    }
                    // 截取和配置一样的长度进行匹配
                    String deptId = StrUtil.sub(org.getDeptId(), 0, entity.getPvalue().length());
                    // 判断部门和租户的关系，如果对应多个则每个租户都新增一条数据
                    if (Objects.equals(entity.getPvalue(), deptId) && this.baseMapper.countOrgById(org.getDeptId(), entity.getAppId()) <= 0) {
                        TUcOrg model = BeanUtil.copyProperties(org, TUcOrg.class);
//                        if (ObjectUtil.isNotEmpty(org.getDeptId()) && org.getDeptId().length() > 3) {
////                            String code = StrUtil.sub(org.getDeptId(), 0, org.getDeptId().length() - 3);
//                            String parentId = this.baseMapper.getOrgIdByAppId(entity.getAppId(), org.getOrgParentId());
//                            model.setOrgParentId(parentId);
//                        }
                        model.setId(null);
                        model.setAppId(entity.getAppId());
                        model.setOrgCreateTime(new Date());
                        org.setAppId(entity.getAppId());
                        addList.add(model);
                    }
                }
            }
        }
        return addList;
    }

    @Override
    public void deleteOrgByAppId(String appId) {
        this.baseMapper.deleteOrgByAppId(appId);
    }

    @Override
    public String getTopOrgId() {
        return this.baseMapper.getTopOrgId();
    }

    @Override
    public String getSellOrgId(String deptCode) {
        return this.baseMapper.getSellOrgId(deptCode);
    }

    @Override
    public String getAppIdByParentId(String parentId) {
        return this.baseMapper.getAppIdByParentId(parentId);
    }

    @Override
    public Org getByOgId(String orgId) {
        return this.baseMapper.getByOgId(orgId);
    }

    @Override
    public Org getByOgIdAndType(String orgId, String type) {
        return this.baseMapper.getByOgIdAndType(orgId, type);
    }

    private LambdaQueryWrapper<TUcOrg> buildQueryWrapper(Org bo) {
        LambdaQueryWrapper<TUcOrg> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgId()), TUcOrg::getOrgId, bo.getOrgId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgName()), TUcOrg::getOrgName, bo.getOrgName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgFullName()), TUcOrg::getOrgFullName, bo.getOrgFullName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgSpells()), TUcOrg::getOrgSpells, bo.getOrgSpells());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgFullSpells()), TUcOrg::getOrgFullSpells, bo.getOrgFullSpells());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgParentId()), TUcOrg::getOrgParentId, bo.getOrgParentId());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgType()), TUcOrg::getOrgType, bo.getOrgType());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgLevel()), TUcOrg::getOrgLevel, bo.getOrgLevel());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgMgrType()), TUcOrg::getOrgMgrType, bo.getOrgMgrType());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgWorkAddress()), TUcOrg::getOrgWorkAddress, bo.getOrgWorkAddress());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgWorkPhone()), TUcOrg::getOrgWorkPhone, bo.getOrgWorkPhone());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgWorkType()), TUcOrg::getOrgWorkType, bo.getOrgWorkType());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgStatus()), TUcOrg::getOrgStatus, bo.getOrgStatus());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgParentId()), TUcOrg::getOrgParentId, bo.getOrgParentId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgParentName()), TUcOrg::getOrgParentName, bo.getOrgParentName());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getCompanyId()), TUcOrg::getCompanyId, bo.getCompanyId());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgBranchLeader()), TUcOrg::getOrgBranchLeader, bo.getOrgBranchLeader());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getDeptId()), TUcOrg::getDeptId, bo.getDeptId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgSubType()), TUcOrg::getOrgSubType, bo.getOrgSubType());
        lqw.like(ObjectUtil.isNotEmpty(bo.getDeptName()), TUcOrg::getDeptName, bo.getDeptName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getCompanyName()), TUcOrg::getCompanyName, bo.getCompanyName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getOrgBranchLeaderName()), TUcOrg::getOrgBranchLeaderName, bo.getOrgBranchLeaderName());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgCreator()), TUcOrg::getOrgCreator, bo.getOrgCreator());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgUpdator()), TUcOrg::getOrgUpdator, bo.getOrgUpdator());
        return lqw;
    }
}
