package com.dgtly.sync.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.ShiroSaltUtil;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.UserIdentityUtil;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.sync.domain.MetaEmployee;
import com.dgtly.sync.domain.SyncFailDetail;
import com.dgtly.sync.domain.SyncLog;
import com.dgtly.sync.exception.*;
import com.dgtly.sync.mapper.MetaDiySalesorgtreeMapper;
import com.dgtly.sync.mapper.MetaEmployeeMapper;
import com.dgtly.sync.mapper.SyncFailDetailMapper;
import com.dgtly.sync.service.IAnalysisSysUserService;
import com.dgtly.sync.service.ISyncLogService;
import com.dgtly.system.domain.*;
import com.dgtly.system.mapper.SysRoleMapper;
import com.dgtly.system.mapper.SysUserExtMapper;
import com.dgtly.system.mapper.SysUserRoleMapper;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.system.service.ISysDictDataService;
import com.dgtly.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//立邦员工
@Service("analysisDiyCustomerService")
public class AnalysisSysUserService implements IAnalysisSysUserService {

    private static final Logger log = LoggerFactory.getLogger(AnalysisSysUserService.class);

    @Autowired
    private SyncFailDetailMapper syncFailDetailMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private MetaEmployeeMapper MetaEmployeeDiyMapper;
    @Autowired
    private MetaDiySalesorgtreeMapper metaDiySalesorgtreeMapper;
    @Autowired
    private ISyncLogService syncLogService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    @SuppressWarnings("all")
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserExtMapper sysUserExtMapper;

    private  String [] paintRoleKeys = {"shopStoneLikePaint"};

    private  String [] goldPoleKeys = {"goldShopUser"};;

    /**
     * 解析DIY用户数据  异步执行（new）
     * @param packageId
     * @return
     */
    @Override
    @Async
    public SyncLog analysisSysUser(String packageId){
        //解析逻辑件DIY用户逻辑.jpg
        MetaEmployee param = new MetaEmployee();
        if(packageId==null||packageId.trim().equals("")){
            Long l = new Date().getTime();
            packageId = l.toString();
        }else{
            param.setPackageId(packageId);
        }
        param.setBusinessUnit("DIY");

        List<MetaEmployee> MetaEmployees = MetaEmployeeDiyMapper.selectMetaEmployeeDiyCopy1List(param);
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysuser");
        syncLog.setStartTime(new Date());

        Set<String> loginNameList = sysUserService.selectAllUserLoginName();


        syncLog.setPackageId(packageId);
        syncLog.setTotalCount((long)MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;

        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.roleid"));
        //推荐下单角色仅限销售部和销售员
        Long recommendRoleId = Long.parseLong(configService.selectConfigByKey("libang.user.recommend.roleid"));
        //自提角色
        Long selfRoleId = Long.parseLong(configService.selectConfigByKey("libang.user.self.roleid"));
        Long[] roleIds = {roleId};
        //Long[] recommendRoleIds = {roleId,recommendRoleId};推荐下单
        Long[] selfRoleIdAndRecommendRoleIds = {recommendRoleId,selfRoleId,roleId};
        Long[] officeRolesIds = {selfRoleId,roleId};
        if(MetaEmployees.size()>0){

            //用户objid3为列表内的内容才为DIY人员
            Set<String> diyObjid3Set =  getConfigValueSet("libang_diyobjid3");
            //用户岗位名称为列表的内容才是区公司级别人员
            Set<String> companySet =  getConfigValueSet("libang_company_level_postname");
            //用户岗位名称为列表的内容才是销售大区级别人员(此层级已废弃)
            Set<String> saledeptSet =  getConfigValueSet("libang_saledept_level_postname");
            //用户岗位名称为列表的内容才是销售部级别人员
            Set<String> officeSet =  getConfigValueSet("libang_office_level_postname");
            //用户岗位名称为列表的内容才是销售分部级别人员
            Set<String> subofficeSet =  getConfigValueSet("libang_suboffice_level_postname");
            //用户岗位名称为列表的内容才是销售员级别人员
            Set<String> empSet =  getConfigValueSet("libang_emp_level_postname");
            Map<Integer,Map<String,Map<String,String>>>  salesTreeMap = getDiySalesOrgTree();



            for(MetaEmployee m:MetaEmployees) {
                try {
                    //todo
//                    if(!m.getLoginName().equalsIgnoreCase("wangzhen")){
//                        continue;
//                    }

                    //用户是否属于DIY筛选范围
//                    if(!diyObjid3Set.contains(m.getStext3())){
//                        throw new OutOfScopeDIYException(m);
//                    }
                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    user.setRoleIds(roleIds);
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);

                    //判断用户所处销售层级
                    //先啊判断用户所属的岗位名称确定销售部门
                    if(companySet.contains(postName) || empSet.contains(postName)||subofficeSet.contains(postName)||officeSet.contains(postName)||saledeptSet.contains(postName)){
                    if (companySet.contains(postName)) {
                        //先处理特殊的第三级 区公司级别
                        userExt.setOrgName(m.getStext5());
                        int i = getLevel(userExt, salesTreeMap);
                        if (i == 4) {//职位都有时判断部门 大区
                            userExt.setSalesLevel("office_level");
                        } else {
                            userExt.setSalesLevel("company_level");
                            user.setRoleIds(officeRolesIds);
                            userExt.setOrgName(m.getStext3());
                            setExtOrgCodeOn3(salesTreeMap, userExt);
                        }
                    //判断用户u岗位是否在销售员敢为、销售分部岗位、销售部岗位、销售大区岗位中
                    }
                    if(empSet.contains(postName)||subofficeSet.contains(postName)||officeSet.contains(postName)||saledeptSet.contains(postName)){
                            //获取最后所属的部门名称
                            String orgName = getStext(m);
                            if(orgName.indexOf("通路推广组")!=-1){
                                orgName =  getStextSecond(m);
                            }
                            userExt.setOrgName(orgName);
                            int i = getLevel(userExt,salesTreeMap);
                            if (i == -1) {
                                //失败后取上一层
                                orgName = getStextSecond(m);
                                userExt.setOrgName(orgName);
                                i = getLevel(userExt, salesTreeMap);
                                if (i == -1) {
                                    throw new NotFountOrgCodeException(m);
                                }
                            }
                            switch (i){
                                case 5:
                                    if(empSet.contains(m.getEmployeePostName())){
                                        //等级6 销售员
                                        userExt.setSalesLevel("emp_level");
                                        user.setRoleIds(selfRoleIdAndRecommendRoleIds);
                                    }else if(subofficeSet.contains(m.getEmployeePostName())){
                                        //等级6 销售分部
                                        userExt.setSalesLevel("suboffice_level");
                                        user.setRoleIds(selfRoleIdAndRecommendRoleIds);
                                    }
                                    break;
                                case 4:
                                    userExt.setSalesLevel("office_level");
                                    user.setRoleIds(officeRolesIds);
                                    break;
                                case 3:
                                    userExt.setSalesLevel("company_level");
                                    user.setRoleIds(officeRolesIds);
                                    break;
                            }
                        }
                    }else {
                            log.error("DIY用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                            SyncFailDetail syncFailDetail = new SyncFailDetail();
                            syncFailDetail.setPackageId(packageId);
                            syncFailDetail.setFailReason("DIY用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                            syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                            syncFailDetail.setFailLevel("1");
                            syncFailDetail.setExceptionType("not found post");
                            failDetails.add(syncFailDetail);
                            failCount++;
                            user.setSysUserExt(userExt);
                            user.setUpdateTime(new Date());
                            this.save(user,m);
                            continue;
                        }

                        if (StringUtils.isEmpty(userExt.getOrgCode())){
                            log.error("DIY用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                            SyncFailDetail syncFailDetail = new SyncFailDetail();
                            syncFailDetail.setPackageId(packageId);
                            syncFailDetail.setFailReason("DIY用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                            syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                            syncFailDetail.setFailLevel("1");
                            syncFailDetail.setExceptionType("not found dept");
                            failDetails.add(syncFailDetail);
                            failCount++;
                            user.setSysUserExt(userExt);
                            user.setUpdateTime(new Date());
                            this.save(user,m);
                            continue;
                        }


//                    if(userExt.getOrgCode()==null){
//                        throw new NotFountOrgCodeException(m);
//                    }

                    /**======== 构建diy用户扩展信息表 end===============*/
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        /**  更新 */
                        SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
                        if("1".equals(sysUser.getIsSync())){
                            continue;
                        }
                        if(!userExt.getSalesLevel().equals(sysUser.getSysUserExt().getSalesLevel())){
                            sysUserService.deleteByLoginName(user.getLoginName());
                        }
                        //if(!sysUser.getSysUserExt().getPostCode().equals(userExt.getPostCode())){
                            System.out.println("解析diy部门不一致情况原/新"+sysUser.getSysUserExt().getPostCode()+"/"+userExt.getPostCode());
                            SysUserRole role=new SysUserRole();
                            role.setUserId(sysUser.getUserId());
                            userRoleMapper.deleteUserRoleInfo(role);
                            user.setUserId(sysUser.getUserId());
                            insertUserRole(user);
                        //}

                        /*if(!"diy_level".equals(sysUser.getSysUserExt().getSalesLevel())){*/
                            user.setSysUserExt(userExt);
                        //}
                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        /**  插入 */
                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                }catch (OutOfScopeDIYException|NotFountOrgCodeException|OutOfDIYPostNameException|OutOfLeveLException|NotOrgNameException e){
                    /**
                     * 警告类异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                }catch (Exception e) {
                    /**
                     * 错误异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        }else{
            syncLog.setSuccessCount(0L);
            syncLog.setFaileCount(0L);
        }
        try{
            syncLog.setPackageId(packageId);
            syncLog.setEndTime(new Date());
            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;

    }

    /**
     * @param
     * @description: 解析零售下事业部人员
     * @param:
     * @return:
     * @author: njs
     * @date: 2023/5/10 10:12
     */
    @Override
    public SyncLog analysisSysDivisionUser() {
        Long l = new Date().getTime();
        String packageId = l.toString();
        //解析零售下事业部人员直接sql查
        List<MetaEmployee> MetaEmployees = MetaEmployeeDiyMapper.selectMetaEmployeeDiyListByDivision();
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysuserDivision");
        syncLog.setStartTime(new Date());
        Set<String> loginNameList = sysUserService.selectAllUserLoginName();
        syncLog.setTotalCount((long)MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;
        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.division.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.division.roleid"));
        Long[] roleIds = {roleId};
        Map<Integer,Map<String,Map<String,String>>>  salesTreeMap = getDiySalesOrgTree();
        if(MetaEmployees.size()>0){
            for(MetaEmployee m:MetaEmployees) {
                try {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    user.setRoleIds(roleIds);
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);
                    userExt.setSalesLevel("division_level");
                    userExt.setOrgName(m.getStext3());
                    setExtOrgCodeOn2(salesTreeMap, userExt);
                    if (StringUtils.isEmpty(userExt.getOrgCode())){
                        log.error("DIY-事业部用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("DIY-事业部用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found dept");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }

                    /**======== 构建diy用户扩展信息表 end===============*/
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        /**  更新 */
                        SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
                        if("1".equals(sysUser.getIsSync())){
                            continue;
                        }
                        if(!userExt.getSalesLevel().equals(sysUser.getSysUserExt().getSalesLevel())){
                            sysUserService.deleteByLoginName(user.getLoginName());
                        }
                        //if(!sysUser.getSysUserExt().getPostCode().equals(userExt.getPostCode())){
                        System.out.println("解析DIY-事业部部门不一致情况原/新"+sysUser.getSysUserExt().getPostCode()+"/"+userExt.getPostCode());
                        SysUserRole role=new SysUserRole();
                        role.setUserId(sysUser.getUserId());
                        role.setRoleId(user.getRoleIds()[0]);
                        userRoleMapper.deleteUserRoleInfo(role);
                        user.setUserId(sysUser.getUserId());
                        insertUserRole(user);
                        //}


                        user.setSysUserExt(userExt);

                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        /**  插入 */
                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                }catch (OutOfScopeDIYException|NotFountOrgCodeException|OutOfDIYPostNameException|OutOfLeveLException|NotOrgNameException e){
                    /**
                     * 警告类异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                }catch (Exception e) {
                    /**
                     * 错误异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析DIY-事业部用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        }else{
            syncLog.setSuccessCount(0L);
            syncLog.setFaileCount(0L);
        }
        try{
            syncLog.setPackageId(packageId);
            syncLog.setEndTime(new Date());
            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析DIY-事业部用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析DIY-事业部用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;

    }

    /**
     * @description: 处理应用服务本部的人，只给门店拜访权限
     * @param: []
     * @return: com.dgtly.sync.domain.SyncLog
     * @author: njs
     * @date: 2025/5/8 14:02
     */
    @Override
    public SyncLog analysisSysApplicationServiceUser() {
        //解析逻辑件DIY用户逻辑.jpg
        MetaEmployee param = new MetaEmployee();
        param.setBusinessUnit("应用服务本部");
        Long l = new Date().getTime();
        String packageId = l.toString();
        List<MetaEmployee> MetaEmployees = MetaEmployeeDiyMapper.selectMetaEmployeeDiyCopy1List(param);
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysuserApplicationService");
        syncLog.setStartTime(new Date());
        Set<String> loginNameList = sysUserService.selectAllUserLoginName();
        syncLog.setTotalCount((long)MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;
        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.applicationService.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.applicationService.roleid"));
        Long[] roleIds = {roleId};
        Map<Integer,Map<String,Map<String,String>>>  salesTreeMap = getDiySalesOrgTree();
        if(MetaEmployees.size()>0){
            for(MetaEmployee m:MetaEmployees) {
                try {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    user.setRoleIds(roleIds);
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);
                    userExt.setSalesLevel("applicationService_level");
                    userExt.setOrgName(m.getStext3());
                    userExt.setOrgCode(m.getObjid3());
                    if (StringUtils.isEmpty(userExt.getOrgCode())){
                        log.error("应用服务本部用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("应用服务本部用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found dept");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }

                    /**======== 构建diy用户扩展信息表 end===============*/
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        /**  更新 */
                        SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
                        if("1".equals(sysUser.getIsSync())){
                            continue;
                        }
                        if(!userExt.getSalesLevel().equals(sysUser.getSysUserExt().getSalesLevel())){
                            sysUserService.deleteByLoginName(user.getLoginName());
                        }
                        System.out.println("解析应用服务本部用户不一致情况原/新"+sysUser.getSysUserExt().getPostCode()+"/"+userExt.getPostCode());
                        SysUserRole role=new SysUserRole();
                        role.setUserId(sysUser.getUserId());
                        userRoleMapper.deleteUserRoleInfo(role);
                        user.setUserId(sysUser.getUserId());
                        insertUserRole(user);


                        user.setSysUserExt(userExt);

                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        /**  插入 */
                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                }catch (OutOfScopeDIYException|NotFountOrgCodeException|OutOfDIYPostNameException|OutOfLeveLException|NotOrgNameException e){
                    /**
                     * 警告类异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                }catch (Exception e) {
                    /**
                     * 错误异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析应用服务本部用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        }else{
            syncLog.setSuccessCount(0L);
            syncLog.setFaileCount(0L);
        }
        try{
            syncLog.setPackageId(packageId);
            syncLog.setEndTime(new Date());
            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析应用服务本部用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析应用服务本部用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;

    }


    /**
     * 解析CW用户数据  异步执行
     * @param packageId
     * @return
     */
   /* @Override
    @Async
    public SyncLog analysisSysCwUser(String packageId) {
        MetaEmployee param = new MetaEmployee();
        if (packageId == null || packageId.trim().equals("")) {
            Long l = new Date().getTime();
            packageId = l.toString();
        } else {
            param.setPackageId(packageId);
        }

        param.setBusinessUnit("CW");
        param.setStext3("厨卫底材事业部");//厨卫底材事业部

        List<MetaEmployee> MetaEmployees = MetaEmployeeMapper.selectMetaEmployeeList(param);
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysusercw");
        syncLog.setStartTime(new Date());

        Set<String> loginNameList = sysUserService.selectAllUserLoginName();

        syncLog.setPackageId(packageId);
        syncLog.setTotalCount((long) MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;

        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.cw.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.cw.roleid"));
        Long[] roleIds = {roleId};
        if (MetaEmployees.size() > 0) {

            Set<String> companyPostNameSet = getConfigValueSet("cw_comp_postname");
            Set<String> companyDeptPostNameSet = getConfigValueSet("cw_comp_dept_postname");
            Set<String> companyEndPostNameSet = getConfigValueSet("cw_comp_end_postname");

            Set<String> deptPostNameSet = getConfigValueSet("cw_dept_postname");
            Set<String> officePostNameSet = getConfigValueSet("cw_office_postname");
            Set<String> empPostNameSet = getConfigValueSet("cw_emp_postname");

            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiySalesOrgTreeY9();

            for (MetaEmployee m : MetaEmployees) {
                try {
                    //用户是否属于DIY筛选范围
//                    if(!diyObjid3Set.contains(m.getStext3())){
//                        throw new OutOfScopeDIYException(m);
//                    }
                    *//** =============用户基本信息构建 start===============*//*
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    user.setRoleIds(roleIds);
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    *//** =============用户基本信息构建 end===============*//*


                    *//**======== 构建diy用户扩展信息表 start===============*//*
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);

                    String orgName = getStext(m);

                    if (companyPostNameSet.contains(postName) || companyDeptPostNameSet.contains(orgName) || companyEndPostNameSet.contains(orgName)) {
                        if (companyEndPostNameSet.contains(orgName)) {
                            if (postName != null && (postName.trim().endsWith("部主管") || postName.trim().endsWith("部门主管")
                                    || postName.trim().endsWith("部主管（代）") || postName.trim().endsWith("部门主管（代）"))) {
                                userExt.setSalesLevel("cw_diy");
                            }else{
                                throw new OutOfDIYPostNameException(m);
                            }
                        } else {
                            userExt.setSalesLevel("cw_diy");
                        }
                    } else if (deptPostNameSet.contains(postName)) {
                        userExt.setSalesLevel("cw_dept");
                        userExt.setOrgName(m.getStext4());
                        setExtOrgCodeY9(salesTreeMap, 3, userExt);
                    } else if (officePostNameSet.contains(postName)) {
                        userExt.setSalesLevel("cw_office");
                        userExt.setOrgName(m.getStext5());
                        setExtOrgCodeY9(salesTreeMap, 4, userExt);
                    } else if (empPostNameSet.contains(postName)) {
                        userExt.setSalesLevel("cw_emp");
                        userExt.setOrgName(m.getStext5());
                        //userExt.setOrgCode(m.getSapEmployeeId());
                        setExtOrgCodeY9(salesTreeMap, 4, userExt);
                    } else {
                        log.error("CW用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("CW用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found post");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }

                    if (StringUtils.isEmpty(userExt.getOrgCode())){
                        log.error("CW用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("CW用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found dept");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }


                    *//**======== 构建diy用户扩展信息表 end===============*//*
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        *//**  更新 *//*
                        SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
                        if("1".equals(sysUser.getIsSync())){
                            continue;
                        }
                      *//*  if(sysUser.getSysUserExt().getSalesLevel().equals("cw_emp")){
                            setExtOrgCodeY9(salesTreeMap, 4, userExt);
                            sysUserExtMapper.updateSysUserExt(sysUser.getSysUserExt());
                        }*//*
                        if(!userExt.getSalesLevel().equals(sysUser.getSysUserExt().getSalesLevel())){
                            sysUserService.deleteByLoginName(user.getLoginName());
                        }
                        //if(!sysUser.getSysUserExt().getPostCode().equals(userExt.getPostCode())){
                            log.error("解析cw部门不一致情况原/新", sysUser.getSysUserExt().getPostCode()+"/"+userExt.getPostCode());
                            SysUserRole role=new SysUserRole();
                            role.setUserId(sysUser.getUserId());
                            userRoleMapper.deleteUserRoleInfo(role);
                            user.setUserId(sysUser.getUserId());
                            insertUserRole(user);
                       // }

                        if (!"diy_level".equals(sysUser.getSysUserExt().getSalesLevel())) {
                            user.setSysUserExt(userExt);
                        }
                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        *//**  插入 *//*

                        userExt.setIdentity(UserIdentityUtil.UI_CW);

                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                } catch (OutOfScopeDIYException | NotFountOrgCodeException | OutOfDIYPostNameException | OutOfLeveLException | NotOrgNameException e) {
                    *//**
                     * 警告类异常
                     *//*
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                } catch (Exception e) {
                    *//**
                     * 错误异常
                     *//*
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析cw用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        } else {
            syncLog.setSuccessCount(0l);
            syncLog.setFaileCount(0l);
        }
        try {
            syncLog.setEndTime(new Date());
            if (failDetails.size() > 0) {
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        } catch (Exception e) {
            log.error("解析cw用户插入解析日志出错", e);
            e.printStackTrace();
            throw new BusinessException("解析cw用户插入解析日志出错", e);
        } finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;
    }*/

    @Override
    public SyncLog analysisSysYSLUser(String packageId) {
        MetaEmployee param = new MetaEmployee();
        if (packageId == null || packageId.trim().equals("")) {
            Long l = new Date().getTime();
            packageId = l.toString();
        } else {
            param.setPackageId(packageId);
        }

        param.setBusinessUnit("YSL");
        param.setStext3("雅士利");

        List<MetaEmployee> MetaEmployees = MetaEmployeeDiyMapper.selectMetaEmployeeDiyCopy1List(param);
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysuserysl");
        syncLog.setStartTime(new Date());

        Set<String> loginNameList = sysUserService.selectAllUserLoginName();

        syncLog.setPackageId(packageId);
        syncLog.setTotalCount((long) MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;

        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.ysl.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.ysl.roleid"));
        Long[] roleIds = {roleId};
        if (MetaEmployees.size() > 0) {

            String deptName = configService.selectConfigByKey("ysl.dept.orgName");
            String deptCode = configService.selectConfigByKey("ysl.dept.orgCode");

            Set<String> companyPostNameSet = getConfigValueSet("ysl_comp_postname");
            Set<String> officePostNameSet = getConfigValueSet("ysl_office_postname");
            Set<String> empPostNameSet = getConfigValueSet("ysl_emp_postname");
            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiyYSLSalesOrgTree();
            for (MetaEmployee m : MetaEmployees) {
                try {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    user.setRoleIds(roleIds);
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    /** =============用户基本信息构建 end===============*/

                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);

                    if (companyPostNameSet.contains(postName)) {
                        userExt.setSalesLevel("ysl_diy");
                        userExt.setOrgName(deptName);
                        userExt.setOrgCode(deptCode);
                    } else if (officePostNameSet.contains(postName)) {
                        userExt.setSalesLevel("ysl_office");
                        userExt.setOrgName(m.getStext5());
                        setExtOrgCodeY9(salesTreeMap, 4, userExt);
                    } else if (empPostNameSet.contains(postName)) {
                        userExt.setSalesLevel("ysl_emp");
                        userExt.setOrgName(m.getStext5());
                        setExtOrgCodeY9(salesTreeMap, 4, userExt);
                    } else {
                        log.error("YSL用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("YSL用户对应的岗位未找到！当前用户信息： " + m.getLoginName() + " ， 岗位名称： " + postName);
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found post");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }

                    if (StringUtils.isEmpty(userExt.getOrgCode())){
                        log.error("YSL用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        SyncFailDetail syncFailDetail = new SyncFailDetail();
                        syncFailDetail.setPackageId(packageId);
                        syncFailDetail.setFailReason("YSL用户对应的销售部未找到！当前用户信息： " + m.getLoginName() + " ， 销售部名称： " + userExt.getOrgName());
                        syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                        syncFailDetail.setFailLevel("1");
                        syncFailDetail.setExceptionType("not found dept");
                        failDetails.add(syncFailDetail);
                        failCount++;
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        this.save(user,m);
                        continue;
                    }

                    /**======== 构建diy用户扩展信息表 end===============*/
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        /**  更新 */
                        SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
                        if(sysUser.getIsSync().equals("1")){
                            continue;
                        }
                       if(!userExt.getSalesLevel().equals(sysUser.getSysUserExt().getSalesLevel())){
                           sysUserService.deleteByLoginName(user.getLoginName());
                       }
                       //if(!sysUser.getSysUserExt().getPostCode().equals(userExt.getPostCode())){
                           log.error("解析ysl部门不一致情况原/新", sysUser.getSysUserExt().getPostCode()+"/"+userExt.getPostCode());
                           SysUserRole role=new SysUserRole();
                           role.setUserId(sysUser.getUserId());
                           userRoleMapper.deleteUserRoleInfo(role);
                           user.setUserId(sysUser.getUserId());
                           insertUserRole(user);
                      // }
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        /**  插入 */

                        userExt.setIdentity(UserIdentityUtil.UI_YSL);

                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                } catch (OutOfScopeDIYException | NotFountOrgCodeException | OutOfDIYPostNameException | OutOfLeveLException | NotOrgNameException e) {
                    /**
                     * 警告类异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                } catch (Exception e) {
                    /**
                     * 错误异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析ysl用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        } else {
            syncLog.setSuccessCount(0L);
            syncLog.setFaileCount(0L);
        }
        try {
            syncLog.setPackageId(packageId);
            syncLog.setEndTime(new Date());
            if (failDetails.size() > 0) {
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        } catch (Exception e) {
            log.error("解析ysl用户插入解析日志出错", e);
            e.printStackTrace();
            throw new BusinessException("解析ysl用户插入解析日志出错", e);
        } finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;
    }

    @Override
    public SyncLog analysisSysClueReporting() {
        Long l = new Date().getTime();
        String packageId = l.toString();
        List<MetaEmployee> MetaEmployees = MetaEmployeeDiyMapper.selectMetaEmployeetClueReporting();
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("sysuserClueReporting");
        syncLog.setStartTime(new Date());

        Set<String> loginNameList = sysUserService.selectAllUserLoginName();
        syncLog.setTotalCount((long) MetaEmployees.size());
        List<SyncFailDetail> failDetails = new ArrayList<>();
        long successCount = 0;
        long failCount = 0;
        Long deptIdsfa = Long.parseLong(configService.selectConfigByKey("libang.user.sfa.deptid"));
        Long roleIdsfa = Long.parseLong(configService.selectConfigByKey("libang.user.sfa.roleid"));
        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.ClueReporting.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.ClueReporting.roleid"));
        if (MetaEmployees.size() > 0) {
            for (MetaEmployee m : MetaEmployees) {
                try {
                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setLoginName(m.getLoginName());
                    user.setUserName(m.getName());
                    user.setEmail(m.getEmail());
                    user.setPhonenumber(m.getMobile());
                    String sex = "" + (Integer.parseInt(m.getSex()) - 1);
                    user.setSex(sex);
                    //同步0
                    user.setIsSync("0");
                    if (m.getStatus() == 0) {
                        user.setStatus("1");
                        user.setDelFlag("2");
                    } else {
                        user.setStatus("0");
                    }
                    /** =============用户基本信息构建 end===============*/
                    SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());

                    /**======== 构建用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setBossEmployeeId(m.getBossEmployeeId());
                    userExt.setBossName(m.getBossName());
                    userExt.setSapEmployeeId(m.getSapEmployeeId());
                    userExt.setPostCode(m.getEmployeePost());
                    userExt.setDuty(m.getDuty());
                    userExt.setDutyName(m.getDutyName());
                    String postName = m.getEmployeePostName();
                    userExt.setPostName(postName);

                    Set<String> sfaPostNameSet = getConfigValueSet("sfa_comp_postname");
                    if (m.getBusinessUnit().equals("DIY")) {
                    if (sfaPostNameSet.contains(postName)) {
                        userExt.setSalesLevel("diysfa_level");
                            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiySalesOrgTree();
                            Set<String> companySet =  getConfigValueSet("libang_company_level_postname");
                            if(companySet.contains(postName)){
                                //先处理特殊的第三级 区公司级别
                                userExt.setOrgName(m.getStext4());
                                setExtOrgCodeOn3(salesTreeMap,userExt);

                            }else {
                                //判断用户u岗位是否在销售员敢为、销售分部岗位、销售部岗位、销售大区岗位中
                                    //获取最后所属的部门名称
                                //如果sfa存在该岗位则直接取公司
                                if(sfaPostNameSet.contains(postName)){
                                    String orgName =m.getStext3();
                                    userExt.setOrgName(orgName);
                                    int i = getLevel(userExt,salesTreeMap);
                                } else{
                                    String orgName = getStextSfa(m,"DIY");
                                    if(orgName.indexOf("通路推广组")!=-1){
                                        orgName =  getStextSecond(m);
                                    }
                                    userExt.setOrgName(orgName);
                                    int i = getLevel(userExt,salesTreeMap);
                                }

                            }
                        }
                        /* else if (m.getBusinessUnit().equals("CW")) {
                            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiySalesOrgTreeY9();
                            Set<String> deptPostNameSet = getConfigValueSet("cw_dept_postname");
                            Set<String> officePostNameSet = getConfigValueSet("cw_office_postname");
                            Set<String> empPostNameSet = getConfigValueSet("cw_emp_postname");
                            if (deptPostNameSet.contains(postName)) {
                                userExt.setOrgName(m.getStext4());
                                setExtOrgCodeY9(salesTreeMap, 3, userExt);
                            } else if (officePostNameSet.contains(postName)) {
                                userExt.setOrgName(m.getStext5());
                                setExtOrgCodeY9(salesTreeMap, 4, userExt);
                            } else if (empPostNameSet.contains(postName)) {
                                userExt.setOrgName(m.getStext5());
                                userExt.setOrgCode(m.getSapEmployeeId());
                            }else{
                                String orgName = getStextSfa(m,"CW");
                                userExt.setOrgName(orgName);
                                int i = getLevelSapCw(userExt,salesTreeMap);
                            }
                        } else if (m.getBusinessUnit().equals("YSL")) {
                            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiyYSLSalesOrgTree();
                            userExt.setOrgName(m.getStext5());
                            setExtOrgCodeY9(salesTreeMap, 4, userExt);
                        }*/
                    }else{
                        userExt.setSalesLevel("ClueReporting_level");
                        userExt.setOrgName("品保中心");
                        userExt.setOrgCode("1");
                    }
                    if("品保中心".equals(userExt.getOrgName())){
                        Long[] roleIds = {roleId};
                        user.setDeptId(deptId);
                        user.setRoleIds(roleIds);
                    }else{
                        Long[] roleIdsSfa = {roleIdsfa};
                        user.setDeptId(deptIdsfa);
                        user.setRoleIds(roleIdsSfa);
                    }
                    /**======== 构建用户扩展信息表 end===============*/
                    loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
                    if (loginNameList.contains(user.getLoginName().toUpperCase())) {
                        /**  更新 */
                        if(sysUser.getIsSync().equals("1")){
                            continue;
                        }
                        sysUserService.deleteByLoginName(user.getLoginName());
                        SysUserRole role=new SysUserRole();
                        role.setUserId(sysUser.getUserId());
                        role.setRoleId(user.getRoleIds()[0]);
                        userRoleMapper.deleteUserRoleInfo(role);
                        user.setUserId(sysUser.getUserId());
                        insertUserRole(user);
                        user.setSysUserExt(userExt);
                        user.setUpdateTime(new Date());
                        sysUserService.updateUserInfoAndSalesExt(user);
                    } else {
                        /**  插入 */
                        userExt.setIdentity(UserIdentityUtil.UI_ClueReporting);
                        //修改密码并加密
                        user.setPassword(m.getLoginName());
                        user.setSalt(ShiroSaltUtil.randomSalt());
                        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                        user.setSysUserExt(userExt);
                        sysUserService.insertUserAndSalesExt(user);
                        successCount++;
                    }
                } catch (OutOfScopeDIYException | NotFountOrgCodeException | OutOfDIYPostNameException | OutOfLeveLException | NotOrgNameException e) {
                    /**
                     * 警告类异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("0");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    failCount++;
                } catch (Exception e) {
                    /**
                     * 错误异常
                     */
                    SyncFailDetail syncFailDetail = new SyncFailDetail();
                    syncFailDetail.setPackageId(packageId);
                    syncFailDetail.setFailReason(e.getMessage());
                    syncFailDetail.setDataJson(JSONObject.toJSONString(m));
                    syncFailDetail.setFailLevel("1");
                    syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                    failDetails.add(syncFailDetail);
                    e.printStackTrace();
                    log.error("解析品保中心用户出错", e);
                    failCount++;
                }
            }
            syncLog.setSuccessCount(successCount);
            syncLog.setFaileCount(failCount);
        } else {
            syncLog.setSuccessCount(0L);
            syncLog.setFaileCount(0L);
        }
        try {
            syncLog.setPackageId(packageId);
            syncLog.setEndTime(new Date());
            if (failDetails.size() > 0) {
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        } catch (Exception e) {
            log.error("解析品保中心用户插入解析日志出错", e);
            e.printStackTrace();
            throw new BusinessException("解析品保中心用户插入解析日志出错", e);
        } finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return syncLog;
    }

    /**
     * 获取字典的set
     * @param dictType
     * @return
     */
    public Set<String> getConfigValueSet(String dictType){
        Set<String> res = new HashSet<>();
        List<SysDictData> dictDatas = sysDictDataService.selectSimpleDictDataByType(dictType);
        for(SysDictData d: dictDatas){
            res.add(d.getDictValue());
        }
        return res;
    }

    /**品保中心 diy，cw，ysl 找不到部门的人员线索报备新增**/
    public void save(SysUser user,MetaEmployee m){
        Set<String> sfaPostNameSet = getConfigValueSet("sfa_comp_postname");
        String postName = m.getEmployeePostName();
        Long deptId = Long.parseLong(configService.selectConfigByKey("libang.user.ClueReporting.deptid"));
        Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.ClueReporting.roleid"));
        Long deptIdsfa = Long.parseLong(configService.selectConfigByKey("libang.user.sfa.deptid"));
        Long roleIdsfa = Long.parseLong(configService.selectConfigByKey("libang.user.sfa.roleid"));
        SysUserExt userExt =user.getSysUserExt();
        if(m.getBusinessUnit().equals("DIY")){
        if (sfaPostNameSet.contains(postName)) {
            userExt.setSalesLevel("diysfa_level");
            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiySalesOrgTree();
            Set<String> companySet = getConfigValueSet("libang_company_level_postname");
            if (companySet.contains(postName)) {
                //先处理特殊的第三级 区公司级别
                userExt.setOrgName(m.getStext4());
                setExtOrgCodeOn3(salesTreeMap, userExt);

            } else {
                //判断用户u岗位是否在销售员敢为、销售分部岗位、销售部岗位、销售大区岗位中
                //获取最后所属的部门名称
                //如果sfa存在该岗位则直接取公司
                if(sfaPostNameSet.contains(postName)){
                    String orgName =m.getStext3();
                    userExt.setOrgName(orgName);
                    int i = getLevel(userExt,salesTreeMap);
                }else{
                String orgName = getStextSfa(m, "DIY");
                if (orgName.indexOf("通路推广组") != -1) {
                    orgName = getStextSecond(m);
                }
                userExt.setOrgName(orgName);
                int i = getLevel(userExt, salesTreeMap);
                }

            }
            /*}else if(m.getBusinessUnit().equals("CW")){
                Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiySalesOrgTreeY9();
                Set<String> deptPostNameSet = getConfigValueSet("cw_dept_postname");
                Set<String> officePostNameSet = getConfigValueSet("cw_office_postname");
                Set<String> empPostNameSet = getConfigValueSet("cw_emp_postname");
                if (deptPostNameSet.contains(postName)) {
                    userExt.setOrgName(m.getStext4());
                    setExtOrgCodeY9(salesTreeMap, 3, userExt);
                } else if (officePostNameSet.contains(postName)) {
                    userExt.setOrgName(m.getStext5());
                    setExtOrgCodeY9(salesTreeMap, 4, userExt);
                } else if (empPostNameSet.contains(postName)) {
                    userExt.setOrgName(m.getStext5());
                    userExt.setOrgCode(m.getSapEmployeeId());
                }else{
                    String orgName = getStextSfa(m,"CW");
                    userExt.setOrgName(orgName);
                    int i = getLevelSapCw(userExt,salesTreeMap);
                }
            }*/
        }else{
            userExt.setSalesLevel("ClueReporting_level");
            userExt.setOrgName("品保中心");
            userExt.setOrgCode("1");
        }
        }else if(m.getBusinessUnit().equals("YSL")){
            Map<Integer, Map<String, Map<String, String>>> salesTreeMap = getDiyYSLSalesOrgTree();
            userExt.setOrgName(m.getStext5());
            setExtOrgCodeY9(salesTreeMap, 4, userExt);
        }else{
            userExt.setSalesLevel("ClueReporting_level");
            userExt.setOrgName("品保中心");
            userExt.setOrgCode("1");
        }

        Set<String> loginNameList = sysUserService.selectAllUserLoginName();
        if("品保中心".equals(userExt.getOrgName())){
            Long[] roleIds = {roleId};
            user.setDeptId(deptId);
            user.setRoleIds(roleIds);
        }else{
            Long[] roleIds = {roleId};
            Long[] roleIdsSfa = {roleIdsfa};
            //合并数组的长度等于两个数组的长度
            Long[] roles = new Long[roleIds.length+roleIdsSfa.length];
            //循环赋值
            for(int i =0;i<roles.length;i++){
                if(i<roleIds.length) {
                    roles[i]=roleIds[i];

                }else {
                    roles[i]=roleIdsSfa[i-roleIds.length];
                }
            }
            user.setDeptId(deptIdsfa);
            user.setRoleIds(roles);
        }
        //同步0
        user.setIsSync("0");
        /**======== 构建用户扩展信息表 end===============*/


        loginNameList = loginNameList.stream().map(String::toUpperCase).collect(Collectors.toSet());
        if (loginNameList.contains(user.getLoginName().toUpperCase())) {
            /**  更新 */
            SysUser sysUser=sysUserService.selectUserByLoginName(user.getLoginName());
            if(!("1").equals(sysUser.getIsSync())){
            sysUserService.deleteByLoginName(user.getLoginName());
            SysUserRole role=new SysUserRole();
            role.setUserId(sysUser.getUserId());
            userRoleMapper.deleteUserRoleInfo(role);
            user.setUserId(sysUser.getUserId());
            insertUserRole(user);
            user.setSysUserExt(userExt);
            user.setUpdateTime(new Date());
            sysUserService.updateUserInfoAndSalesExt(user);
            }
        } else {
            //验证删除，防止重复
           // sysUserService.deleteUserByLoginName(user.getLoginName());
            /**  插入 */
            userExt.setIdentity(UserIdentityUtil.UI_ClueReporting);
            //修改密码并加密
            user.setPassword(user.getLoginName());
            user.setSalt(ShiroSaltUtil.randomSalt());
            user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            user.setSysUserExt(userExt);
            sysUserService.insertUserAndSalesExt(user);
        }
    }


    /**
     * 获取销售组织架构树
     * @return
     */
    public Map<Integer,Map<String,Map<String,String>>> getDiySalesOrgTree(){
        Map<String,Map<String,String>> map2= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(2, "DIY");
        Map<String,Map<String,String>> map3= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(3, "DIY");
        Map<String,Map<String,String>> map4= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(4, "DIY");
        Map<String,Map<String,String>> map5= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(5, "DIY");
        Map<String,Map<String,String>> map6= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(6, "DIY");
        Map<Integer,Map<String,Map<String,String>>>res = new HashMap<>();
        res.put(2,map2);
        res.put(3,map3);
        res.put(4,map4);
        res.put(5,map5);
        res.put(6,map6);
        return res;
    }

    /**
     * 获取用户最后的stext
     * @param m
     * @return
     */
    public String getStext(MetaEmployee m){
        if(m.getStext7()!=null&&!m.getStext7().trim().equals("")){
            return m.getStext7();
        }else if(m.getStext6()!=null&&!m.getStext6().trim().equals("")){
            return m.getStext6();
        }else if(m.getStext5()!=null&&!m.getStext5().trim().equals("")){
            return m.getStext5();
        }else if(m.getStext4()!=null&&!m.getStext4().trim().equals("")){
            return m.getStext4();
        }else if(m.getStext3()!=null&&!m.getStext3().trim().equals("")){
            return m.getStext3();
        }else if(m.getStext2()!=null&&!m.getStext2().trim().equals("")){
            return m.getStext2();
        }else if(m.getStext1()!=null&&!m.getStext1().trim().equals("")){
            return m.getStext1();
        }
        throw  new NotOrgNameException(m);
    }

    public String getStextSfa(MetaEmployee m,String type){
        if("DIY".equals(type)){
         if(m.getStext5()!=null&&!m.getStext5().trim().equals("")){
            return m.getStext5();
        }
        } if(m.getStext4()!=null&&!m.getStext4().trim().equals("")){
            return m.getStext4();
        }else if(m.getStext3()!=null&&!m.getStext3().trim().equals("")){
            return m.getStext3();
        }else if(m.getStext2()!=null&&!m.getStext2().trim().equals("")){
            return m.getStext2();
        }else if(m.getStext1()!=null&&!m.getStext1().trim().equals("")){
            return m.getStext1();
        }
        throw  new NotOrgNameException(m);
    }
    /**
     * 获取用户最后的stext
     * @param m
     * @return
     */
    public String getStextSecond(MetaEmployee m){
        if(m.getStext7()!=null&&!m.getStext7().trim().equals("")){
            if(m.getStext6()!=null&&!m.getStext6().trim().equals("")) {
                return m.getStext6();
            }
        }else if(m.getStext6()!=null&&!m.getStext6().trim().equals("")){
            if(m.getStext5()!=null&&!m.getStext5().trim().equals("")){
                return m.getStext5();
            }
        }else if(m.getStext5()!=null&&!m.getStext5().trim().equals("")){
            if(m.getStext4()!=null&&!m.getStext4().trim().equals("")){
                return m.getStext4();
            }
        }else if(m.getStext4()!=null&&!m.getStext4().trim().equals("")){
            if(m.getStext3()!=null&&!m.getStext3().trim().equals("")){
                return m.getStext3();
            }
        }else if(m.getStext3()!=null&&!m.getStext3().trim().equals("")){
            if(m.getStext2()!=null&&!m.getStext2().trim().equals("")){
                return m.getStext2();
            }
        }else if(m.getStext2()!=null&&!m.getStext2().trim().equals("")){
            if(m.getStext1()!=null&&!m.getStext1().trim().equals("")){
                return m.getStext1();
            }
        }
        throw  new NotOrgNameException(m);
    }

    /**
     * 根据销售的部门等级及销售组织名称获取销售的组织code 向下兼容
     * @param salesTree
     * @param level 销售登记
     * @param userExt 用户扩展信息
     * @return
     */
    public boolean setExtOrgCode(Map<Integer,Map<String,Map<String,String>>> salesTree,int level,SysUserExt userExt){
        if(userExt.getOrgName()==null||userExt.getOrgName().trim().equals("")){
            return false;
        }
        String orgname = userExt.getOrgName();
        for(;level<7;level++){
            if(salesTree.containsKey(level)){
                Map<String,Map<String,String>> temp = salesTree.get(level);
                if(temp.containsKey(orgname)){
                    userExt.setOrgCode(temp.get(orgname).get("orgcode"));
                    return true;
                }else{
                    continue;
                }
            }
        }
        return false;
    }

    /**
     * 根据销售的部门等级及销售组织名称获取销售的组织code 向下兼容
     * @param salesTree
     * @param level 销售登记
     * @param userExt 用户扩展信息
     * @return
     */
    public boolean setExtOrgCodeY9(Map<Integer, Map<String, Map<String, String>>> salesTree, int level, SysUserExt userExt) {
        if (userExt.getOrgName() == null || userExt.getOrgName().trim().equals("")) {
            return false;
        }
        String orgname = userExt.getOrgName();
        if (salesTree.containsKey(level)) {
            Map<String, Map<String, String>> temp = salesTree.get(level);
            for (String key : temp.keySet()) {
                if (level==3 && orgname.indexOf(key) != -1) {
                    userExt.setOrgCode(temp.get(key).get("orgcode"));
                    return true;
                }else if (level==4 && key.indexOf(orgname) != -1) {
                    userExt.setOrgCode(temp.get(key).get("orgcode"));
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据销售的部门等级及销售组织名称获取销售的组织code 向上兼容
     * @param salesTree
     * @param level 销售登记
     * @param userExt 用户扩展信息
     * @return
     */
    public boolean setExtOrgCodeUp(Map<Integer,Map<String,Map<String,String>>> salesTree,int level,SysUserExt userExt){
        if(userExt.getOrgName()==null||userExt.getOrgName().trim().equals("")){
            return false;
        }
        String orgname = userExt.getOrgName();
        for(;level>3;level--){
            if(salesTree.containsKey(level)){
                Map<String,Map<String,String>> temp = salesTree.get(level);
                if(temp.containsKey(orgname)){
                    userExt.setOrgCode(temp.get(orgname).get("orgcode"));
                    return true;
                }else{
                    continue;
                }
            }
        }
        return false;
    }
    /**
     * 根据用户所处部门是否包含第三等级区公司名称 来获取code特殊情况针对 第三级特殊情况
     * @param salesTree
     * @param userExt 用户扩展信息
     * @return
             */
    public boolean setExtOrgCodeOn3(Map<Integer,Map<String,Map<String,String>>> salesTree,SysUserExt userExt){
        if(userExt.getOrgName()==null||userExt.getOrgName().trim().equals("")){
            return false;
        }
        String orgname = userExt.getOrgName();
        Map<String,Map<String,String>> temp = salesTree.get(3);
        //遍历区公司名称
        for (String key : temp.keySet()) {
            if(orgname.indexOf(key)!=-1){
                userExt.setOrgCode(temp.get(key).get("orgcode"));
                userExt.setOrgName(key);
                return true;
            }
        }
        return false;

    }
    //事业部人员组织架构
    public boolean setExtOrgCodeOn2(Map<Integer,Map<String,Map<String,String>>> salesTree,SysUserExt userExt){
        if(userExt.getOrgName()==null||userExt.getOrgName().trim().equals("")){
            return false;
        }
        String orgname = userExt.getOrgName();
        Map<String,Map<String,String>> temp = salesTree.get(2);
        //遍历区公司名称
        for (String key : temp.keySet()) {
            if(orgname.indexOf(key)!=-1){
                userExt.setOrgCode(temp.get(key).get("orgcode"));
                userExt.setOrgName(key);
                return true;
            }
        }
        return false;

    }

    public int getLevel(SysUserExt userExt,Map<Integer,Map<String,Map<String,String>>> salesTree){
        String orgName = userExt.getOrgName();
        String orgNameTmp = userExt.getOrgName();
     /*   if (orgNameTmp != null && orgNameTmp.startsWith("36城-")) {
            orgNameTmp = orgNameTmp.replaceAll("36城-", "");
        }*/
        for(int i =6;i>2;i--){
            if(salesTree.containsKey(i)){
                Map<String,Map<String,String>> temp = salesTree.get(i);
                if(temp.containsKey(orgName) || temp.containsKey(orgNameTmp)){
                    userExt.setOrgCode(temp.get(orgName).get("orgcode"));
                    return i;
                }
            }
        }
        return -1;

    }

    public int getLevelSapCw(SysUserExt userExt,Map<Integer,Map<String,Map<String,String>>> salesTree){
        String orgName = userExt.getOrgName();
        String s ="销售大区";
        String s1 = orgName.replace(s,"");
     /*   if (orgNameTmp != null && orgNameTmp.startsWith("36城-")) {
            orgNameTmp = orgNameTmp.replaceAll("36城-", "");
        }*/
        for(int i =6;i>2;i--){
            if(salesTree.containsKey(i)){
                Map<String,Map<String,String>> temp = salesTree.get(i);
                if(temp.containsKey(s1)){
                    userExt.setOrgCode(temp.get(s1).get("orgcode"));
                    return i;
                }
            }
        }
        return -1;

    }
    /**
     * 获取销售组织架构树
     * @return
     */
    public Map<Integer,Map<String,Map<String,String>>> getDiySalesOrgTreeY9(){
        Map<String,Map<String,String>> map3= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(3, "CW");

        Map<String,Map<String,String>> map4= metaDiySalesorgtreeMapper.selectSalesTreeByLevel(4, "CW");
        Map<Integer,Map<String,Map<String,String>>>res = new HashMap<>();
        res.put(3,map3);
        res.put(4,map4);
        return res;
    }

    /**
     * 获取销售组织架构树
     * @return
     */
    public Map<Integer,Map<String,Map<String,String>>> getDiyYSLSalesOrgTree(){
        Map<String,Map<String,String>> map3= metaDiySalesorgtreeMapper.selectSalesTreeByOrgCode(3, "4000");

        Map<String,Map<String,String>> map4= metaDiySalesorgtreeMapper.selectSalesTreeByOrgCode(4, "4000");
        Map<Integer,Map<String,Map<String,String>>>res = new HashMap<>();
        res.put(3,map3);
        res.put(4,map4);
        return res;
    }

    /**
     * 根据销售的部门等级及销售组织名称获取销售的组织code
     * @param salesTree
     * @param level 销售登记
     * @param userExt 用户扩展信息
     * @return
     */
    public boolean setExtOrgCodeEbrY9(Map<Integer,Map<String,Map<String,String>>> salesTree,int level,SysUserExt userExt){
        if(userExt.getOrgName()==null||userExt.getOrgName().trim().equals("")){
            return false;
        }
        String orgname = userExt.getOrgName();
        for(;level<5;level++){
            if(salesTree.containsKey(level)){
                Map<String,Map<String,String>> temp = salesTree.get(level);
                String code = getLikeKey(temp,orgname);
                if(code!=null){
                    userExt.setOrgCode(code);
                    return true;
                }else{
                    continue;
                }
            }
        }
        return false;

    }

    public String getLikeKey( Map<String,Map<String,String>> map,String key){
        if(map.containsKey(key)){
            return map.get(key).get("orgcode");
        }else{
            Iterator it = map.entrySet().iterator();
            while(it.hasNext()) {
                Map.Entry<String, Map<String,String>> entry = (Map.Entry<String, Map<String,String>>)it.next();
                if (entry.getKey().indexOf(key) != -1) {
                    Map<String,String> t =entry.getValue();
                    String value = t.get("orgcode");
                    map.put(key,t);
                    return value;
                }else if(key.indexOf(entry.getKey())!=-1){
                    Map<String,String> t =entry.getValue();
                    String value = t.get("orgcode");
                    map.put(key,t);
                    return value;
                }
            }
            return null;
        }
    }
    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                SysRole sysRole =  roleMapper.selectRoleById(ur.getRoleId());
                if (sysRole != null){
                    if (Arrays.asList(paintRoleKeys).contains(sysRole.getRoleKey())){
                        ur.setShopType("0");
                    }
                    if (Arrays.asList(goldPoleKeys).contains(sysRole.getRoleKey())){
                        ur.setShopType("1");
                    }
                }
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }
}
