package com.dxhy.admin.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.admin.sys.config.AdminConfig;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.admin.sys.entity.*;
import com.dxhy.admin.sys.model.*;
import com.dxhy.admin.sys.service.*;
import com.xxl.sso.core.user.SsoUser;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("ssoLoginService")
@Slf4j
public class SsoLoginServiceImpl implements SsoLoginService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysTabulateService sysTabulateService;
    @Resource
    private SysTabulateDeptService sysTabulateDeptService;
    @Resource
    private SysConfigService sysConfigService;

    @Override
    public boolean saveUser(SsoUser user) {

        if (user.getUserSource() == 1) {

            // 保存 机构信息
            boolean insertOrg = this.insertOrg(user);
            // 保存角色信息
            boolean insertRole = this.insertRole(user);
            // 保存用户信息
            boolean insertUser = this.insertUser(user);

            log.info("insertOrg = {},insertRole={},insertUser",insertOrg,insertRole,insertUser);

            // 刷新用户缓存
            sysUserService.refreshCache(false, user.getUsername());
            return insertOrg && insertUser && insertRole;
        } else {
            return true;
        }

    }

    public boolean insertUser(SsoUser user) {
        try {
            SysUserEntity userEntity = this.toUser(user);
            // 先删除用户信息，在新增
            sysUserService.deleteUserBigb(userEntity.getUserId());
            sysUserService.saveUser(userEntity);
            return true;
        } catch (Exception e) {
            log.error("insertUser 报错信息为{}",e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean insertRole(SsoUser user) {
        try {
            // 判断角色是否存在
            List<SysRoleEntity> roleEntityList = this.toRoleEntity(user.getRoles());
            if (roleEntityList.size() > 0) {
                for (SysRoleEntity sysRoleEntity : roleEntityList) {
                    sysRoleService.deleteBatch(sysRoleEntity.getRoleId());
                    sysRoleService.saveRole(sysRoleEntity);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("insertRole 报错信息为{}",e);
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 保存机构信息
     *
     * @param user
     *            用户信息
     * @return 返回信息
     */
    public boolean insertOrg(SsoUser user) {
        try {
            List<SysDeptEntity> deptList = this.toDept(user);
            if (deptList != null && deptList.size() > 0) {
                sysDeptService.saveDeptList(deptList);
            }
            return true;
        } catch (Exception e) {
            log.error("insertOrg 报错信息为{}",e);
            e.printStackTrace();
            return false;
        }

    }

    public List<SysDeptEntity> toDept(SsoUser user) {
        List<SysDeptEntity> deptList = new ArrayList<>();
        int deptSum = 0;
        SysDeptEntity dept;
        List<com.xxl.sso.core.entity.SysDeptEntity> taxplayercodeDeptList = user.getTaxplayercodeDeptList();
        if (taxplayercodeDeptList != null && taxplayercodeDeptList.size() > 0) {
            for (com.xxl.sso.core.entity.SysDeptEntity entity : taxplayercodeDeptList) {
                dept = new SysDeptEntity();
                dept.setDeptId(entity.getDeptId());
                dept.setParentId(entity.getParentId());
                dept.setTaxno(entity.getTaxpayerCode());
                dept.setTaxname(entity.getName());
                dept.setName(entity.getName());
                dept.setLinkman("");
                dept.setPhone(entity.getTaxpayerPhone());
                dept.setAddress(entity.getTaxpayerAddress());
                dept.setAccount(entity.getTaxpayerAccount());
                dept.setBank(entity.getTaxpayerBank());
                dept.setCompany(AdminConfig.company);
                dept.setOrgCode(entity.getEnterpriseNumbers());
                String deptType = this.toDeptType(String.valueOf(entity.getDeptType()),
                    String.valueOf(entity.getParentId()), entity.getTaxpayerCode());
                dept.setDeptType(deptType);
                dept.setOrgType(this.toOrgType(dept.getDeptType(), String.valueOf(entity.getParentId())));
                dept.setUpgradeStatus(AdminConfig.upgradeStatus);
                // 是否查验 0-- 不查验 1---查验
                dept.setCheckStatus(AdminConfig.checkStatus);
                // 是否采集状态 0 -- 不采集 1--采集
                dept.setCjStatus(AdminConfig.cjStatus);
                // 是否签收认证 0 -- 不签收认证 1 -- 签收认证
                dept.setQsStatus(AdminConfig.qsStatus);
                // 所选数据库名称
                dept.setDbName("business");
                // 兼容大企业平台添加
                dept.setAceKey(AdminConfig.aceKey);
                // 兼容大企业平台添加
                dept.setAceId(AdminConfig.aceId);
                deptList.add(dept);
            }
        }
        return deptList;
    }

    private String toOrgType(String deptType, String parentId) {
        String orgType;
        switch (deptType) {
            case "1":
                // 集团
                orgType = "1";
                break;
            case "2":
                // 子公司 虚拟购方
                orgType = "2";
                break;
            case "3":
                // 分支机构 购方税号
                orgType = "5";
                break;
            case "4":
                // 部门 购方门店
                orgType = "7";
                break;
            // 中心企业
            case "0":
            default:
                orgType = "0";
                break;
        }

        if (SysConfig.PARENT_ID.equals(parentId)) {
            orgType = "1";
        }

        return orgType;
    }

    private String toDeptType(String type, String parentId, String taxno) {
        String deptType;
        switch (type) {
            case "1":
                // 总公司 集团
                deptType = "1";
                break;
            case "2":
            case "3":
                // 子公司 分支机构 存在购方税号
                deptType = "3";
                break;
            case "4":
                // 部门
                // 分支机构 部门
                deptType = "4";
                break;
            case "5":
                // 虚拟机构
                deptType = "2";
                break;
            default:
                deptType = "0";
                break;
        }

        if (SysConfig.PARENT_ID.equals(parentId)) {
            deptType = "1";
        }
        if ("1".equals(deptType) && StringUtils.isNotBlank(taxno)) {
            deptType = "3";
        }
        if (("4".equals(type) || "5".equals(type)) && StringUtils.isNotBlank(taxno)) {
            deptType = "3";
        }
        return deptType;
    }

    public SysUserEntity toUser(SsoUser user) {
        SysUserEntity entity = new SysUserEntity();
        entity.setLoginname(user.getUsername());
        entity.setUserId(user.getUserId());
        entity.setUsername(user.getName());
        entity.setEmail(user.getEmail());
        entity.setMobile(user.getMobile());
        entity.setStatus(user.getStatus());
        entity.setPassword(user.getUsername());
        entity.setPlpassword(user.getUsername());
        entity.setCompany(AdminConfig.company);
        entity.setUserType("1");
        entity.setDeptId(user.getDept().getDeptId());
        entity.setDeptName(user.getDept().getName());
        entity.setUserOrgEntities(this.toUserOrg(user));
        entity.setRoleIdList(this.toRoleId(user));

        return entity;
    }

    public List<Long> toRoleId(SsoUser user) {
        List<Long> roleIds = new ArrayList<>();
        List<com.xxl.sso.core.entity.SysRoleEntity> roles = user.getRoles();
        if (roles.size() > 0) {
            for (com.xxl.sso.core.entity.SysRoleEntity role : roles) {
                roleIds.add(role.getRoleId());
            }
        }
        return roleIds;
    }

//    public List<SysUserOrgEntity> toUserOrg(SsoUser user) {
//        SysUserOrgEntity userOrg;
//        List<SysUserOrgEntity> listUserOrg = new ArrayList<>();
//        List<Long> dataPerm = user.getDataPerm();
//        List<com.xxl.sso.core.entity.SysDeptEntity> taxplayercodeDeptList = user.getTaxplayercodeDeptList();
//        if (dataPerm != null && dataPerm.size() > 0) {
//            for (Long deptId : dataPerm) {
//                if (dataPerm.size() > 0) {
//                    for (com.xxl.sso.core.entity.SysDeptEntity sysDeptEntity : taxplayercodeDeptList) {
//                        log.debug("deptId : " + deptId + "   sysDetp: " + sysDeptEntity.getDeptId());
//                        if (deptId.longValue() == sysDeptEntity.getDeptId().longValue()) {
//                            userOrg = new SysUserOrgEntity();
//                            userOrg.setCompany(AdminConfig.company);
//                            userOrg.setDeptId(sysDeptEntity.getDeptId());
//                            userOrg.setTaxname(sysDeptEntity.getName());
//                            userOrg.setTaxno(sysDeptEntity.getTaxpayerCode());
//                            listUserOrg.add(userOrg);
//                        }
//                    }
//                }
//            }
//        }
//        log.debug("listUserOrg : " + listUserOrg.size() + "   listUserOrgJson: " + JSON.toJSONString(listUserOrg));
//        return listUserOrg;
//    }

    public List<SysUserOrgEntity> toUserOrg(SsoUser user) {
        SysUserOrgEntity userOrg;
        Map<Long, com.xxl.sso.core.entity.SysDeptEntity> detpCollect = null;
        List<SysUserOrgEntity> listUserOrg = new ArrayList<>();
        List<Long> dataPerm = user.getDataPerm();
        List<com.xxl.sso.core.entity.SysDeptEntity> taxplayercodeDeptList = user.getTaxplayercodeDeptList();
        if(taxplayercodeDeptList != null && taxplayercodeDeptList.size() > 0){
            detpCollect = taxplayercodeDeptList.stream().collect(Collectors.toMap(com.xxl.sso.core.entity.SysDeptEntity::getDeptId, tri -> tri));
        }
        if(detpCollect == null){
            return listUserOrg;
        }
        if (dataPerm != null && dataPerm.size() > 0) {

            for (Long deptId : dataPerm) {
                com.xxl.sso.core.entity.SysDeptEntity deptEntity = detpCollect.get(deptId);
                if(deptEntity != null){
                    userOrg = new SysUserOrgEntity();
                    userOrg.setCompany(AdminConfig.company);
                    userOrg.setDeptId(deptEntity.getDeptId());
                    userOrg.setTaxname(deptEntity.getName());
                    userOrg.setTaxno(deptEntity.getTaxpayerCode());
                    listUserOrg.add(userOrg);
                }
            }

        }
        log.info("listUserOrg : " + listUserOrg.size() + "   listUserOrgJson: " + JSON.toJSONString(listUserOrg));
        return listUserOrg;
    }

    public List<SysRoleEntity> toRoleEntity(List<com.xxl.sso.core.entity.SysRoleEntity> ssoRoleList) {
        SysRoleEntity sysRoleEntity;
        List<SysRoleEntity> roleEntityList = new ArrayList<>();
        if (ssoRoleList.size() > 0) {
            for (com.xxl.sso.core.entity.SysRoleEntity ssoRoleEntity : ssoRoleList) {
                sysRoleEntity = new SysRoleEntity();
                sysRoleEntity.setCompany(AdminConfig.company);
                sysRoleEntity.setDeptId(ssoRoleEntity.getDeptId());
                sysRoleEntity.setRoleId(ssoRoleEntity.getRoleId());
                sysRoleEntity.setRoleName(ssoRoleEntity.getRoleName());
                sysRoleEntity.setCreateTime(ssoRoleEntity.getCreateTime());
                sysRoleEntity.setUpdateTime(DateUtil.date());
                sysRoleEntity.setMenuIdList(this.toMenuId(ssoRoleEntity.getRoleId()));
                roleEntityList.add(sysRoleEntity);
            }
        }
        return roleEntityList;
    }

    public List<Long> toMenuId(long roleId) {
        List<String> roleIds = new ArrayList<>();
        roleIds.add(String.valueOf(roleId));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("systemSign", "");
        jsonObject.put("roleIds", roleIds);
        log.info("获取角色请求参数：{} , 请求地址：{}", jsonObject.toString(), AdminConfig.queryRoleUrl);
        String post = HttpUtil.post(AdminConfig.queryRoleUrl, jsonObject.toString(), 30000);
        log.info("获取角色返回信息：{}", post);
        if (StringUtils.isNotBlank(post)) {
            SsoReturnModel ssoReturnModel = JSON.parseObject(post, SsoReturnModel.class);
            if ("0000".equals(ssoReturnModel.getCode())) {
                List<SysRoleModel> data = ssoReturnModel.getData();
                List<Long> menus = data.get(0).getMenus();
                if (menus.size() > 0) {
                    menus.addAll(sysMenuService.queryIdList(menus));
                    return menus;
                }
            }
        }
        return null;
    }

    public List<SysMenuEntity> toMenu(SsoUser user) {
        SysMenuEntity sysMenuEntity;
        List<SysMenuEntity> menuList = new ArrayList<>();
        List<com.xxl.sso.core.entity.SysMenuEntity> menus = user.getMenus();
        for (com.xxl.sso.core.entity.SysMenuEntity sysMenu : menus) {
            sysMenuEntity = new SysMenuEntity();
            String systemSign = sysMenu.getSystemSign();
            if ("JXXT".equals(systemSign) || "QYPC".equals(systemSign) || "GYL".equals(systemSign)
                || "YWXT".equals(systemSign)) {
                if (StringUtils.isNotBlank(sysMenu.getUrl()) && StringUtils.isNotBlank(sysMenu.getName())) {
                    sysMenuEntity.setMenuId(sysMenu.getMenuId());
                    sysMenuEntity.setParentId(sysMenu.getParentId());
                    sysMenuEntity.setOrderNum(sysMenu.getOrderNum());
                    sysMenuEntity.setName(sysMenu.getName());
                    sysMenuEntity.setType(sysMenu.getType());
                    sysMenuEntity.setSystemCode(sysMenu.getSystemSign());
                    if (3 == sysMenu.getType()) {
                        sysMenuEntity.setComponent("");
                        sysMenuEntity.setIcon("");
                        sysMenuEntity.setNoCache(true);
                        sysMenuEntity.setUrl(sysMenu.getUrl());
                    } else if (0 == sysMenu.getType()) {
                        sysMenuEntity.setUrl("/");
                        sysMenuEntity.setNoCache(true);
                        sysMenuEntity.setComponent("");
                        if ("JXXT".equals(sysMenuEntity.getSystemCode())) {
                            sysMenuEntity.setIcon("icon_jxpt");
                        } else if ("QYPC".equals(sysMenuEntity.getSystemCode())) {
                            sysMenuEntity.setIcon("icon_qypc");
                        } else if ("GYL".equals(sysMenuEntity.getSystemCode())) {
                            sysMenuEntity.setIcon("icon_gyl");
                        } else if ("YWXT".equals(sysMenuEntity.getSystemCode())) {
                            sysMenuEntity.setIcon("icon_gyl");
                        }
                    } else if (1 == sysMenu.getType() || 2 == sysMenu.getType()) {
                        String[] split = sysMenu.getUrl().split("/");
                        SysMenuEntity menu =
                            this.queryMenu("/" + split[split.length - 1], sysMenu.getType(), sysMenu.getSystemSign());
                        if (menu != null) {
                            sysMenuEntity.setComponent(menu.getComponent());
                            sysMenuEntity.setIcon(menu.getIcon());
                            sysMenuEntity.setNoCache(menu.isNoCache());
                            sysMenuEntity.setSystemCode(menu.getSystemCode());
                            sysMenuEntity.setUrl(menu.getUrl());
                            sysMenuEntity.setBtnRuleFlag(menu.isBtnRuleFlag());
                            sysMenuEntity.setQueryRuleFlag(menu.isQueryRuleFlag());
                            if (menu.getType() == 2) {
                                sysMenuEntity.setModelMenuId(menu.getMenuId());
                                List<SysMenuEntity> queryList = sysMenuService.getQueryList(menu.getMenuId(), 4);
                                for (SysMenuEntity menuEntity : queryList) {
                                    menuEntity.setParentId(sysMenuEntity.getMenuId());
                                }
                                if (queryList.size() > 0) {
                                    menuList.addAll(queryList);
                                }
                            }
                        } else {
                            sysMenuEntity = new SysMenuEntity();
                        }

                    }
                    if (StringUtils.isNotBlank(sysMenuEntity.getName())) {
                        menuList.add(sysMenuEntity);
                    }
                }
            }

        }
        return menuList;
    }

    public SysMenuEntity queryMenu(String url, int type, String systemCode) {
        return sysMenuService.queryMenuType(url, type, systemCode);
    }

    @Override
    public void saveMenu() {
        log.info("根据UserID 1 获取 信息，保存所有菜单");
        try {
            List<TabulateMenuModel> menuModels = null;
            TabulateMenuModel tabulateMenuModel;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("systemSign", "");
            jsonObject.put("password", "");
            jsonObject.put("userId", "1");
            jsonObject.put("username", "");
            log.info("获取菜单请求参数：{} ，地址：{}", jsonObject.toString(), AdminConfig.queryUserUrl);
            String post = HttpUtil.post(AdminConfig.queryUserUrl, jsonObject.toString(), 300000);
            log.info("获取菜单信息返回：{}", post);
            if (StringUtils.isNotBlank(post)) {
                jsonObject = JSONObject.parseObject(post);
                SsoReturnUserModel ssoReturnUserModel = new SsoReturnUserModel();
                ssoReturnUserModel.setCode(jsonObject.getString("code"));
                ssoReturnUserModel.setMessage(jsonObject.getString("message"));
                ssoReturnUserModel.setData(JSON.parseObject(jsonObject.getString("data"), SsoUser.class));
                //SsoReturnUserModel ssoReturnUserModel = JSON.parseObject(post, SsoReturnUserModel.class);
                if ("0000".equals(ssoReturnUserModel.getCode())) {
                    List<SysMenuEntity> sysMenuEntities = this.toMenu(ssoReturnUserModel.getData());

                    log.info("菜单信息数量：{}", sysMenuEntities.size());
                    if (sysMenuEntities.size() > 0) {
                        sysMenuService.saveMenuBatch(sysMenuEntities);
                        // 保存菜单与显示列表对应关系,更新显示列表id
                        menuModels = new ArrayList<>();
                        for (SysMenuEntity menuEntity : sysMenuEntities) {
                            if (2 == menuEntity.getType()) {
                                tabulateMenuModel = new TabulateMenuModel();
                                tabulateMenuModel.setModelMenuId(menuEntity.getModelMenuId());
                                tabulateMenuModel.setMenuId(menuEntity.getMenuId());
                                menuModels.add(tabulateMenuModel);
                            }
                        }
                    }

                }
            }
            if (menuModels != null && menuModels.size() > 0) {
                // 更新显示列表ID
                sysTabulateService.updateTabulateMenuId(menuModels);
                // 刷新中心企业缓存
                sysTabulateDeptService.refreshCache(SysConfig.ZXQY);
            }
            // if (menuIdList != null && menuIdList.size() > 0) {
            // // 保存显示列表权限
            // sysTabulateDeptService.saveListTablate(menuIdList, AdminConfig.company);
            // // 刷新显示列表缓存
            // sysTabulateDeptService.refreshCache(AdminConfig.company);
            // }
            log.info("根据UserID 1 获取 信息，保存所有菜单成功");

        } catch (Exception e) {
            log.info("根据UserID 1 获取 信息，保存所有菜单异常：{}", e.getMessage());
            e.printStackTrace();
        }

    }

    @Override
    public Map<String, String> setTokenUser(String token) {
        Map<String, String> runMap = null;
        SysConfigEntity sysConfigEntity = sysConfigService.queryCode("KEY_YHZX");

        if (sysConfigEntity == null) {
            runMap = new HashMap<>();
            runMap.put("code", "1");
            runMap.put("msg", "获取配置信息失败");
            runMap.put("loginOuturl", AdminConfig.loginOutUrl);
            runMap.put("userName", "");
            return runMap;
        }
        AdminSsoConfigModel adminSsoConfigModel =
            JSON.parseObject(sysConfigEntity.getParamValue(), AdminSsoConfigModel.class);
        String body = HttpRequest.post(adminSsoConfigModel.getQueryUserUrl()).header("token", token).execute().body();
        log.info("获取用户信息：{}", body);
        SsoUserReModel ssoUserReModel = JSON.parseObject(body, SsoUserReModel.class);
        if ("0000".equals(ssoUserReModel.getCode())) {
            // 保存 机构信息
            SsoUserDataModel ssoUserDataModel = JSON.parseObject(ssoUserReModel.getData(), SsoUserDataModel.class);
            boolean b = this.insertTokenOrg(ssoUserDataModel, adminSsoConfigModel);
            if (b) {
                // 保存用户信息
                boolean tokenUser = this.insertTokenUser(ssoUserDataModel, adminSsoConfigModel);
                if (tokenUser) {

                    runMap = new HashMap<>();
                    runMap.put("code", "0");
                    runMap.put("loginOuturl", adminSsoConfigModel.getLoginOutUrl());
                    runMap.put("userName", ssoUserDataModel.getUsername());
                    runMap.put("msg", "保存用户信息成功");
                    return runMap;
                } else {
                    sysUserService.refreshCache(false, ssoUserDataModel.getUsername());
                    runMap = new HashMap<>();
                    runMap.put("code", "0");
                    runMap.put("msg", "保存用户信息失败");
                    runMap.put("loginOuturl", adminSsoConfigModel.getLoginOutUrl());
                    runMap.put("userName", "");
                    return runMap;
                }

            } else {
                runMap = new HashMap<>();
                runMap.put("code", "1");
                runMap.put("msg", "保存机构信息失败");
                runMap.put("loginOuturl", adminSsoConfigModel.getLoginOutUrl());
                runMap.put("userName", "");

                return runMap;
            }

        } else {
            runMap = new HashMap<>();
            runMap.put("code", ssoUserReModel.getCode());
            runMap.put("msg", ssoUserReModel.getMessage());
            runMap.put("loginOuturl", adminSsoConfigModel.getLoginOutUrl());
            runMap.put("userName", "");

            return runMap;
        }
    }

    public List<SysDeptEntity> toTokenDept(SsoUserDataModel user, AdminSsoConfigModel configModel) {
        List<SysDeptEntity> deptList = new ArrayList<>();
        SysDeptEntity dept;
        Map<String, SysDeptEntity> collect = null;
        List<SsoUserTaxplayercodeDept> taxplayercodeDeptList = user.getTaxplayercodeDeptList();
        if (taxplayercodeDeptList != null && taxplayercodeDeptList.size() > 0) {
            List<SysDeptEntity> sysDeptEntities = sysDeptService.queryDeptParentId(configModel.getParentId());
            if (sysDeptEntities.size() > 0) {
                collect = sysDeptEntities.stream().collect(Collectors.toMap(SysDeptEntity::getTaxno, tri -> tri));
            }
            for (SsoUserTaxplayercodeDept entity : taxplayercodeDeptList) {
                if (StringUtils.isNotBlank(entity.getTaxpayerCode())) {
                    if (sysDeptEntities.size() > 0 && collect != null) {
                        SysDeptEntity deptEntity = collect.get(entity.getTaxpayerCode());
                        if (deptEntity == null) {
                            deptList.add(this.toDeptEntity(entity, configModel));
                        } else {
                            if (!deptEntity.getTaxname().equals(entity.getName())) {
                                deptEntity.setTaxname(entity.getName());
                                deptList.add(deptEntity);
                            }
                        }

                    } else {
                        deptList.add(this.toDeptEntity(entity, configModel));
                    }
                }
            }
        }
        return deptList;
    }

    public SysDeptEntity toDeptEntity(SsoUserTaxplayercodeDept entity, AdminSsoConfigModel configModel) {
        SysDeptEntity dept = new SysDeptEntity();
        dept.setParentId(configModel.getParentId());
        dept.setTaxno(entity.getTaxpayerCode());
        dept.setTaxname(entity.getName());
        dept.setName(entity.getName());
        dept.setLinkman("");
        dept.setPhone(entity.getTaxpayerPhone());
        dept.setAddress(entity.getTaxpayerAddress());
        dept.setAccount(entity.getTaxpayerAccount());
        dept.setBank(entity.getTaxpayerBank());
        dept.setCompany(configModel.getCompany());
        dept.setOrgCode(entity.getEnterpriseNumbers());
        dept.setDeptType(SysConfig.DeptType.DEPT_TYPE_3.getCode());
        dept.setOrgType(SysConfig.OrgType.ORG_TYPE_5.getCode());
        dept.setUpgradeStatus(AdminConfig.upgradeStatus);
        // 是否查验 0-- 不查验 1---查验
        dept.setCheckStatus(AdminConfig.checkStatus);
        // 是否采集状态 0 -- 不采集 1--采集
        dept.setCjStatus(AdminConfig.cjStatus);
        // 是否签收认证 0 -- 不签收认证 1 -- 签收认证
        dept.setQsStatus(AdminConfig.qsStatus);
        // 所选数据库名称
        dept.setDbName("business");
        // 兼容大企业平台添加
        dept.setAceKey(AdminConfig.aceKey);
        // 兼容大企业平台添加
        dept.setAceId(AdminConfig.aceId);
        return dept;
    }

    public SysUserEntity toTokenUser(SsoUserDataModel user, AdminSsoConfigModel configModel) {
        SysUserEntity entity = new SysUserEntity();
        entity.setLoginname(user.getUsername());
        entity.setUserId(user.getUserId());
        entity.setUsername(user.getName());
        entity.setEmail(user.getEmail());
        entity.setMobile(user.getPhone());
        entity.setStatus(Integer.parseInt(user.getStatus()));
        entity.setPassword(user.getUsername());
        entity.setPlpassword(user.getUsername());
        entity.setCompany(configModel.getCompany());
        entity.setUserType("1");
        entity.setDeptId(configModel.getDeptId());
        entity.setDeptName(user.getDept().getName());
        entity.setUserOrgEntities(this.toTokenUserOrg(user.getTaxplayercodeDeptList(), configModel));
        entity.setRoleIdList(this.toTokenRoleId(configModel));

        return entity;
    }

    public List<SysUserOrgEntity> toTokenUserOrg(List<SsoUserTaxplayercodeDept> dept, AdminSsoConfigModel configModel) {
        SysUserOrgEntity userOrg;
        List<SysUserOrgEntity> listUserOrg = new ArrayList<>();
        for (SsoUserTaxplayercodeDept sysDeptEntity : dept) {
            // 获取税号信息
            SysDeptEntity deptEntity =
                sysDeptService.queryDeptTaxno(configModel.getCompany(), sysDeptEntity.getTaxpayerCode());
            if (deptEntity != null) {
                userOrg = new SysUserOrgEntity();
                userOrg.setCompany(configModel.getCompany());
                userOrg.setDeptId(deptEntity.getDeptId());
                userOrg.setTaxname(sysDeptEntity.getName());
                userOrg.setTaxno(sysDeptEntity.getTaxpayerCode());
                listUserOrg.add(userOrg);
            }

        }

        log.debug("listUserOrg : " + listUserOrg.size() + "   listUserOrgJson: " + JSON.toJSONString(listUserOrg));
        return listUserOrg;
    }

    public List<Long> toTokenRoleId(AdminSsoConfigModel configModel) {
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(configModel.roleId);
        return roleIds;
    }

    public boolean insertTokenUser(SsoUserDataModel user, AdminSsoConfigModel configModel) {
        try {
            SysUserEntity userEntity = this.toTokenUser(user, configModel);
            sysUserService.saveUser(userEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 保存机构信息
     *
     * @param user
     *            用户信息
     * @return 返回信息
     */
    public boolean insertTokenOrg(SsoUserDataModel user, AdminSsoConfigModel configModel) {
        try {
            List<SysDeptEntity> deptList = this.toTokenDept(user, configModel);
            if (deptList != null && deptList.size() > 0) {
                sysDeptService.saveDeptList(deptList);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
