package com.dgtly.sync.service;

import com.alibaba.fastjson.JSONArray;
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.http.HttpUtils;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.sync.domain.Customers;
import com.dgtly.sync.domain.SyncFailDetail;
import com.dgtly.sync.domain.SyncLog;
import com.dgtly.sync.domain.UserAssVO;
import com.dgtly.sync.mapper.CustomersMapper;
import com.dgtly.sync.mapper.SyncFailDetailMapper;
import com.dgtly.sync.utils.CustomerAccessTokenUtil;
import com.dgtly.sync.utils.CustomerAccessTokenUtil.UrlType;
import com.dgtly.system.domain.AssRelcustomerinfo;
import com.dgtly.system.domain.SysDictData;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.domain.SysUserExt;
import com.dgtly.system.mapper.SysUserExtMapper;
import com.dgtly.system.mapper.SysUserMapper;
import com.dgtly.system.mapper.SysUserShopExtMapper;
import com.dgtly.system.service.IAssRelcustomerinfoService;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.system.service.ISysDictDataService;
import com.dgtly.system.service.impl.SysUserServiceImpl;
import com.dgtly.wxportal.mapper.WxQyUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

@Component
public class AnalysisDiyCustomerComponent {

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


    @Autowired
    private CustomerAccessTokenUtil customerAccessTokenUtil;

    @Autowired
    private CustomersMapper customersMapper;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysUserExtMapper sysUserExtMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WxQyUserMapper wxQyUserMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISyncLogService syncLogService;
    @Autowired
    private SyncFailDetailMapper syncFailDetailMapper;
    @Autowired
    private IAssRelcustomerinfoService assRelcustomerinfoService;

    @Autowired
    private AnalysisDiyCustomerComponent analysisDiyCustomerComponent;

    @Autowired
    private SysUserShopExtMapper userShopExtMapper;
    private Long deptId;
    //老板角色
    private Long[] roleIds;
    //财务
    private Long[] FinanceRoleIds;
    //仓管
    private Long[] HouseRoleIds;
    private Long[] roleGuideIds;
    private Long[] roleCwIds;
    private Long[] roleCwDiyIds;
    private Long[] roleFXDiyIds;  //3.4接口，同步分销用户
    private Long[] roleStoreIds; //3.6门店经销商
    private Long[] roleBusiness;//7.5厨卫业务人员角色
    private Long[] roleXls;//13.1新零售经销商角色
    private Long[] roleMsq;//经销商魔术漆
    private Long[] roleWqBm;//经销商外墙业务经理
    private Long[] roleSfa;//5.1家装顾问挂sfa角色


    public void analyDiyCustomer2() {
        List<SysDictData> sysDictData = sysDictDataService.selectSimpleDictDataByType("sys_system_ass_cusyomer");
        String deptCodes = sysDictData.get(0).getDictValue();
        String [] deptCode = deptCodes.split(",");
        for (String dCode : deptCode){
            log.info("本次需要同步的经销商:{}",dCode);
            getManagerList(dCode,"");
        }
    }


    public SyncLog analyDiyCustomer1() {
        log.info("开始同步经销商用户B");
        if (roleMsq == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.msq.roleid"));
            roleMsq = new Long[]{roleId};
        }
        if (roleWqBm == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.wqbm.roleid"));
            roleWqBm = new Long[]{roleId};
        }
        Map<String, Customers> chainsMap = customersMapper.selectCustomerMapByChainsCode();

        List<SyncFailDetail> failDetails = new ArrayList<>();
        SyncLog syncLog = new SyncLog();
        syncLog.setStartTime(new Date());
        String packageId = "diycustomer" + syncLog.getStartTime().getTime();
        syncLog.setPackageId(packageId);
        long total = 0;
        long success = 0;
        Set<String> loginNameSet = sysUserService.selectAllUserLoginName();
        Set<String> diyNameSet = sysUserService.selectDiyUserLoginName();


        String MsqUserJson = "";
        try {
            MsqUserJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.MSQ, 1 + ""));
        } catch (Exception e) {
            log.error("获取经销商魔术漆施工人员接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }
        JSONObject msqjson = JSONObject.parseObject(MsqUserJson);
        Integer msqcount = msqjson.getInteger("count");
        JSONArray MSQ = new JSONArray();
        if (msqcount > 100) {
            int co = 0;
            if (msqcount % 100 != 0) {
                co = (msqcount / 100) + 2;
            } else {
                co = (msqcount / 100) + 1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    msqjson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.MSQ, i + "")));
                } catch (Exception e) {
                    log.error("循环获取经销魔术漆施工人员列表接口错误！第" + i + "页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                int code = msqjson.getInteger("code");
                if (code == 0) {
                    MSQ.addAll(msqjson.getJSONArray("data"));
                }
            }
            success += buildSysUser(false,MSQ, loginNameSet, diyNameSet, 4, failDetails, packageId, chainsMap);
            total += MSQ.size();
        } else {
            int code = msqjson.getInteger("code");
            if (code == 0) {
                MSQ.addAll(msqjson.getJSONArray("data"));
                success += buildSysUser(false,MSQ, loginNameSet, diyNameSet, 4, failDetails, packageId, chainsMap);
                total += MSQ.size();
            }
        }



        String WqBmUserJson = "";
        try {
            WqBmUserJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.WQBM, 1 + ""));
        } catch (Exception e) {
            log.error("获取经销外墙服务商人员接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }
        JSONObject wqbmjson = JSONObject.parseObject(WqBmUserJson);
        Integer wqbmcount = wqbmjson.getInteger("count");
        JSONArray WQBM = new JSONArray();
        if (wqbmcount > 100) {
            int co = 0;
            if (wqbmcount % 100 != 0) {
                co = (wqbmcount / 100) + 2;
            } else {
                co = (wqbmcount / 100) + 1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    wqbmjson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.WQBM, i + "")));
                } catch (Exception e) {
                    log.error("循环获取经销外墙服务商人员列表接口错误！第" + i + "页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                int code = wqbmjson.getInteger("code");
                if (code == 0) {
                    WQBM.addAll(wqbmjson.getJSONArray("data"));
                }
            }
            success += buildSysUser(false,WQBM, loginNameSet, diyNameSet, 5, failDetails, packageId, chainsMap);
            total += WQBM.size();

        } else {
            int code = msqjson.getInteger("code");
            if (code == 0) {
                WQBM.addAll(msqjson.getJSONArray("data"));
                success += buildSysUser(false,WQBM, loginNameSet, diyNameSet, 5, failDetails, packageId, chainsMap);
                total += WQBM.size();
            }
        }





        try{
            syncLog.setTotalCount(total);
            syncLog.setSuccessCount(success);
            syncLog.setFaileCount((long)failDetails.size());
            syncLog.setEndTime(new Date());
            syncLog.setSyncType("diycustomer");

            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }
        return null;
    }
    /**
     * 获取并解析DIY经销商用户
     * 因为经销商用户并不涉及用信息更新等方面 所以只插入不更新
     * @return
     */
    //@Override
    public SyncLog analyDiyCustomer() {
        log.info("开始解析DIY经销商用户A");
        if(deptId==null){
            deptId = Long.parseLong(configService.selectConfigByKey("libang.customer.deptid"));
        }
        //老板角色
        if(roleIds==null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customer.roleid"));
            roleIds = new Long[]{roleId};
        }
        //财务
        if(FinanceRoleIds==null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customerFinance.roleid"));
            FinanceRoleIds = new Long[]{roleId};
        }
        //仓管
        if(HouseRoleIds==null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customerHouse.roleid"));
            HouseRoleIds = new Long[]{roleId};
        }
        if(roleXls ==null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customerXls.roleid"));
            roleXls = new Long[]{roleId};
        }

        if(roleSfa == null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.user.sfa.roleid"));
            roleSfa = new Long[]{roleId};
        }

        if (roleGuideIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.guide.roleid"));
            roleGuideIds = new Long[]{roleId};
        }
        if (roleCwIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.cw.roleid"));
            roleCwIds = new Long[]{roleId};
        }
        if (roleCwDiyIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.cw.roleid"));
            Long roleDiyId = Long.parseLong(configService.selectConfigByKey("libang.guide.roleid"));
            roleCwDiyIds = new Long[]{roleId, roleDiyId};
        }
        if (roleFXDiyIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.fx.roleid"));
            roleFXDiyIds = new Long[]{roleId};
        }
        if (roleStoreIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.storeCustomer.roleid"));
            roleStoreIds = new Long[]{roleId};
        }
        if (roleMsq == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.msq.roleid"));
            roleMsq = new Long[]{roleId};
        }
        if (roleWqBm == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.wqbm.roleid"));
            roleWqBm = new Long[]{roleId};
        }

        Map<String,Customers> chainsMap = customersMapper.selectCustomerMapByChainsCode();

        List<SyncFailDetail> failDetails = new ArrayList<>();
        SyncLog syncLog = new SyncLog();
        syncLog.setStartTime(new Date());
        String packageId = "diycustomer"+syncLog.getStartTime().getTime();
        syncLog.setPackageId(packageId);
        long total = 0;
        long success = 0;
        Set<String> loginNameSet = sysUserService.selectAllUserLoginName();
        Set<String> diyNameSet = sysUserService.selectDiyUserLoginName();


        // 3.4、获取经销商分销业务员人员列表(分页)开始： ===================>
        log.info("3.4、获取经销商分销业务员人员列表(分页)开始： ===================>");
        String fxResellerJson ="";
        try{
            fxResellerJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.RESELLER,1+""));
        }catch (Exception e){
            log.error("获取经销商分销业务员人员列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject fxJson = JSONObject.parseObject(fxResellerJson);
        Integer fxCount = fxJson.getInteger("count");
        JSONArray jsonArray = new JSONArray();
        if(fxCount>100){
            int co = 0;
            if (fxCount%100 != 0){
                co = (fxCount/100) +2;
            }else{
                co = (fxCount/100) +1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    fxJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.RESELLER,i+"")));
                } catch (Exception e) {
                    log.error("循环获取经销商财务接口错误！第"+i+"页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                int code = fxJson.getInteger("code");
                if(code==0){
                    jsonArray.addAll( fxJson.getJSONArray("userlist"));
                }
            }
            success+=buildSysUserFx(jsonArray,loginNameSet,6,failDetails,packageId,chainsMap);
            total+=jsonArray.size();

        }else{
            int code = fxJson.getInteger("code");
            if(code==0){
                jsonArray.addAll( fxJson.getJSONArray("userlist"));
                success+=buildSysUserFx(jsonArray,loginNameSet,6,failDetails,packageId,chainsMap);
                total+=jsonArray.size();
            }
        }
        log.info("3.4、获取经销商分销业务员人员列表(分页)结束： <========================");
        //3.4、获取经销商分销业务员人员列表(分页)结束： <========================

        //3.6经销商经销人员列表
        String staffListJson ="";
        JSONArray STAFF = new JSONArray();
        try {
            staffListJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.STAFF, 1+""));
        } catch (Exception e) {
            log.error("3.6经销商经销人员列表！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject json = JSONObject.parseObject(staffListJson);
        Integer Staffcount = json.getInteger("count");
        if(Staffcount>100){
            int co = 0;
            if (Staffcount%100 != 0){
                co = (Staffcount/100) +2;
            }else{
                co = (Staffcount/100) +1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    json = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.STAFF,i+"")));
                } catch (Exception e) {
                    log.error("循环获取3.6接口错误！第"+i+"页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                int code = json.getInteger("code");
                if(code==0){
                    STAFF.addAll(json.getJSONArray("data"));
                }
            }
            success += buildSysUserStaff(STAFF, loginNameSet, diyNameSet, failDetails, packageId, chainsMap,8);
            total += STAFF.size();
        }else{
            int code = json.getInteger("code");
            if(code==0){
                STAFF.addAll(json.getJSONArray("data"));
                success += buildSysUserStaff(STAFF, loginNameSet, diyNameSet, failDetails, packageId, chainsMap,8);
                total += STAFF.size();
            }
        }

        //3.7经销商倍增人员人员(门店经销商)
        String beizengJson ="";
        JSONArray bz = new JSONArray();
        try {
            beizengJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BZ, 1+""));
        } catch (Exception e) {
            log.error("3.7经销商倍增人员列表！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject bzJson = JSONObject.parseObject(beizengJson);
        Integer bzCount = bzJson.getInteger("count");
        if(bzCount>100){
            int co = 0;
            if (bzCount%100 != 0){
                co = (bzCount/100) +2;
            }else{
                co = (bzCount/100) +1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    bzJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BZ,i+"")));
                } catch (Exception e) {
                    log.error("循环获取3.7经销商倍增人员错误！第"+i+"页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                int code = bzJson.getInteger("code");
                if(code==0){
                    bz.addAll(bzJson.getJSONArray("data"));
                }
            }
            success += buildSysUserBz(bz, loginNameSet, diyNameSet, failDetails, packageId, chainsMap,5);
            total += bz.size();
        }else{
            int code = bzJson.getInteger("code");
            if(code==0){
                bz.addAll(bzJson.getJSONArray("data"));
                success += buildSysUserBz(bz, loginNameSet, diyNameSet, failDetails, packageId, chainsMap,5);
                total += bz.size();
            }
        }





        //导购经销商
        String guideJson ="";
        try{
            guideJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.STOREGUIDE,null));
        }catch (Exception e){
            log.error("获取经销商导购接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }
        Map<String,Customers> codeMap = customersMapper.selectCustomerMapByCode();
        JSONObject gjson = JSONObject.parseObject(guideJson);
        int code = gjson.getInteger("code");
        if(code==0){
            JSONArray STOREGUIDE = new JSONArray();
            STOREGUIDE.addAll(gjson.getJSONArray("userlist"));
            success+=buildSysUser(false,STOREGUIDE,loginNameSet,diyNameSet,0,failDetails,packageId,codeMap);
            total+=gjson.getJSONArray("userlist").size();
        }

        //经销商负责人
        String managerJson ="";
        try{
            managerJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.MANAGER,null));
        }catch (Exception e){
            log.error("获取经销商经理接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject mjson = JSONObject.parseObject(managerJson);


        code = mjson.getInteger("code");
        if(code==0){
            JSONArray MANAGER = new JSONArray();
            MANAGER.addAll(mjson.getJSONArray("userlist"));
            success+=buildSysUser(false,MANAGER,loginNameSet,diyNameSet,1,failDetails,packageId,chainsMap);
            total+=mjson.getJSONArray("userlist").size();
        }
//财务3.2
        String financeJson ="";
        try{
            financeJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.FINANCE,1+""));
        }catch (Exception e){
            log.error("获取经销商财务接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject fjson = JSONObject.parseObject(financeJson);
        Integer fcount = fjson.getInteger("count");
        JSONArray FINANCE = new JSONArray();
        if(fcount>100){
            int co = 0;
            if (fcount%100 != 0){
                co = (fcount/100) +2;
            }else{
                co = (fcount/100) +1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    fjson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.FINANCE,i+"")));
                } catch (Exception e) {
                    log.error("循环获取经销商财务接口错误！第"+i+"页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                code = fjson.getInteger("code");
                if(code==0){
                    FINANCE.addAll(fjson.getJSONArray("userlist"));
                }
            }
            success+=buildSysUser(false,FINANCE,loginNameSet,diyNameSet,2,failDetails,packageId,chainsMap);
            total+=FINANCE.size();
        }else{
            code = fjson.getInteger("code");
            if(code==0){
                FINANCE.addAll(fjson.getJSONArray("userlist"));
                success+=buildSysUser(false,FINANCE,loginNameSet,diyNameSet,2,failDetails,packageId,chainsMap);
                total+=FINANCE.size();
            }
        }

//3.3经销商仓管人员
        String warehouseJson ="";
        try{
            warehouseJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.WAREHOUSE,1+""));
        }catch (Exception e){
            log.error("获取经销商仓管接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject wjson = JSONObject.parseObject(warehouseJson);
        Integer wcount = wjson.getInteger("count");
        JSONArray WAREHOUSE = new JSONArray();
        if(wcount>100){
            int co = 0;
            if (wcount%100 != 0){
                co = (wcount/100) +2;
            }else{
                co = (wcount/100) +1;
            }
            for (int i = 1; i < co; i++) {
                try {
                    wjson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.WAREHOUSE,i+"")));
                } catch (Exception e) {
                    log.error("获取经销商仓管接口错误！第"+i+"页");
                    customerAccessTokenUtil.reSetToken();
                    throw e;
                }
                code = wjson.getInteger("code");
                if(code==0){
                    WAREHOUSE.addAll(wjson.getJSONArray("userlist"));
                }
            }
            success+=buildSysUser(false,WAREHOUSE,loginNameSet,diyNameSet,3,failDetails,packageId,chainsMap);
            total+=WAREHOUSE.size();
        }else{
            code = wjson.getInteger("code");
            if(code==0){
                WAREHOUSE.addAll(wjson.getJSONArray("userlist"));
                success+=buildSysUser(false,WAREHOUSE,loginNameSet,diyNameSet,3,failDetails,packageId,chainsMap);
                total+=WAREHOUSE.size();
            }
        }


        //13.1 新零售经销商人员列表
        String xlsCustomerJson ="";
        try{
            xlsCustomerJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.XLS,null));
        }catch (Exception e){
            log.error("获取新零售经销商人员接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject xlsJson = JSONObject.parseObject(xlsCustomerJson);
        code = xlsJson.getInteger("code");
        if(code==0){
            JSONArray xlsMANAGER = new JSONArray();
            xlsMANAGER.addAll(xlsJson.getJSONArray("data"));
            success+=buildSysUser(false,xlsMANAGER,loginNameSet,diyNameSet,7,failDetails,packageId,chainsMap);
            total+=xlsMANAGER.size();
        }

        //5.1获家装顾问师人员列表
        String homeCustomerJson ="";
        try{
            homeCustomerJson = HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.HOMEDECORATION,null));
        }catch (Exception e){
            log.error("获取家装顾问师经销商人员接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        JSONObject homeJson = JSONObject.parseObject(homeCustomerJson);
        code = homeJson.getInteger("code");
        if(code==0){
            JSONArray homeCustomer = new JSONArray();
            homeCustomer.addAll(homeJson.getJSONArray("userlist"));
            success+=buildSysUser(false,homeCustomer,loginNameSet,diyNameSet,9,failDetails,packageId,chainsMap);
            total+=homeCustomer.size();
        }

        /*try {
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BOSSLIST, null)));
            code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, 4, failDetails, packageId, chainsMap);
                total += bossListJson.getJSONArray("userlist").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫老板列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }*/

        /*try {
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.MANAGERLIST, null)));
            code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, 5, failDetails, packageId, chainsMap);
                total += bossListJson.getJSONArray("userlist").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫经理列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }*/

        /*try {
            //获取厨卫业务员人员
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BUSINESSLIST, null)));
            code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, 6, failDetails, packageId, chainsMap);
                total += bossListJson.getJSONArray("userlist").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫业务人员列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }*/

        try{
            syncLog.setTotalCount(total);
            syncLog.setSuccessCount(success);
            syncLog.setFaileCount((long)failDetails.size());
            syncLog.setEndTime(new Date());
            syncLog.setSyncType("diycustomer");

            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }


        return null;
    }

    /**
     * 获取经销商负责人
     * @param depCode
     * @param userNo
     * @return
     */
    public  String  getManagerList(String depCode , String userNo){
    try {
        log.info("接收到参数depCode:{},userNO:{}",depCode,userNo);
            String url = customerAccessTokenUtil.getUrl(UrlType.MANAGERLIST, null);
            Map<String,Customers> chainsMap = customersMapper.selectCustomerMapByChainsCodeByCode();
            List<SyncFailDetail> failDetails = new ArrayList<>();
            //获取经销商负责人
            //拼接请求参数
            if (StringUtils.isNotEmpty(depCode)){
                url = url+"&depCode="+depCode;
            }
            if (StringUtils.isNotEmpty(userNo)){
                url = url+"&userNo="+userNo;
            }
            log.info("获取经销商负责人请求地址{}",url);
            JSONObject managerListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(url));
            log.info("获取经销商负责人请求结果为:{}",managerListJson);
            int code = managerListJson.getInteger("code");
            if (code == 0) {
                JSONArray dataArray = managerListJson.getJSONArray("data");
                if(dataArray.size() >0){
                    StringBuffer users = new StringBuffer();
                    for (int i = 0; i < dataArray.size(); i++){
                        JSONObject object = dataArray.getJSONObject(i);
                        String name = object.getString("name");
                        users.append(name).append(",");
                    }
                    String packageId = "diycustomer"+new Date().getTime();
                    buildSysUser(true ,dataArray, null, null, 1, failDetails, packageId, chainsMap);
                    return users.substring(0,users.length()-1)+"同步成功";
                }else {
                    return "同步成功,数据为空";
                }
            }else {
                return "获取数据失败";
            }
        } catch (Exception e) {
            customerAccessTokenUtil.reSetToken();
            log.error("获取经销商负责人接口错误！",e);
            return "获取数据失败";
        }
    }


    /*
     * @description: 厨卫人员拉取
     * @author: qxm
     * @date: 2022/4/25 10:03
     */
  /*  public SyncLog analyCwCustomer() {
        if(deptId==null){
            deptId = Long.parseLong(configService.selectConfigByKey("libang.customer.deptid"));
        }
        if(roleIds==null){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customer.roleid"));
            roleIds = new Long[]{roleId};
        }

        if (roleGuideIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.guide.roleid"));
            roleGuideIds = new Long[]{roleId};
        }
        if (roleCwIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.cw.roleid"));
            roleCwIds = new Long[]{roleId};
        }
        if (roleCwDiyIds == null) {
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.cw.roleid"));
            Long roleDiyId = Long.parseLong(configService.selectConfigByKey("libang.guide.roleid"));
            roleCwDiyIds = new Long[]{roleId, roleDiyId};
        }
        if(roleBusiness ==null ){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.cw.business"));
            roleBusiness = new Long[]{roleId};
        }


        List<SyncFailDetail> failDetails = new ArrayList<>();
        SyncLog syncLog = new SyncLog();
        syncLog.setStartTime(new Date());
        String packageId = "diycustomer"+syncLog.getStartTime().getTime();
        syncLog.setPackageId(packageId);
        long total = 0;
        long success = 0;
        Set<String> loginNameSet = sysUserService.selectAllUserLoginName();
        Set<String> diyNameSet = sysUserService.selectDiyUserLoginName();

        Map<String,Customers> codeMap = customersMapper.selectCustomerMapByCode();

        Map<String,Customers> chainsMap = customersMapper.selectCustomerMapByChainsCode();

        try {
            // JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BOSSLIST, null)));
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.AllRole, null)));
            int code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, failDetails, packageId, chainsMap);
                //total += bossListJson.getJSONArray("userlist").size();
                total += bossListJson.getJSONArray("data").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

    *//*    try {
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.MANAGERLIST, null)));
            int code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, 5, failDetails, packageId, chainsMap);
                total += bossListJson.getJSONArray("userlist").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫经理列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }

        try {
            //获取厨卫业务员人员
            JSONObject bossListJson = JSONObject.parseObject(HttpUtils.sendSSLGet(customerAccessTokenUtil.getUrl(UrlType.BUSINESSLIST, null)));
            int code = bossListJson.getInteger("code");
            if (code == 0) {
                success += buildSysUserEbr(bossListJson, loginNameSet, diyNameSet, 6, failDetails, packageId, chainsMap);
                total += bossListJson.getJSONArray("userlist").size();
            }
        } catch (Exception e) {
            log.error("获取厨卫业务人员列表接口错误！");
            customerAccessTokenUtil.reSetToken();
            throw e;
        }*//*

        try{
            syncLog.setTotalCount(total);
            syncLog.setSuccessCount(success);
            syncLog.setFaileCount((long)failDetails.size());
            syncLog.setEndTime(new Date());
            syncLog.setSyncType("diycustomer");

            if(failDetails.size()>0){
                syncFailDetailMapper.batchInsertSyncFailDetail(failDetails);
            }
        }catch (Exception e){
            log.error("解析用户插入解析日志出错",e);
            e.printStackTrace();
            throw new BusinessException("解析用户插入解析日志出错",e);
        }finally {
            syncLogService.insertSyncLog(syncLog);
        }


        return null;
    }*/

    /**
     * 构建 插入用户List
     * @param
     * @param loginNameSet 排重用
     * @param isManager
     * @return
     */
    public Integer buildSysUser(boolean oneUser,JSONArray jsonArray, Set<String> loginNameSet,Set<String> diyNameSet, int isManager, List<SyncFailDetail> failDetails,String packageId, Map<String,Customers> cusMap) {
        // JSONArray jsonArray = json.getJSONArray("userlist");
        log.info("开始解析用户列表{}",jsonArray);
        if (oneUser){
            Long roleId = Long.parseLong(configService.selectConfigByKey("libang.customer.roleid"));
            roleIds = new Long[]{roleId};
        }
        int count = 0;
        List<String> interfaceList = new ArrayList<>();
        List<UserAssVO> assVOList =new ArrayList<>();
        for (int x = 0; x < jsonArray.size(); x++) {
            JSONObject jsonObject = jsonArray.getJSONObject(x);
            String loginName = jsonObject.getString("userid");
            Boolean isDelete = jsonObject.getBoolean("isDelete");
            if(isDelete){
                String customerCode = jsonObject.getString("depCode");
                String name = jsonObject.getString("name");
                String phone = jsonObject.getString("mobile");
                UserAssVO assVO =new UserAssVO();
                assVO.setUserName(name);
                assVO.setCustomerCode(customerCode);
                assVO.setPhone(phone);
                assVOList.add(assVO);
                continue;
            }
            if (loginName != null && !"".equals(loginName)) {
                interfaceList.add(loginName);
            }
        }
        List<String> loginNames = sysUserService.selectUserByIsManager(isManager);
        List<String> collect =new ArrayList<>();
        loginNames.removeAll(interfaceList);
        collect.addAll(loginNames);
        if (!oneUser){
            if (collect.size() > 0) {
                for (String login : collect
                ) {
                    SysUser u = sysUserService.selectUserByLoginName(login);
                    if (("0").equals(u.getIsSync())) {
                        String CustomerManager = u.getSysUserExt().getIsCustomerManager();
                        if (StringUtils.isNotEmpty(CustomerManager)){
                            String[] manager = CustomerManager.split(",");
                            if (manager.length > 1) {
                                if(assVOList !=null && assVOList.size()>0){
                                    boolean containsValue = assVOList.iterator().hasNext() && assVOList.iterator().next().getUserName().equals(u.getUserName());
                                    if(containsValue){
                                        for (UserAssVO vo:assVOList
                                        ) {
                                            if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber()) ){
                                                List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                                if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                                    assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                                }
                                            }
                                        }
                                    }

                                }
                                List<String> resultList = new ArrayList<>(manager.length);
                                Collections.addAll(resultList,manager);
                                Object i=isManager;
                                resultList.remove(i.toString());
                                String IsManager = resultList.stream().map(String::valueOf).collect(Collectors.joining(","));
                                u.getSysUserExt().setIsCustomerManager(IsManager);
                                sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                            } else {
                                if(assVOList !=null && assVOList.size()>0){
                                    boolean containsValue = assVOList.iterator().hasNext() && assVOList.iterator().next().getUserName().equals(u.getUserName());
                                    if(containsValue){
                                        for (UserAssVO vo:assVOList
                                        ) {
                                            if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                                List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                                if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                                    assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                                }else{
                                                    //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                                    if(("1").equals(u.getIsShopAccount())){
                                                        SysUserExt userExt = u.getSysUserExt();
                                                        if(userExt !=null){
                                                            userExt.setDelFlag("2");
                                                            userExt.setDelTime(new Date());
                                                            sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                                        }

                                                    }else{
                                                        u.setQuit("2");
                                                        sysUserService.updateUserInfo(u);
                                                    }
                                                }
                                            }
                                        }
                                    }else{
                                        //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                        if(("1").equals(u.getIsShopAccount())){
                                            SysUserExt userExt = u.getSysUserExt();
                                            if(userExt !=null){
                                                userExt.setDelFlag("2");
                                                userExt.setDelTime(new Date());
                                                sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                            }

                                        }else{
                                            u.setQuit("2");
                                            sysUserService.updateUserInfo(u);
                                        }
                                    }
                                }else{
                                    //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                    if(("1").equals(u.getIsShopAccount())){
                                        SysUserExt userExt = u.getSysUserExt();
                                        if(userExt !=null){
                                            userExt.setDelFlag("2");
                                            userExt.setDelTime(new Date());
                                            sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                        }

                                    }else{
                                        u.setQuit("2");
                                        sysUserService.updateUserInfo(u);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            log.info("数据同步当前数据：{}", jo);
            try {
                String userNo = jo.getString("userNo");
                String enable = jo.getString("enable");
                String name = jo.getString("name");
                String status = jo.getString("status");
                Boolean isSync = jo.getBoolean("isSync");
                Boolean isDelete = jo.getBoolean("isDelete");
                String userid = jo.getString("userid");
                String customerCode = jo.getString("depCode");
                String customerName = null;
                if (isManager != 0) {
                    customerName = jo.getString("depName");
                }
                /*企业微信中成员启用状态。1表示启用的成员，0表示被禁用*/
                /*if(enable==null||enable.trim().equals("0")){
                    continue;
                }
                *//*企业微信中人员激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。*//*
                if(status==null || !status.trim().equals("1")){
                    continue;
                }
                *//*人员信息是否已更新入企业微信。true：更新成功false：更新失败*//*
                if(!isSync){
                    continue;
                }
                *//*人员信息是否被标记删除true：删除，false：未删除*/
                if(isDelete){
                    continue;
                }
                if (userid == null || userid.trim().equals("")) {
                    continue;
                }
                loginNameSet = sysUserService.selectAllUserLoginName();
                loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
                if (!loginNameSet.contains(userid.toUpperCase().trim())) {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(userid);
                    user.setUserName(jo.getString("name"));
                    user.setPhonenumber(jo.getString("mobile"));
                    if (isManager == 0) {
                        user.setRoleIds(roleGuideIds);
                    }else if(isManager == 2){
                        user.setRoleIds(FinanceRoleIds);
                    }else if(isManager == 4){
                        user.setRoleIds(roleMsq);
                    }else if(isManager == 5){
                        user.setRoleIds(roleWqBm);
                    }else if(isManager == 3){
                        user.setRoleIds(HouseRoleIds);
                    }else if(isManager == 7){
                        user.setRoleIds(roleXls);
                    }else if(isManager == 9){
                        user.setRoleIds(roleSfa);
                    }else{
                        user.setRoleIds(roleIds);
                    }
                    user.setPassword(user.getLoginName());
                    user.setSalt(ShiroSaltUtil.randomSalt());
                    user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));


                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setSalesLevel("customer_level");
                    userExt.setIsCustomerManager(isManager + "");
                    userExt.setSapEmployeeId(userNo);
                    userExt.setIdentity(UserIdentityUtil.UI_DIY);
                    userExt.setPostName("DIY经销商");
                    String orgCode = jo.getString("depCode");
                    String code = null;
                    if (cusMap.containsKey(orgCode)) {
                        Customers c = cusMap.get(orgCode);
                        userExt.setOrgCode(c.getChainsCode());
                        userExt.setOrgName(c.getChainsName());
                        code = c.getChainsCode();
                    } else {
                        userExt.setOrgCode(orgCode);
                        userExt.setOrgName(customerName);
                    }
                    if (isManager == 0) {
                        userExt.setCustomerCode(userExt.getOrgCode());
                    } else {
                        userExt.setCustomerCode(jo.getString("depCode"));
                    }
//                    /**======== 构建diy用户wx信息表 start===============*/
//                    WxQyUser wxQyUser = new WxQyUser();
//                    wxQyUser.setUserid(jo.getString("userid"));
//                    wxQyUser.setMobile(jo.getString("mobile"));
                    user.setSysUserExt(userExt);
                    insertUserAndExt(user);
                    count++;
                    loginNameSet.add(userid);
                } else {
                    /*已经存在的，需要先清空职位，更新职位
                    （首先查询当前用户职位，判断当前职位是否包含当前职位，不存在就更新，存在就不更新）*/
                    //查询岗位现阶段存在的用户
                    SysUser userOld = sysUserService.selectUserByLoginName(userid);
                    SysUser user = sysUserService.selectUserByLoginName(userid);
                    //将用户扩展表的信息给加上
                    if(StringUtils.isBlank(user.getSysUserExt().getSalesLevel())){
                        log.info("进行用户扩展表信息补偿：--------userId:"+user.getSysUserExt().getUserId().toString());
                        SysUserExt userExt = new SysUserExt();
                        userExt.setUserId(user.getUserId());
                        userExt.setSalesLevel("customer_level");
                        userExt.setIsCustomerManager(isManager + "");
                        userExt.setSapEmployeeId(userNo);
                        userExt.setIdentity(UserIdentityUtil.UI_DIY);
                        userExt.setPostName("DIY经销商");
                        String orgCode = jo.getString("depCode");
                        String code = null;
                        if (cusMap.containsKey(orgCode)) {
                            Customers c = cusMap.get(orgCode);
                            userExt.setOrgCode(c.getChainsCode());
                            userExt.setOrgName(c.getChainsName());
                            code = c.getChainsCode();
                        } else {
                            userExt.setOrgCode(orgCode);
                            userExt.setOrgName(customerName);
                        }
                        if (isManager == 0) {
                            userExt.setCustomerCode(userExt.getOrgCode());
                        } else {
                            userExt.setCustomerCode(jo.getString("depCode"));
                        }
                        sysUserExtMapper.insertOrUpSysUserExt(userExt);
                        user.setSysUserExt(userExt);
                        userOld.setSysUserExt(userExt);
                    }
                    if (("0").equals(user.getIsSync())) {
                        //查询该用户是否存在该接口返回中
                        user.setPhonenumber(jo.getString("mobile"));
                        if (user.getSysUserExt().getIsCustomerManager() == null) {
                            user.getSysUserExt().setIsCustomerManager(isManager + "");
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        /*判断不是导购角色，更新经销商角色*/
//                    if (isManager == 1 || isManager == 2 || isManager == 3) {
//                        user.setRoleIds(roleIds);
//                        sysUserService.updateUser(user);
//                    }
                        //根据用户id和角色id删除

                        if (isManager == 0) {
                            sysUserService.insertUserRole(user.getUserId(), roleGuideIds[0]);
                        }else if(isManager == 2){
                            sysUserService.insertUserRole(user.getUserId(), FinanceRoleIds[0]);
                        }else if(isManager == 3){
                            sysUserService.insertUserRole(user.getUserId(), HouseRoleIds[0]);
                        }else if(isManager == 4){
                            sysUserService.insertUserRole(user.getUserId(), roleMsq[0]);
                        }else if(isManager == 5){
                            sysUserService.insertUserRole(user.getUserId(), roleWqBm[0]);
                        }else if (isManager ==7){
                            sysUserService.insertUserRole(user.getUserId(), roleXls[0]);
                        }else if(isManager == 9){
                            sysUserService.insertUserRole(user.getUserId(), roleSfa[0]);
                        }else {
                            sysUserService.insertUserRole(user.getUserId(), roleIds[0]);
                        }
                        if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "") ||
                                !user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                            if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "")) {
                                /*更新职位*/
                                user.getSysUserExt().setIsCustomerManager(user.getSysUserExt().getIsCustomerManager() + "," + isManager);
                            }
                            //处理导购多身份时，不更新经销商编码
                            if(!("019").equals(customerCode.substring(0, 3)) && isManager != 0){
                            if (!user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                                /*更新经销商code*/
                                if (cusMap.containsKey(customerCode)) {
                                    Customers c = cusMap.get(customerCode);
                                    user.getSysUserExt().setOrgCode(c.getChainsCode());
                                    user.getSysUserExt().setCustomerCode(c.getChainsCode());
                                    user.getSysUserExt().setOrgName(c.getChainsName());
                                } else {
                                    user.getSysUserExt().setOrgCode(customerCode);
                                    user.getSysUserExt().setCustomerCode(customerCode);
                                    user.getSysUserExt().setOrgName(customerName);
                                }
                            }
                            log.info("updateSysUserExt" + customerCode);
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                            }
                        }
                        if(("019").equals(user.getSysUserExt().getCustomerCode().substring(0, 3)) && ("0").equals(user.getSysUserExt().getIsCustomerManager())){
                            String isCustomerManager = user.getSysUserExt().getIsCustomerManager();
                            List<String> listManager = new ArrayList<>();
                            String[] split = isCustomerManager.split(",");
                            for (String s : split) {
                                if(s !=null && !("").equals(s)){
                                    listManager.add(s);
                                }
                            }
                            if(listManager.size() == 1 ){
                                user.getSysUserExt().setCustomerCode(customerCode);
                                user.getSysUserExt().setOrgCode(customerCode);
                                user.getSysUserExt().setOrgName(customerName);
                                sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                            }
                        }
                       /* if(user.getSysUserExt().getIsCustomerManager() !=null){
                            if(user.getSysUserExt().getIsCustomerManager().contains("0")){
                                if(("019").equals(user.getSysUserExt().getOrgCode().substring(0, 3))){
                                    if (cusMap.containsKey(customerCode)) {
                                        Customers c = cusMap.get(customerCode);
                                        user.getSysUserExt().setOrgCode(c.getChainsCode());
                                        user.getSysUserExt().setOrgName(c.getChainsName());
                                    } else {
                                        user.getSysUserExt().setOrgCode(customerCode);
                                        user.getSysUserExt().setOrgName(customerName);
                                    }
                                }
                            }
                        }*/
                        /*解决名称不一样的情况*/
                            user.setUserName(name);
                            sysUserService.updateUserInfo(user);

                        List<AssRelcustomerinfo> assRelcustomerinfoList = new ArrayList<>();
                        /*过滤导购*/
                        if (isManager != 0 && !("019").equals(userOld.getSysUserExt().getOrgCode().substring(0, 3)) && !("019").equals(userOld.getSysUserExt().getCustomerCode().substring(0, 3))
                                && !("019").equals(user.getSysUserExt().getOrgCode().substring(0, 3)) && !("019").equals(user.getSysUserExt().getCustomerCode().substring(0, 3))
                        ) {
                            log.info("到这了");
                            log.info("q:{}",userOld.getSysUserExt().getOrgCode());
                            log.info("q:{}",userOld.getSysUserExt().getCustomerCode());
                            log.info("q:{}",user.getSysUserExt().getOrgCode());
                            log.info("q:{}",customerCode);
                            if (user.getSysUserExt().getOrgCode() != null && (!customerCode.equals(userOld.getSysUserExt().getOrgCode()) || !customerCode.equals(userOld.getSysUserExt().getCustomerCode()) )) {

                                assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(customerCode, user.getUserId().toString());
                                if (assRelcustomerinfoList != null && assRelcustomerinfoList.size() > 0) {
                                    log.info("删除用户关联经销商----"+user.getUserId().toString()+"经销商身份代码--"+isManager);
                                    assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(user.getUserId().toString(), customerCode);
                                }


                                    AssRelcustomerinfo info = new AssRelcustomerinfo();
                                    info.setUserId(userOld.getUserId().toString());
                                    if(!customerCode.equals(userOld.getSysUserExt().getOrgCode())){
                                        info.setMainkunnr(userOld.getSysUserExt().getOrgCode());
                                    }else{
                                        info.setMainkunnr(userOld.getSysUserExt().getCustomerCode());
                                    }
                                    if (cusMap.containsKey(info.getMainkunnr())) {
                                        Customers c = cusMap.get(info.getMainkunnr());
                                        info.setMainname1(c.getChainsName());
                                    }
                                    info.setKunnr(customerCode);
                                    if (customerName != null && customerName != "") {
                                        info.setName1(customerName);
                                    } else {
                                         String Name = assRelcustomerinfoService.selectCustomerName(customerCode);
                                         info.setName1(Name);
                                    }
                                    info.setGlfs("用户关联");
                                    log.info("新增用户关联经销商----"+user.getUserId().toString());
                                    log.info("新增用户关联经销商----"+info+"经销商身份代码--"+isManager);
                                    assRelcustomerinfoService.insertAssRelcustomerinfo(info);

                                }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
                SyncFailDetail syncFailDetail = new SyncFailDetail();
                syncFailDetail.setPackageId(packageId);
                syncFailDetail.setFailReason(e.getMessage());
                syncFailDetail.setDataJson(jo.toJSONString());
                syncFailDetail.setFailLevel("1");
                syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                failDetails.add(syncFailDetail);
            }
        }

        return count;
    }


    /**
     * 构建 厨卫插入用户List
     * @param json
     * @param loginNameSet 排重用
     * @param
     * @return
     */
//    public Integer buildSysUserEbr(JSONObject json, Set<String> loginNameSet,Set<String> diyNameSet, List<SyncFailDetail> failDetails,String packageId, Map<String,Customers> cusMap){
//        JSONArray jsonArray = json.getJSONArray("data");
//        int count = 0;
//        List<String > interfaceList4=new ArrayList<>();
//        List<String > interfaceList5=new ArrayList<>();
//        List<String > interfaceList7=new ArrayList<>();
//        List<String > interfaceList9=new ArrayList<>();
//        for(int x =0;x<jsonArray.size();x++){
//            JSONObject jsonObject = jsonArray.getJSONObject(x);
//            String loginName = jsonObject.getString("userid");
//            String role=jsonObject.getString("role_code");
//            if(loginName !=null && !"".equals(loginName)){
//                if(role.equals("boss")){
//                    interfaceList4.add(loginName);
//                }else if(role.equals("manager")){
//                    interfaceList5.add(loginName);
//                }else if(role.equals("CWWH")){
//                    interfaceList7.add(loginName);
//                }else if(role.equals("business")){
//                    interfaceList9.add(loginName);
//                }
//
//            }
//        }
//        int isManager=1;
//        for(int i =0;i<jsonArray.size();i++){
//            JSONObject jo = jsonArray.getJSONObject(i);
//
//            try {
//                String role=jo.getString("role_code");
//              /*  if(role.equals("business")){
//                    continue;
//                }*/
//                String userNo = jo.getString("userNo");
//                String name = jo.getString("name");
//                String userid = jo.getString("userid");
//                String customerCode = jo.getString("depCode");
//                if(role.equals("boss")){
//                    isManager=4;
//                }else if(role.equals("manager")){
//                    isManager=5;
//                }else if(role.equals("CWWH")){
//                    isManager=7;
//                }else if(role.equals("business")){
//                    isManager=9;
//                }
//
//
//                /*企业微信中成员启用状态。1表示启用的成员，0表示被禁用*/
//                /*if(enable==null||enable.trim().equals("0")){
//                    continue;
//                }
//                *//*企业微信中人员激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。*//*
//                if(status==null || !status.trim().equals("1")){
//                    continue;
//                }
//                *//*人员信息是否已更新入企业微信。true：更新成功false：更新失败*//*
//                if(!isSync){
//                    continue;
//                }
//                *//*人员信息是否被标记删除true：删除，false：未删除*//*
//                if(isDelete){
//                    continue;
//                }*/
//                if(userid==null||userid.trim().equals("")){
//                    continue;
//                }
//                loginNameSet = sysUserService.selectAllUserLoginName();
//                diyNameSet = sysUserService.selectDiyUserLoginName();
//                loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
//                if (!loginNameSet.contains(userid.toUpperCase().trim())) {
//
//                    /** =============用户基本信息构建 start===============*/
//                    SysUser user = new SysUser();
//                    user.setCompanyId(1L);
//                    user.setDeptId(deptId);
//                    user.setLoginName(userid);
//                    user.setUserName(jo.getString("name"));
//                    user.setPhonenumber(jo.getString("mobile"));
//                    if(role.equals("business")){
//                        user.setRoleIds(roleBusiness);
//                    } else if (diyNameSet.contains(userid) && !role.equals("business")) {
//                        user.setRoleIds(roleCwDiyIds);
//                    } else if(!role.equals("business")){
//                        user.setRoleIds(roleCwIds);
//                    }
//                    user.setPassword(user.getLoginName());
//                    user.setSalt(ShiroSaltUtil.randomSalt());
//                    user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
//
//
//                    /** =============用户基本信息构建 end===============*/
//
//
//                    /**======== 构建diy用户扩展信息表 start===============*/
//                    SysUserExt userExt = new SysUserExt();
//                    userExt.setSalesLevel("customer_level");
//
//                    userExt.setIdentity(UserIdentityUtil.UI_CW);// 1=diy,2=ebr,3=all
//
//                    userExt.setCustomerCode(jo.getString("depCode"));
//                    userExt.setIsCustomerManager(isManager + "");
//                    userExt.setSapEmployeeId(userNo);
//
//                    userExt.setPostName("CW经销商");
//                    String orgCode = jo.getString("depCode");
//                    if(cusMap.containsKey(orgCode)){
//                        Customers c = cusMap.get(orgCode);
//                        userExt.setOrgCode(c.getChainsCode());
//                        userExt.setOrgName(c.getChainsName());
//                    }else{
//                        userExt.setOrgCode(orgCode);
//                        //userExt.setOrgName(customerName);
//                    }
//
////                    /**======== 构建diy用户wx信息表 start===============*/
////                    WxQyUser wxQyUser = new WxQyUser();
////                    wxQyUser.setUserid(jo.getString("userid"));
////                    wxQyUser.setMobile(jo.getString("mobile"));
//                    user.setSysUserExt(userExt);
//                    insertUserAndExt(user);
//                    count++;
//                    loginNameSet.add(userid);
//                }else{
//                    /*已经存在的，需要先清空职位，更新职位
//                    （首先查询当前用户职位，判断当前职位是否包含当前职位，不存在就更新，存在就不更新）*/
//                    SysUser user = sysUserService.selectUserByLoginName(userid);
//                    if(("0").equals(user.getIsSync())){
//                        //每个接口查询俩次是否有重复开始查询一次，快结束查一次
//                        //查询该用户是否存在该接口返回中
//                        if(user.getSysUserExt().getIsCustomerManager()==null ){
//                            user.getSysUserExt().setIsCustomerManager(isManager+ "");
//                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
//                        }
//                        List<AssRelcustomerinfo>  assRelcustomerinfoList=new ArrayList<>();
//                        if ( !("019").equals(user.getSysUserExt().getOrgCode().substring(0,3)) && !("019").equals(user.getSysUserExt().getCustomerCode().substring(0,3))) {
//                            if (!customerCode.equals(user.getSysUserExt().getCustomerCode())) {
//                                assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(customerCode, user.getUserId().toString());
//                                if (assRelcustomerinfoList != null && assRelcustomerinfoList.size() > 0) {
//                                    assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(user.getUserId().toString(), customerCode);
//                                }
//                                assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(customerCode, user.getUserId().toString());
//                                if (assRelcustomerinfoList == null || assRelcustomerinfoList.size() == 0) {
//                                    String customerName = assRelcustomerinfoService.selectCustomerName(customerCode);
//                                    AssRelcustomerinfo info = new AssRelcustomerinfo();
//                                    info.setUserId(user.getUserId().toString());
//                                    info.setMainkunnr(user.getSysUserExt().getCustomerCode());
//                                    info.setMainname1(user.getSysUserExt().getOrgName());
//                                    info.setKunnr(customerCode);
//                                    if (customerName != null && customerName != "") {
//                                        info.setName1(customerName);
//                                    }else {
//                                        if (cusMap.containsKey(info.getKunnr())) {
//                                            Customers c = cusMap.get(info.getKunnr());
//                                            info.setName1(c.getChainsName());
//                                        }
//                                    }
//                                    info.setGlfs("用户关联");
//                                    assRelcustomerinfoService.insertAssRelcustomerinfo(info);
//
//                                }
//
//                            }
//                        }
//                        if (diyNameSet.contains(userid) && !role.equals("business")) {
//                            sysUserService.insertUserRole(user.getUserId(), roleIds[0]);
//                            sysUserService.insertUserRole(user.getUserId(), roleCwIds[0]);
//                        } else if(role.equals("business")){
//                            sysUserService.insertUserRole(user.getUserId(), roleBusiness[0]);
//                        }else if(!role.equals("business")) {
//                            sysUserService.insertUserRole(user.getUserId(), roleCwIds[0]);
//                        }
//
//                        if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "") ||
//                                !user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
//                            if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "")) {
//                                /*更新职位*/
//                                user.getSysUserExt().setIsCustomerManager(user.getSysUserExt().getIsCustomerManager() + "," + isManager);
//                            }
//                            if (!user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
//                                /*更新经销商code*/
//                                if (cusMap.containsKey(customerCode)) {
//                                    Customers c = cusMap.get(customerCode);
//                                    user.getSysUserExt().setOrgCode(c.getChainsCode());
//                                    user.getSysUserExt().setOrgName(c.getChainsName());
//                                } else {
//                                    user.getSysUserExt().setOrgCode(customerCode);
//
//                                }
//                            }
//                            log.info("updateSysUserExt" + customerCode);
//                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
//                        }
//                        /*解决名称不一样的情况*/
//                        if(!user.getUserName().equals(name)){
//                            user.setUserName(name);
//                            sysUserService.updateUserInfo(user);
//                        }
//                        //更新 identity 1=diy,2=ebr,3=all
//                        if (diyNameSet.contains(userid) && !"1,2".equals(user.getSysUserExt().getIdentity())) {
//
//                            log.info("updateSysUserExt identity 1,2" + userid);
//                            user.getSysUserExt().setIdentity(UserIdentityUtil.UI_DIY+","+UserIdentityUtil.UI_CW);
//
//                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
//                        }
//                        if (!diyNameSet.contains(userid) && !"2".equals(user.getSysUserExt().getIdentity())) {
//                            log.info("updateSysUserExt identity 2" + userid);
//                            user.getSysUserExt().setIdentity(UserIdentityUtil.UI_CW);
//                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
//                        }
//                    }
//                }
//            }catch (Exception e){
//                log.error(e.getMessage());
//                e.printStackTrace();
//                SyncFailDetail syncFailDetail = new SyncFailDetail();
//                syncFailDetail.setPackageId(packageId);
//                syncFailDetail.setFailReason(e.getMessage());
//                syncFailDetail.setDataJson(jo.toJSONString());
//                syncFailDetail.setFailLevel("1");
//                syncFailDetail.setExceptionType(e.getClass().getSimpleName());
//                failDetails.add(syncFailDetail);
//            }
//        }
//        //厨卫老板
//        List<String> loginNames4=sysUserService.selectUserByIsManager(4);
//        //厨卫经理
//        List<String> loginNames5=sysUserService.selectUserByIsManager(5);
//        //厨卫仓管
//        List<String> loginNames7=sysUserService.selectUserByIsManager(7);
//        //厨卫业务人员
//        List<String> loginNames9=sysUserService.selectUserByIsManager(9);
//        List<String> collect4 =new ArrayList<>();
//        loginNames4.removeAll(interfaceList4);
//        collect4.addAll(loginNames4);
//        this.uninoncw(collect4, 4);
//        List<String> collect5 =new ArrayList<>();
//        loginNames5.removeAll(interfaceList5);
//        collect5.addAll(loginNames5);
//        this.uninoncw(collect5, 5);
//        List<String> collect7 =new ArrayList<>();
//        loginNames7.removeAll(interfaceList7);
//        collect7.addAll(loginNames7);
//        this.uninoncw(collect7, 7);
//        List<String> collect9 =new ArrayList<>();
//        loginNames9.removeAll(interfaceList9);
//        collect9.addAll(loginNames9);
//        this.uninoncw(collect9, 9);
//        return count;
//    }

    /*void uninoncw( List<String> collect, int isManager){
        if (collect.size() > 0) {
            for (String login:collect
            ) {
                SysUser u = sysUserService.selectUserByLoginName(login);
                if(("0").equals(u.getIsSync())){
                    String CustomerManager= u.getSysUserExt().getIsCustomerManager();
                    String[] manager=CustomerManager.split(",");
                    if(manager.length >1){
                        List<String> resultList = new ArrayList<>(manager.length);
                        Collections.addAll(resultList,manager);
                        Object i=isManager;
                        resultList.remove(i.toString());
                        String IsManager = resultList.stream().map(String::valueOf).collect(Collectors.joining(","));
                        u.getSysUserExt().setIsCustomerManager(IsManager);
                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                    }else{
                        u.setQuit("2");
                        sysUserService.updateUserInfo(u);
                    }
                }
            }
        }
    }*/

    /***
     *
     * 3.6
     * **/
    public Integer buildSysUserStaff(JSONArray STAFF, Set<String> loginNameSet,Set<String> diyNameSet, List<SyncFailDetail> failDetails,String packageId, Map<String,Customers> cusMap,Integer isManager){
        //JSONArray jsonArray = json.getJSONArray("data");
        int count = 0;
        List<String > interfaceList8=new ArrayList<>();
        List<UserAssVO> assVOList8 =new ArrayList<>();
        for(int x =0;x<STAFF.size();x++){
            JSONObject jsonObject = STAFF.getJSONObject(x);
            String loginName = jsonObject.getString("userid");
            Boolean isDelete = jsonObject.getBoolean("isDelete");
            if(isDelete){
                String customerCode = jsonObject.getString("depCode");
                String name = jsonObject.getString("name");
                String phone = jsonObject.getString("mobile");
                UserAssVO assVO =new UserAssVO();
                assVO.setUserName(name);
                assVO.setPhone(phone);
                assVO.setCustomerCode(customerCode);
                assVOList8.add(assVO);
                continue;
            }
            if(loginName !=null && !"".equals(loginName)){
                    interfaceList8.add(loginName);
            }
        }
        for(int i =0;i<STAFF.size();i++){
            JSONObject jo = STAFF.getJSONObject(i);

            try {
                String userNo = jo.getString("userNo");
                String name = jo.getString("name");
                String userid = jo.getString("userid");
                String customerCode = jo.getString("depCode");
                Boolean isDelete = jo.getBoolean("isDelete");

                /*企业微信中成员启用状态。1表示启用的成员，0表示被禁用*/
                /*if(enable==null||enable.trim().equals("0")){
                    continue;
                }
                *//*企业微信中人员激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。*//*
                if(status==null || !status.trim().equals("1")){
                    continue;
                }
                *//*人员信息是否已更新入企业微信。true：更新成功false：更新失败*//*
                if(!isSync){
                    continue;
                }
                *//*人员信息是否被标记删除true：删除，false：未删除*/
                if(isDelete){
                    continue;
                }
                if(userid==null||userid.trim().equals("")){
                    continue;
                }
                loginNameSet = sysUserService.selectAllUserLoginName();
                diyNameSet = sysUserService.selectDiyUserLoginName();
                loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
                if (!loginNameSet.contains(userid.toUpperCase().trim())) {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(userid);
                    user.setUserName(jo.getString("name"));
                    user.setPhonenumber(jo.getString("mobile"));
                    user.setRoleIds(roleStoreIds);
                    user.setPassword(user.getLoginName());
                    user.setSalt(ShiroSaltUtil.randomSalt());
                    user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));


                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setSalesLevel("customer_level");

                    userExt.setIdentity(UserIdentityUtil.UI_DIY);// 1=diy,2=ebr,3=all

                    userExt.setCustomerCode(jo.getString("depCode"));
                    userExt.setIsCustomerManager(isManager + "");
                    userExt.setSapEmployeeId(userNo);

                    userExt.setPostName("DIY经销商");
                    String orgCode = jo.getString("depCode");
                    if(cusMap.containsKey(orgCode)){
                        Customers c = cusMap.get(orgCode);
                        userExt.setOrgCode(c.getChainsCode());
                        userExt.setOrgName(c.getChainsName());
                    }else{
                        userExt.setOrgCode(orgCode);
                    }

//                    /**======== 构建diy用户wx信息表 start===============*/
//                    WxQyUser wxQyUser = new WxQyUser();
//                    wxQyUser.setUserid(jo.getString("userid"));
//                    wxQyUser.setMobile(jo.getString("mobile"));
                    user.setSysUserExt(userExt);
                    insertUserAndExt(user);
                    count++;
                    loginNameSet.add(userid);
                    diyNameSet.add(userid);
                }else{
                    /*已经存在的，需要先清空职位，更新职位
                    （首先查询当前用户职位，判断当前职位是否包含当前职位，不存在就更新，存在就不更新）*/
                    SysUser user = sysUserService.selectUserByLoginName(userid);
                    if(("0").equals(user.getIsSync())){
                        user.setPhonenumber(jo.getString("mobile"));
                        //每个接口查询俩次是否有重复开始查询一次，快结束查一次
                        //查询该用户是否存在该接口返回中
                        sysUserService.insertUserRole(user.getUserId(), roleStoreIds[0]);
                        if (user.getSysUserExt().getIsCustomerManager() == null) {
                            user.getSysUserExt().setIsCustomerManager(isManager + "");
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "") ||
                                !user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                            if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "")) {
                                /*更新职位*/
                                user.getSysUserExt().setIsCustomerManager(user.getSysUserExt().getIsCustomerManager() + "," + isManager);
                            }
                            if (!user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                                /*更新经销商code*/
                                if (cusMap.containsKey(customerCode)) {
                                    Customers c = cusMap.get(customerCode);
                                    user.getSysUserExt().setOrgCode(c.getChainsCode());
                                    user.getSysUserExt().setCustomerCode(c.getChainsCode());
                                    user.getSysUserExt().setOrgName(c.getChainsName());

                                } else {
                                    user.getSysUserExt().setCustomerCode(customerCode);
                                    user.getSysUserExt().setOrgCode(customerCode);

                                }
                            }
                            log.info("updateSysUserExt" + customerCode);
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        /*解决名称不一样的情况*/
                            user.setUserName(name);
                            sysUserService.updateUserInfo(user);



                    }
                }
            }catch (Exception e){
                log.error(e.getMessage());
                e.printStackTrace();
                SyncFailDetail syncFailDetail = new SyncFailDetail();
                syncFailDetail.setPackageId(packageId);
                syncFailDetail.setFailReason(e.getMessage());
                syncFailDetail.setDataJson(jo.toJSONString());
                syncFailDetail.setFailLevel("1");
                syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                failDetails.add(syncFailDetail);
            }
        }
        List<String> loginNames=sysUserService.selectUserByIsManager(isManager);
        List<String> collect =new ArrayList<>();
        loginNames.removeAll(interfaceList8);
        collect.addAll(loginNames);
        if (collect.size() > 0) {
            for (String login:collect
            ) {
                SysUser u = sysUserService.selectUserByLoginName(login);
                if(("0").equals(u.getIsSync())){
                    String CustomerManager= u.getSysUserExt().getIsCustomerManager();
                    String[] manager=CustomerManager.split(",");
                    if(manager.length >1){
                        if(assVOList8 !=null && assVOList8.size()>0){
                            boolean containsValue = assVOList8.iterator().hasNext() && assVOList8.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList8
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }
                                    }
                                }
                            }

                        }
                        List<String> resultList = new ArrayList<>(manager.length);
                        Collections.addAll(resultList,manager);
                        Object i=isManager;
                        resultList.remove(i.toString());
                        String IsManager = resultList.stream().map(String::valueOf).collect(Collectors.joining(","));
                        u.getSysUserExt().setIsCustomerManager(IsManager);
                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                    }else{
                        if(assVOList8 !=null && assVOList8.size()>0){
                            boolean containsValue = assVOList8.iterator().hasNext() && assVOList8.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList8
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }else{
                                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                            if(("1").equals(u.getIsShopAccount())){
                                                SysUserExt userExt = u.getSysUserExt();
                                                if(userExt !=null){
                                                    userExt.setDelFlag("2");
                                                    userExt.setDelTime(new Date());
                                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                                }

                                            }else{
                                                u.setQuit("2");
                                                sysUserService.updateUserInfo(u);
                                            }
                                        }
                                    }
                                }
                            }else{
                                //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                if(("1").equals(u.getIsShopAccount())){
                                    SysUserExt userExt = u.getSysUserExt();
                                    if(userExt !=null){
                                        userExt.setDelFlag("2");
                                        userExt.setDelTime(new Date());
                                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                    }

                                }else{
                                    u.setQuit("2");
                                    sysUserService.updateUserInfo(u);
                                }
                            }
                        }else{
                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                            if(("1").equals(u.getIsShopAccount())){
                                SysUserExt userExt = u.getSysUserExt();
                                if(userExt !=null){
                                    userExt.setDelFlag("2");
                                    userExt.setDelTime(new Date());
                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                }

                            }else{
                                u.setQuit("2");
                                sysUserService.updateUserInfo(u);
                            }
                        }
                    }
                }
            }
        }

        return count;
    }

    /***
     *
     *3.7经销商经销人员门店
     * **/
    public Integer buildSysUserBz(JSONArray BZ, Set<String> loginNameSet,Set<String> diyNameSet, List<SyncFailDetail> failDetails,String packageId, Map<String,Customers> cusMap,Integer isManager){
        //JSONArray jsonArray = json.getJSONArray("data");
        int count = 0;
        List<String > interfaceList5=new ArrayList<>();
        List<UserAssVO> assVOList5 =new ArrayList<>();
        for(int x =0;x<BZ.size();x++){
            JSONObject jsonObject = BZ.getJSONObject(x);
            String loginName = jsonObject.getString("userid");
            Boolean isDelete = jsonObject.getBoolean("isDelete");
            if(isDelete){
                String customerCode = jsonObject.getString("depCode");
                String name = jsonObject.getString("name");
                UserAssVO assVO =new UserAssVO();
                assVO.setUserName(name);
                String phone = jsonObject.getString("mobile");
                assVO.setPhone(phone);
                assVO.setCustomerCode(customerCode);
                assVOList5.add(assVO);
                continue;
            }
            if(loginName !=null && !"".equals(loginName)){
                    interfaceList5.add(loginName);
            }
        }
        for(int i =0;i<BZ.size();i++){
            JSONObject jo = BZ.getJSONObject(i);

            try {
                String userNo = jo.getString("userNo");
                String name = jo.getString("name");
                String userid = jo.getString("userid");
                String customerCode = jo.getString("depCode");
                Boolean isDelete = jo.getBoolean("isDelete");

                /*企业微信中成员启用状态。1表示启用的成员，0表示被禁用*/
                /*if(enable==null||enable.trim().equals("0")){
                    continue;
                }
                *//*企业微信中人员激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。*//*
                if(status==null || !status.trim().equals("1")){
                    continue;
                }
                *//*人员信息是否已更新入企业微信。true：更新成功false：更新失败*//*
                if(!isSync){
                    continue;
                }
                *//*人员信息是否被标记删除true：删除，false：未删除*/
                if(isDelete){
                    continue;
                }
                if(userid==null||userid.trim().equals("")){
                    continue;
                }
                loginNameSet = sysUserService.selectAllUserLoginName();
                diyNameSet = sysUserService.selectDiyUserLoginName();
                loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
                if (!loginNameSet.contains(userid.toUpperCase().trim())) {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(userid);
                    user.setUserName(jo.getString("name"));
                    user.setPhonenumber(jo.getString("mobile"));
                    user.setRoleIds(roleStoreIds);
                    user.setPassword(user.getLoginName());
                    user.setSalt(ShiroSaltUtil.randomSalt());
                    user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));


                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setSalesLevel("customer_level");

                    userExt.setIdentity(UserIdentityUtil.UI_DIY);// 1=diy,2=ebr,3=all

                    userExt.setCustomerCode(jo.getString("depCode"));
                    userExt.setIsCustomerManager(isManager + "");
                    userExt.setSapEmployeeId(userNo);

                    userExt.setPostName("DIY经销商");
                    String orgCode = jo.getString("depCode");
                    if(cusMap.containsKey(orgCode)){
                        Customers c = cusMap.get(orgCode);
                        userExt.setOrgCode(c.getChainsCode());
                        userExt.setOrgName(c.getChainsName());
                    }else{
                        userExt.setOrgCode(orgCode);
                    }

//                    /**======== 构建diy用户wx信息表 start===============*/
//                    WxQyUser wxQyUser = new WxQyUser();
//                    wxQyUser.setUserid(jo.getString("userid"));
//                    wxQyUser.setMobile(jo.getString("mobile"));
                    user.setSysUserExt(userExt);
                    insertUserAndExt(user);
                    count++;
                    loginNameSet.add(userid);
                    diyNameSet.add(userid);
                }else{
                    /*已经存在的，需要先清空职位，更新职位
                    （首先查询当前用户职位，判断当前职位是否包含当前职位，不存在就更新，存在就不更新）*/
                    SysUser user = sysUserService.selectUserByLoginName(userid);
                    if(("0").equals(user.getIsSync())){
                        user.setPhonenumber(jo.getString("mobile"));
                        //每个接口查询俩次是否有重复开始查询一次，快结束查一次
                        //查询该用户是否存在该接口返回中
                        sysUserService.insertUserRole(user.getUserId(), roleStoreIds[0]);
                        if (user.getSysUserExt().getIsCustomerManager() == null) {
                            user.getSysUserExt().setIsCustomerManager(isManager + "");
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "") ||
                                !user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                            if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "")) {
                                /*更新职位*/
                                user.getSysUserExt().setIsCustomerManager(user.getSysUserExt().getIsCustomerManager() + "," + isManager);
                            }
                            if (!user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                                /*更新经销商code*/
                                if (cusMap.containsKey(customerCode)) {
                                    Customers c = cusMap.get(customerCode);
                                    user.getSysUserExt().setOrgCode(c.getChainsCode());
                                    user.getSysUserExt().setCustomerCode(c.getChainsCode());
                                    user.getSysUserExt().setOrgName(c.getChainsName());
                                } else {
                                    user.getSysUserExt().setCustomerCode(customerCode);
                                    user.getSysUserExt().setOrgCode(customerCode);
                                }
                            }
                            log.info("updateSysUserExt" + customerCode);
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        /*解决名称不一样的情况*/
                            user.setUserName(name);
                            sysUserService.updateUserInfo(user);



                    }
                }
            }catch (Exception e){
                log.error(e.getMessage());
                e.printStackTrace();
                SyncFailDetail syncFailDetail = new SyncFailDetail();
                syncFailDetail.setPackageId(packageId);
                syncFailDetail.setFailReason(e.getMessage());
                syncFailDetail.setDataJson(jo.toJSONString());
                syncFailDetail.setFailLevel("1");
                syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                failDetails.add(syncFailDetail);
            }
        }
        List<String> loginNames=sysUserService.selectUserByIsManager(isManager);
        List<String> collect =new ArrayList<>();
        loginNames.removeAll(interfaceList5);
        collect.addAll(loginNames);
        if (collect.size() > 0) {
            for (String login:collect
            ) {
                SysUser u = sysUserService.selectUserByLoginName(login);
                if(("0").equals(u.getIsSync())){
                    String CustomerManager= u.getSysUserExt().getIsCustomerManager();
                    String[] manager=CustomerManager.split(",");
                    if(manager.length >1){
                        if(assVOList5 !=null && assVOList5.size()>0){
                            boolean containsValue = assVOList5.iterator().hasNext() && assVOList5.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList5
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }
                                    }
                                }
                            }

                        }
                        List<String> resultList = new ArrayList<>(manager.length);
                        Collections.addAll(resultList,manager);
                        Object i=isManager;
                        resultList.remove(i.toString());
                        String IsManager = resultList.stream().map(String::valueOf).collect(Collectors.joining(","));
                        u.getSysUserExt().setIsCustomerManager(IsManager);
                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                    }else{
                        if(assVOList5 !=null && assVOList5.size()>0){
                            boolean containsValue = assVOList5.iterator().hasNext() && assVOList5.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList5
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }else{
                                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                            if(("1").equals(u.getIsShopAccount())){
                                                SysUserExt userExt = u.getSysUserExt();
                                                if(userExt !=null){
                                                    userExt.setDelFlag("2");
                                                    userExt.setDelTime(new Date());
                                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                                }

                                            }else{
                                                u.setQuit("2");
                                                sysUserService.updateUserInfo(u);
                                            }
                                        }
                                    }
                                }
                            }else{
                                //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                if(("1").equals(u.getIsShopAccount())){
                                    SysUserExt userExt = u.getSysUserExt();
                                    if(userExt !=null){
                                        userExt.setDelFlag("2");
                                        userExt.setDelTime(new Date());
                                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                    }

                                }else{
                                    u.setQuit("2");
                                    sysUserService.updateUserInfo(u);
                                }
                            }
                        }else{
                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                            if(("1").equals(u.getIsShopAccount())){
                                SysUserExt userExt = u.getSysUserExt();
                                if(userExt !=null){
                                    userExt.setDelFlag("2");
                                    userExt.setDelTime(new Date());
                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                }

                            }else{
                                u.setQuit("2");
                                sysUserService.updateUserInfo(u);
                            }
                        }
                    }
                }
            }
        }

        return count;
    }
    /**
     * 构建 插入分销 3.4 分销业务员人员 List
     * @param
     * @param loginNameSet 排重用
     * @param isManager
     * @return
     */
    public Integer buildSysUserFx(JSONArray jsonArray, Set<String> loginNameSet, int isManager, List<SyncFailDetail> failDetails,String packageId, Map<String,Customers> cusMap){
        //JSONArray jsonArray = json.getJSONArray("userlist");
        int count = 0;
        List<String > interfaceList=new ArrayList<>();
        List<UserAssVO> assVOList =new ArrayList<>();
        for(int x =0;x<jsonArray.size();x++){
            JSONObject jsonObject = jsonArray.getJSONObject(x);
            String loginName = jsonObject.getString("userid");
            Boolean isDelete = jsonObject.getBoolean("isDelete");
            if(isDelete){
                String customerCode = jsonObject.getString("depCode");
                String name = jsonObject.getString("name");
                UserAssVO assVO =new UserAssVO();
                assVO.setUserName(name);
                String phone = jsonObject.getString("mobile");
                assVO.setPhone(phone);
                assVO.setCustomerCode(customerCode);
                assVOList.add(assVO);
                continue;
            }
            if(loginName!=null && !"".equals(loginName)){
                interfaceList.add(loginName);
            }
        }
        for(int i =0;i<jsonArray.size();i++){
            JSONObject jo = jsonArray.getJSONObject(i);

            try {
                String userNo = jo.getString("userNo");
                String enable = jo.getString("enable");
                String name = jo.getString("name");
                String status = jo.getString("status");
                Boolean isSync = jo.getBoolean("isSync");
                Boolean isDelete = jo.getBoolean("isDelete");
                String userid = jo.getString("userid");
                String customerCode = jo.getString("depCode");
                String customerName=null;
                if (isManager != 0) {
                    customerName=jo.getString("depName");
                }
                /*企业微信中成员启用状态。1表示启用的成员，0表示被禁用*/
                /*if(enable==null||enable.trim().equals("0")){
                    continue;
                }
                *//*企业微信中人员激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业。*//*
                if(status==null || !status.trim().equals("1")){
                    continue;
                }
                *//*人员信息是否已更新入企业微信。true：更新成功false：更新失败*//*
                if(!isSync){
                    continue;
                }
                *//*人员信息是否被标记删除true：删除，false：未删除*/
                if(isDelete){
                    continue;
                }
                if(userid==null||userid.trim().equals("")){
                    continue;
                }
                loginNameSet = sysUserService.selectAllUserLoginName();
                loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
                if (!loginNameSet.contains(userid.toUpperCase().trim())) {

                    /** =============用户基本信息构建 start===============*/
                    SysUser user = new SysUser();
                    user.setCompanyId(1L);
                    user.setDeptId(deptId);
                    user.setLoginName(userid);
                    user.setUserName(jo.getString("name"));
                    user.setPhonenumber(jo.getString("mobile"));

                    if (isManager == 6) {
                        user.setRoleIds(roleFXDiyIds);
                    } else {
                        user.setRoleIds(roleIds);
                    }
                    user.setPassword(user.getLoginName());
                    user.setSalt(ShiroSaltUtil.randomSalt());
                    user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));


                    /** =============用户基本信息构建 end===============*/


                    /**======== 构建diy用户扩展信息表 start===============*/
                    SysUserExt userExt = new SysUserExt();
                    userExt.setSalesLevel("customer_level");
                    userExt.setCustomerCode(jo.getString("depCode"));
                    userExt.setIsCustomerManager(isManager + "");
                    userExt.setSapEmployeeId(userNo);

                    userExt.setPostName("经销商分销业务员");
                    String orgCode = jo.getString("depCode");
                    if(cusMap.containsKey(orgCode)){
                        Customers c = cusMap.get(orgCode);
                        userExt.setOrgCode(c.getChainsCode());
                        userExt.setOrgName(c.getChainsName());
                    }else{
                        userExt.setOrgCode(orgCode);
                    }

//                    /**======== 构建diy用户wx信息表 start===============*/
//                    WxQyUser wxQyUser = new WxQyUser();
//                    wxQyUser.setUserid(jo.getString("userid"));
//                    wxQyUser.setMobile(jo.getString("mobile"));
                    user.setSysUserExt(userExt);
                    insertUserAndExt(user);
                    count++;
                    loginNameSet.add(userid);
                }else{
                    /*已经存在的，需要先清空职位，更新职位
                    （首先查询当前用户职位，判断当前职位是否包含当前职位，不存在就更新，存在就不更新）*/

                    SysUser user = sysUserService.selectUserByLoginName(userid);
                    user.getSysUserExt().setSalesLevel("customer_level");
                    if(("0").equals(user.getIsSync())){
                        user.setPhonenumber(jo.getString("mobile"));
                        //每个接口查询俩次是否有重复开始查询一次，快结束查一次
                        //查询该用户是否存在该接口返回中
                        if(user.getSysUserExt().getIsCustomerManager()==null ){
                            user.getSysUserExt().setIsCustomerManager(isManager+ "");
                            sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        }
                        /*判断不是导购角色，更新经销商角色*/
//                    if (isManager == 1 || isManager == 2 || isManager == 3) {
//                        user.setRoleIds(roleIds);
//                        sysUserService.updateUser(user);
//                    }

                        sysUserService.insertUserRole(user.getUserId(), roleFXDiyIds[0]);

                        if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "") ||
                                !user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                            if (!user.getSysUserExt().getIsCustomerManager().contains(isManager + "")) {
                                /*更新职位*/
                                user.getSysUserExt().setIsCustomerManager(user.getSysUserExt().getIsCustomerManager() + "," + isManager);
                            }
                            if (!user.getSysUserExt().getCustomerCode().equals(customerCode) || !user.getSysUserExt().getOrgCode().equals(customerCode)) {
                                /*更新经销商code*/
                                if (cusMap.containsKey(customerCode)) {
                                    Customers c = cusMap.get(customerCode);
                                    user.getSysUserExt().setOrgCode(c.getChainsCode());
                                    user.getSysUserExt().setCustomerCode(c.getChainsCode());
                                    user.getSysUserExt().setOrgName(c.getChainsName());
                                } else {
                                    user.getSysUserExt().setCustomerCode(customerCode);
                                    user.getSysUserExt().setOrgCode(customerCode);
                                }
                            }
                            log.info("updateSysUserExt" + customerCode);
                        }
                        sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                        /*解决名称不一样的情况*/
                            user.setUserName(name);
                            sysUserService.updateUserInfo(user);
                    }
                    sysUserExtMapper.updateSysUserExt(user.getSysUserExt());
                }
            }catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
                SyncFailDetail syncFailDetail = new SyncFailDetail();
                syncFailDetail.setPackageId(packageId);
                syncFailDetail.setFailReason(e.getMessage());
                syncFailDetail.setDataJson(jo.toJSONString());
                syncFailDetail.setFailLevel("1");
                syncFailDetail.setExceptionType(e.getClass().getSimpleName());
                failDetails.add(syncFailDetail);
            }
        }
        List<String> loginNames = sysUserService.selectUserByIsManager(isManager);
        List<String> collect =new ArrayList<>();
        loginNames.removeAll(interfaceList);
        collect.addAll(loginNames);
        if (collect.size() > 0) {
            for (String login : collect
            ) {
                SysUser u = sysUserService.selectUserByLoginName(login);
                if (("0").equals(u.getIsSync())) {
                    String CustomerManager = u.getSysUserExt().getIsCustomerManager();
                    String[] manager = CustomerManager.split(",");
                    if (manager.length > 1) {
                        if(assVOList !=null && assVOList.size()>0){
                            boolean containsValue = assVOList.iterator().hasNext() && assVOList.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }
                                    }
                                }
                            }

                        }
                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(null, String.valueOf(u.getUserId()));
                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), null);
                        }
                        List<String> resultList = new ArrayList<>(manager.length);
                        Collections.addAll(resultList,manager);
                        Object i=isManager;
                        resultList.remove(i.toString());
                        String IsManager = resultList.stream().map(String::valueOf).collect(Collectors.joining(","));
                        u.getSysUserExt().setIsCustomerManager(IsManager);
                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                    } else {
                        if(assVOList !=null && assVOList.size()>0){
                            boolean containsValue = assVOList.iterator().hasNext() && assVOList.iterator().next().getUserName().equals(u.getUserName());
                            if(containsValue){
                                for (UserAssVO vo:assVOList
                                ) {
                                    if(vo.getUserName().equals(u.getUserName()) && vo.getPhone().equals(u.getPhonenumber())){
                                        List<AssRelcustomerinfo> assRelcustomerinfoList = assRelcustomerinfoService.selectRelcustomerinfoByKunnr(vo.getCustomerCode(), String.valueOf(u.getUserId()));
                                        if(assRelcustomerinfoList !=null && assRelcustomerinfoList.size()>0){
                                            assRelcustomerinfoService.deleteAssRelcustomerinfoByUserId(u.getUserId().toString(), vo.getCustomerCode());
                                        }else{
                                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                            if(("1").equals(u.getIsShopAccount())){
                                                SysUserExt userExt = u.getSysUserExt();
                                                if(userExt !=null){
                                                    userExt.setDelFlag("2");
                                                    userExt.setDelTime(new Date());
                                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                                }

                                            }else{
                                                u.setQuit("2");
                                                sysUserService.updateUserInfo(u);
                                            }
                                        }
                                    }
                                }
                            }else{
                                //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                                if(("1").equals(u.getIsShopAccount())){
                                    SysUserExt userExt = u.getSysUserExt();
                                    if(userExt !=null){
                                        userExt.setDelFlag("2");
                                        userExt.setDelTime(new Date());
                                        sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                    }

                                }else{
                                    u.setQuit("2");
                                    sysUserService.updateUserInfo(u);
                                }
                            }
                        }else{
                            //检测用户是否还有门店账号标识，有则把用户扩展信息离职掉，没有则主账号离职+扩展信息离职
                            if(("1").equals(u.getIsShopAccount())){
                                SysUserExt userExt = u.getSysUserExt();
                                if(userExt !=null){
                                    userExt.setDelFlag("2");
                                    userExt.setDelTime(new Date());
                                    sysUserExtMapper.updateSysUserExt(u.getSysUserExt());
                                }

                            }else{
                                u.setQuit("2");
                                sysUserService.updateUserInfo(u);
                            }
                        }
                    }
                }
            }
        }
        return count;
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer insertUserAndExt(SysUser user) {
        // 新增用户信息
        int rows = sysUserMapper.insertUser(user);

        // 新增用户与角色管理
        sysUserService.insertUserRole(user);
        SysUserExt userExt = user.getSysUserExt();
        userExt.setUserId(user.getUserId());

        int i1 = sysUserExtMapper.insertOrUpSysUserExt(userExt);


        //wxQyUser.setSysUserId(user.getUserId());
//        int i2 =wxQyUserMapper.insertWxQyUser(wxQyUser);
//        if(i1+i2<2){
//            throw new RuntimeException("插入UserExt或WxUser错误");
//        }
        return rows;
    }
}
