package com.dgtly.system.service.impl;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.utils.ShiroSaltUtil;
import com.dgtly.common.utils.http.HttpUtils;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.system.domain.*;
import com.dgtly.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dgtly.common.annotation.DataScope;
import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.text.Convert;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.security.Md5Utils;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author dgtly
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysConfigService configService;


    @Autowired
    private SysUserExtMapper userExtMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserExtMapper sysUserExtMapper;

    @Autowired
    private SysUserShopExtMapper userShopExtMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Value(value = "${spring.esb.esbShopStoneLikePaintUser}")
    private String esbShopStoneLikePaintUserUrl;

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

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



    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByLoginName(String userName)
    {
        return userMapper.selectUserByLoginName(userName);
    }


    @Override
    public List<String> selectUserByIsManager(Integer isCustomerManager) {
        return userMapper.selectUserByIsManager(isCustomerManager);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhoneNumber(String phoneNumber)
    {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByEmail(String email)
    {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids) throws BusinessException
    {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 插入用户信息和销售扩展信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public Integer insertUserAndSalesExt(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        SysUserExt userExt = user.getSysUserExt();
        userExt.setUserId(user.getUserId());
        userExtMapper.insertOrUpSysUserExt(userExt);
        return rows;
    }




    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    @Override
    public int updateIsAuthentication(String isAuthentication,String accountId) {
        return userMapper.updateIsAuthentication(isAuthentication,accountId);
    }

    /**
     * 修改用户个人详细信息和销售销售相关信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUserInfoAndSalesExt(SysUser user) {
        // 删除用户与角色关联
        SysUser u =  userMapper.selectUserByLoginName(user.getLoginName());
        SysUserExt userExt = user.getSysUserExt();
        /*判断同步标识is_sync=1不需要同步*/
        if("1".equals(u.getIsSync())){
            return 1;
        }
        if(userExt!=null){
            userExt.setUserId(u.getUserId());
            userExtMapper.insertOrUpSysUserExt(userExt);
        }
        return userMapper.updateUserByLoginName(user);
    }

    /**
     * 修改公司员工状态
     *
     * @return 结果
     */
    @Override
    public int changeStatus(Long companyId,Integer status)
    {
        return userMapper.changeStatus(companyId,status);
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(SysUser user)
    {
        return updateUserInfo(user);
    }

    /**
     * @description: 新增单用户用户id和角色
     * @param: [user]
     * @return: void
     * @author: njs
     * @date: 2025/8/21 10:12
     */
    public void insertShopUserRole(SysUser user)
    {

        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(user.getUserId());
        ur.setRoleId(user.getRoleId());
        if(user.getShopType() != null){
            ur.setShopType(user.getShopType());
        }
        list.add(ur);
        if (list.size() > 0) {
            userRoleMapper.batchUserRole(list);
        }

    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                SysRole sysRole =  roleMapper.selectRoleById(ur.getRoleId());
                if (sysRole != null){
                    if (Arrays.asList(paintRoleKeys).contains(sysRole.getRoleKey())){
                        ur.setShopType("0");
                    }
                    if (Arrays.asList(goldPoleKeys).contains(sysRole.getRoleKey())){
                        ur.setShopType("1");
                    }
                }
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 校验登录名称是否唯一
     *
     * @param loginName 用户名
     * @return
     */
    @Override
    public String checkLoginNameUnique(String loginName)
    {
        int count = userMapper.checkLoginNameUnique(loginName);
        if (count > 0)
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber(),null);//整个系统中手机号必须唯一
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail(),user.getCompanyId());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId())&&user.isAdmin())
        {
//            user = userMapper.selectUserById(user.getUserId());
//            List<SysRole> roles =  user.getRoles();
//            for(SysRole role:roles){
//                if(role.getRoleKey().equals("admin")){
            throw new BusinessException("不允许操作超级管理员用户");
//                }
//            }

        }
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId)
    {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId)
    {
        List<SysPost> list = postMapper.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName,Long companyId)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {

                if(user.getCompanyId()==null){
                    user.setCompanyId(companyId);
                }
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
                if (StringUtils.isNull(u))
                {
                    SysUser sysUser = userMapper.selectUserById(user.getUserId());
                    if(StringUtils.isNull(sysUser)){
                        user.setPassword(Md5Utils.hash(user.getLoginName() + password));
                        user.setCreateBy(operName);
                        this.insertUser(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                    }else{
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、用户序号 " + user.getUserId() + " 已存在");
                    }
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }




            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 用户状态修改
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }




    /**
     * 查询所有用户LoginName
     *
     * @return 用户信息集合信息
     */
    @Override
    public Set<String> selectAllUserLoginName() {
        return userMapper.selectAllUserLoginName();
    }

    @Override
    public Set<String> selectDiyUserLoginName() {
        return userMapper.selectDiyUserLoginName();
    }

    /**
     * 根据立邦员工id查找用户
     *
     * @param emplyeeId 立邦员工id
     * @return 结果
     */
    @Override
    public SysUser selectUserByEmplyeeId(String emplyeeId) {
        return  userMapper.selectUserByEmplyeeId(emplyeeId);
    }

    /**
     * 根据销售组织代码 获取所属的用户登陆名称
     *
     * @param customerCodes 经销商列表
     * @return 结果
     */
    @Override
    public Map<String,Map<String,Object>> selectLoginNamesByCostumerCode(Set<String> customerCodes) {
        String[] a = new String[customerCodes.size()];
        a = customerCodes.toArray(a);
        return userMapper.selectLoginNamesByCostumerCode(a);

    }

    @Override
    public Map<String, Map<String, Object>> selectLoginNamesByCostumerVoCode(Collection<CustomerModelVO> customerCodes) {
        Map<String,Map<String,Object>> map=new HashMap<>();
        Iterator<CustomerModelVO> it = customerCodes.iterator();
        while (it.hasNext()) {
            CustomerModelVO entry = it.next();
            Map<String,Map<String,Object>> customermap=new HashMap<>();
            customermap=userMapper.selectLoginNamesByCustomerModelVO(entry.getCustomerId(),entry.getCustomerType());
            map.putAll(customermap);
        }
        return map;
    }

    @Override
    public Map<String, Map<String, Object>> selectLoginNamesByEmployeeCode(Set<String> employeeSet) {
        String[] a = new String[employeeSet.size()];
        a = employeeSet.toArray(a);
        return userMapper.selectLoginNamesByEmployeeCode(a);
    }


    @Override
    public int insertPersonalAccount(SysUser user) {
        return userMapper.updateUser(user);
    }
    /**
     * @description: 根据经销商code查询经销人员列表
     * @param: [orgCode]
     * @return: void
     * @author: qxm
     * @date: 2020/10/19 14:36
     */
    @Override
    public List<SysUser> selectUserByOrgCode(String orgCode) {
        return userMapper.selectUserByOrgCode(orgCode);
    }

    @Override
    public String getCustomNameByCode(String code) {
        return userMapper.getCustomNameByCode(code);
    }

    @Override
    public String selectSyncDateUser(Integer type) {
        return userMapper.selectSyncDateUser(type);
    }

    @Override
    public void insertUserRole(Long userId, Long roleId) {
        userMapper.insertUserRole(userId, roleId);
    }

    @Override
    public void deleteByLoginName(String loginName) {
        userMapper.deleteByLoginName(loginName);
    }

    @Override
    public int deleteUserByLoginName(String loginName) {
        return userMapper.deleteUserByLoginName(loginName);
    }

    @Override
    public Boolean buildStoneLikePaintByQwData(JSONObject json) {
        Long roleId = roleMapper.selectRoleIdByRoleKey("shopStoneLikePaint");
        //0TUC仿石漆服务商人员
        Boolean i = buildShopUser(json,"0",roleId);

        return  i;
    }

    public Boolean buildShopUser(JSONObject jsonObject, String usertype, Long roleId){
        JSONObject jo =jsonObject;
        Set<String> loginNameSet = sysUserService.selectAllUserLoginName();
        loginNameSet = loginNameSet.stream().map(String::toUpperCase).collect(Collectors.toSet());
        try {
            String userName = jo.getString("staff_name");
            String userPhone = jo.getString("staff_mobile");
            //是否同步企业微信
            Boolean isSync = jo.getBoolean("is_synced_to_wecom");
            //是否有效用户
            Boolean isActive = jo.getBoolean("is_active");
            String subOfficeCode = jo.getString("office_code");
            String subOfficeName = jo.getString("office_name");
            String shopCode = jo.getString("organization_code");
            String shopName = jo.getString("organization_name");
            String userIdWork = jo.getString("wecom_userid") == null ? "" : jo.getString("wecom_userid");
            String dataUpdateTime = jo.getString("update_datetime");
            String dataUserId = jo.getString("id");
            String customerCode = jo.getString("distributor_code");
            String customerName = jo.getString("distributor_name");
            /*人员信息是否有效，true有效，false无效。是否同步到企微 */
            String loginName ="";
            if(isActive && isSync){
                loginName = jo.getString("wecom_userid");
            }else{
                //先判断该用户是否存在在处理离职和去掉角色，否则直接跳出循环不处理
                //离职掉该门店和用户关联关系
                if(!isActive){
                    //用户无效后接口获取不到企微id,需从关联表查询
                    loginName = userShopExtMapper.selectLoginNameByUserId(dataUserId,shopCode,usertype);
                    if(loginName !=null && !loginName.isEmpty()){
                        //查询用户信息
                        SysUser user = sysUserMapper.selectUserByLoginName(loginName);
                        userShopExtMapper.deleteUserShopExt(user.getUserId().toString(),loginName,shopCode,usertype);
                        //去掉该用户和角色的关联关系
                        userRoleMapper.deleteUserRoleByUserIdAndExt(user.getUserId(),roleId,usertype);
                        //离职处理以及用户主信息是否有门店账号处理需要添加
                        //查询门店用户表是否存在用户和其他门店的关联关系，如果存在就不离职，不存在查询是否有经销商的关联关系，如果存在就不离职，不存在就离职
                        SysUserShopExt shop = new SysUserShopExt();
                        shop.setUserId(user.getUserId().toString());
                        shop.setDelFlag("0");
                        List<SysUserShopExt>  shopExtList = userShopExtMapper.selectSysUserShopExtList(shop);
                        if(shopExtList == null || shopExtList.size() == 0){
                            //在查用户经销商扩展信息
                            SysUserExt userCustomerExt = sysUserExtMapper.selectSysUserExtById(user.getUserId());
                            user.setIsShopAccount("0");
                            if(userCustomerExt == null){
                                //离职处理2
                                user.setQuit("2");
                            }
                            //修改用户信息
                            sysUserMapper.updateUser(user);

                        }
                    }
                }
                return true;
            }
            //先建店
            Map<String, Object> params = new HashMap<>();
            Map<String,String> urlMap = new HashMap<>();
            urlMap.put("userid","ERP");
            List<SysDictData>  sysDictData = sysDictDataMapper.selectDictDataByType("sys_system_bmd_name");
            log.info("获取非bmd的机构:{}", JSON.toJSON(sysDictData));
            boolean isBmd = false;
            for (SysDictData sysDictData1 : sysDictData) {
                if(sysDictData1.getDictLabel().equals(subOfficeName)){
                    isBmd = true;
                }
            }
            if (subOfficeName != null && subOfficeName.startsWith("BMD")){
                if (isBmd){
                    //非bmd token 死值
                    String dorderToken="80027CC7791640CDBAE4D8F0E587985F";
                    urlMap.put("token",dorderToken);
                }else {
                    //bmd token死值
                    String bmdToken="575A4BE6-FCD8-485D-98E0-E51592058AB7";
                    urlMap.put("token",bmdToken);
                }
            }else{
                //非bmd token 死值
                String dorderToken="80027CC7791640CDBAE4D8F0E587985F";
                urlMap.put("token",dorderToken);
            }
            urlMap.put("if","IF_NP_SHOP");
            urlMap.put("callmethod","ADD_FSQ");
            params.put("url", urlMap);
            Map<String,Object> bodyMap = new HashMap<>();
            bodyMap.put("MainCustomerCode",customerCode);
            bodyMap.put("MainCustomerName",customerName);
            bodyMap.put("OfficeCode",subOfficeCode);
            bodyMap.put("OfficeName",subOfficeName);
            bodyMap.put("ShopCode_Pre",shopCode);
            bodyMap.put("ShopCode",shopCode);
            bodyMap.put("ShopLinkman",userName);
            bodyMap.put("ShopName",shopName);
            bodyMap.put("ShopPhone",userPhone);
            bodyMap.put("ShopTypeName","FSQ");
            bodyMap.put("USERID_WORK",userIdWork);
            params.put("body", bodyMap);
            log.info("建店请求报文:{}",bodyMap);
            Map<String, String> headers = new HashMap<String, String>(2);
            String uuidStr = UUID.randomUUID().toString();
            headers.put("Content-Type","application/json");
            headers.put("requestId",uuidStr);
            headers.put("trackId",uuidStr);
            headers.put("sourceSystem","SSB");

            try{
                if (subOfficeName != null && subOfficeName.startsWith("BMD")) {
                    if (isBmd){
                        //非bmd
                        headers.put("serviceName","S_XXX_BMDOMS_DORDERNewStore_S");
                        log.info("非bmd请求报文:{}",params);
                        HttpUtils.sendJsonPostWithHeaders(esbShopStoneLikePaintUserUrl,headers,params);
                    }else {
                        // subOfficeName 以 "BMD" 开头的处理逻辑
                        //bmd
                        log.info("bmd请求报文:{}",params);
                        headers.put("serviceName","S_XXX_BMDOMS_BMDNewStore_S");
                        HttpUtils.sendJsonPostWithHeaders(esbShopStoneLikePaintUserUrl,headers,params);
                    }
                }else{
                    log.info("非bmd请求报文:{}",params);
                    //非bmd
                    headers.put("serviceName","S_XXX_BMDOMS_DORDERNewStore_S");
                    HttpUtils.sendJsonPostWithHeaders(esbShopStoneLikePaintUserUrl,headers,params);
                }
            }catch (Exception e){
                log.error("服务商调用建店异常"+jsonObject,e);
            }


            if (!loginNameSet.contains(loginName.toUpperCase().trim())) {

                /** =============用户基本信息构建 start===============*/
                SysUser user = new SysUser();
                user.setLoginName(loginName);
                log.info("门店新用户"+loginName +"门店类型身份"+usertype);
                user.setUserName(userName);
                user.setPhonenumber(userPhone);
                user.setPassword(loginName);
                user.setSalt(ShiroSaltUtil.randomSalt());
                user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                user.setIsShopAccount("1");
                user.setRoleId(roleId);
                /** =============用户基本信息构建 end===============*/
                SysUser userVoExt = insertUserAndExt(user);
                log.info("用户新增成功"+user);
                // 新增用户与角色管理
                user.setUserId(userVoExt.getUserId());
                user.setShopType(usertype);
                sysUserService.insertShopUserRole(user);
                /**======== 构建门店用户扩展信息表 start===============*/
                SysUserShopExt shopExt = new SysUserShopExt();
                shopExt.setLoginName(loginName);
                shopExt.setShopCode(shopCode);
                shopExt.setShopName(shopName);
                shopExt.setSubofficeCode(subOfficeCode);
                shopExt.setSubofficeName(subOfficeName);
                shopExt.setIsShopType(usertype);
                shopExt.setUserUpdateTime(dataUpdateTime);
                shopExt.setDelFlag("0");
                shopExt.setConstraintUserId(dataUserId);
                //用户id
                shopExt.setUserId(userVoExt.getUserId().toString());
                userShopExtMapper.insertSysUserShopExt(shopExt);
                loginNameSet.add(loginName);
                return true;
            } else {
                /*已经存在的，需增加用户标识,然后增加门店用户扩展信息*/
                SysUser user = sysUserMapper.selectUserByLoginName(loginName);
                user.setPhonenumber(userPhone);
                //允许同步自动用户
                if (("0").equals(user.getIsSync())) {
                    //查询该用户是否存在该接口返回中
                    user.setPhonenumber(userPhone);
                    user.setUserName(userName);
                    user.setIsShopAccount("1");
                    sysUserService.updateUserInfo(user);

                    /**======== 构建门店用户扩展信息表 start===============*/
                    //先删除用户门店扩展表，再插入
                    userShopExtMapper.deletePhysicsUserShopExt(user.getUserId().toString(),loginName,shopCode,usertype);
                    SysUserShopExt shopExt = new SysUserShopExt();
                    shopExt.setLoginName(loginName);
                    shopExt.setShopCode(shopCode);
                    shopExt.setShopName(shopName);
                    shopExt.setSubofficeCode(subOfficeCode);
                    shopExt.setSubofficeName(subOfficeName);
                    shopExt.setIsShopType(usertype);
                    shopExt.setUserUpdateTime(dataUpdateTime);
                    shopExt.setDelFlag("0");
                    shopExt.setConstraintUserId(dataUserId);
                    //用户id
                    shopExt.setUserId(user.getUserId().toString());
                    userShopExtMapper.insertSysUserShopExt(shopExt);
                    //去掉该用户和角色的关联关系
                    userRoleMapper.deleteUserRoleByUserIdAndExt(user.getUserId(),roleId,usertype);
                    user.setRoleId(roleId);
                    user.setUserId(user.getUserId());
                    user.setShopType(usertype);
                    sysUserService.insertShopUserRole(user);

                }
                return true;
            }
        }catch (Exception e){
            log.error("门店用户数据分析异常"+e.getMessage());

        }

        return false;
    }




    public SysUser insertUserAndExt(SysUser user) {
        // 新增用户信息
        sysUserMapper.insertUser(user);

        return user;
    }
}
