package com.zfire.mall.manager.logic.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.SVerification;
import com.zfire.mall.manager.bean.admin.AdminModuleTree;
import com.zfire.mall.manager.bean.admin.AdminUserBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.admin.reqDto.AdminUserAddReqBean;
import com.zfire.mall.manager.bean.admin.respDto.AdminUserDto;
import com.zfire.mall.manager.bean.k3.K3CustomerBean;
import com.zfire.mall.manager.commonmapper.AdminMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.CuseromtTypeEnum;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.JiaXianStockEnum;
import com.zfire.mall.manager.enums.SMSTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.common.SMSLogic;
import com.zfire.mall.manager.logic.external.ExternalEnginLogic;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.JiaSMUtil;
import com.zfire.mall.manager.utils.JwtUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminUserLogic {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    ExternalEnginLogic externalEnginLogic;
    @Autowired
    AdminWebsitLogic adminWebsitLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    K3CustomerLogic k3CustomerLogic;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    AdminModuleService adminModuleService;
    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    AdminUserModuleRelaService adminUserModuleRelaService;
    @Autowired
    AdminCompanyService adminCompanyService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    SMSLogic smsLogic;

    @Autowired
    AdminUserStockService adminUserStockService;
    @Resource
    AdminUserBindEnginService adminUserBindEnginService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    StockCorrespondService stockCorrespondService;
    @Autowired
    AdminUserCategoryRelaService adminUserCategoryRelaService;
    @Autowired
    KingDeeCategoryService kingDeeCategoryService;

    @Autowired
    CustomerBillLimitConfigService customerBillLimitConfigService;

    @Autowired
    CustomerProductTypeRelaService customerProductTypeRelaService;

    @Autowired
    TradeLoginOrderService tradeLoginOrderService;


    /**
     * 验证码
     */
    public SVerification defaultKaptcha() throws IOException {
        // 生成文字验证码
        String text = defaultKaptcha.createText();

        // 生成图片验证码
        ByteArrayOutputStream outputStream = null;
        BufferedImage image = defaultKaptcha.createImage(text);
        outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        byte b[] = outputStream.toByteArray();//从流中获取数据数组。
//        String baseStr = new BASE64Encoder().encode(b);
        String baseStr = Base64.getEncoder().encodeToString(b);
        //生成一个token
        String code = UUID.randomUUID().toString();
        redisUtil.set(Constant.RedisPrefix.VERIFICATION + code, text, 2 * 60);
        SVerification verification = new SVerification();
        verification.setCode(code);
        verification.setPic(baseStr);
        return verification;
    }

    /**
     * 登录
     */
    @Transactional(rollbackFor = Exception.class)
    public AdminUserBean login(String userName, String password, String code, String codeValue,String smsCode,String loginType,HttpServletRequest request) throws RemoteServiceException, ParseException {
        String value = (String) redisUtil.get(Constant.RedisPrefix.VERIFICATION + code);
        if (Constant.LOGIN_TYPE_ACCOUNT.equals(loginType) && (value == null || !value.toLowerCase().equals(codeValue.toLowerCase()))) {
            throw new RemoteServiceException("验证码错误");
        }

        AdminUser adminUser ;
        if(loginType != null && loginType.equals(Constant.LOGIN_TYPE_MOBILE)){
            Object validMessageCode = redisUtil.get(Constant.RedisPrefix.LOGIN_MOBILE_SMS + userName);
            if (!smsCode.equals(validMessageCode.toString())){
                throw new RemoteServiceException("短信验证码输入错误");
            }
            redisUtil.del(Constant.RedisPrefix.LOGIN_MOBILE_SMS + userName);
            adminUser = adminUserService.lambdaQuery().eq(AdminUser::getLoginMobile, userName).one();
            if(adminUser == null){
                throw new RemoteServiceException("检测到当前手机号暂未注册");
            }
        } else {
            adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName).eq(AdminUser::getPassword, SecureUtil.md5(password)).one();
            if (adminUser == null) {
                throw new RemoteServiceException("帐号密码错误");
            }
        }
        if (!adminUser.getStatus()) {
            throw new RemoteServiceException("帐号冻结中，请联系相关管理人员");
        }

        AdminUserBean adminUserBean = new AdminUserBean();

        //经销商登录先初始化钱包
        if(adminUser.getIsCustomer()){
            walletLogic.initByK3Customer(adminUser.getCustomerId());

            //经销商获得是否前置仓
            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());
            if(kingDeeCustomer == null)
                throw new RemoteServiceException("绑定了无效的经销商信息，请联系相关人员");
            adminUserBean.setIsFront(kingDeeCustomer.getIsFront());
            adminUserBean.setIsPick(kingDeeCustomer.getIsPick());
            adminUserBean.setFrontPickType(kingDeeCustomer.getFrontPickType());

        }
        adminUser.setLastLoginTime(new Date());
        adminUser.updateById();


        BeanUtils.copyProperties(adminUser, adminUserBean);
        //不返回密码
        adminUserBean.setPassword(null);
        adminUserBean.setDecodePwd(null);
        adminUserBean.setToken(JwtUtils.createJWT(adminUser.getAdminUserId(), adminUser.getNickName(), adminUser.getUserName(), 20 * 60 * 60 * 1000));

        AdminUserCom adminUserCom = commonLogic.getAdminUser(adminUser.getAdminUserId(),true, request);
        adminUserBean.setAdminWebsit(adminUserCom.getAdminWebsit());

        String timeString = "2024-07-18 17:30:00";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = format.parse(timeString);

        if (adminUserCom.getIsCustomer() && new Date().before(DateUtil.offsetHour(date,12))){
            throw new RemoteServiceException("系统更新中");
        }

        //存放到redis
        redisUtil.set(Constant.RedisPrefix.TOKEN_MGR + adminUserBean.getToken(), adminUserCom, 20 * 60 * 60);
        return adminUserBean;
    }

    public void smsCode(String mobile,String code,String codeValue) throws Exception {
        if (!Validator.isMobile(mobile)) {
            throw new RemoteServiceException("手机号格式不正确。");
        }
        //判断手机号生成图片验证码是否正确
        String value = (String) redisUtil.get(Constant.RedisPrefix.VERIFICATION + code);
        if (!value.toLowerCase().equals(codeValue.toLowerCase())) {
            throw new RemoteServiceException("图片验证码错误");
        }
        AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getLoginMobile, mobile).one();
        if(adminUser == null){
            throw new RemoteServiceException("检测到当前手机号暂未注册");
        }
        // 向手机号发送验证码
        smsLogic.sendSms(Constant.RedisPrefix.LOGIN_MOBILE_SMS, mobile, SMSTypeEnum.LOGIN_MOBILE_SMS.toString(), Constant.SMS_EXPIRE);
    }


    /**
     * 修改密码
     */
    public void updatePassword(String userName, String password, String newPwd) throws RemoteServiceException {
        AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName)
                .eq(AdminUser::getPassword, SecureUtil.md5(password)).one();
        if (adminUser == null) {
            throw new RemoteServiceException("帐号密码错误");
        }
        adminUser.setDecodePwd(newPwd);
        adminUser.setPassword(SecureUtil.md5(newPwd));
        adminUserService.updateById(adminUser);
    }

    /**
     * 修改帐号状态
     */
    public void updateStatus(String adminUserId, Boolean status) {
        adminUserService.lambdaUpdate().set(AdminUser::getStatus, status).eq(AdminUser::getAdminUserId, adminUserId).update();
    }

    /**
     * 重置密码
     */
    public void resetPassword(String adminUserId, String password, HttpServletRequest request) throws RemoteServiceException {
        //检查是否拥有重置的密码权限
        String nickName = CommonUtils.getNickName(request);
        if (!nickName.equals("admin")) {
            throw new RemoteServiceException("只有超级管理员才有重置密码的权限");
        }

        //开始重置
        AdminUser adminUser = adminUserService.getById(adminUserId);
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setDecodePwd(password);
        adminUser.updateById();
    }

    /**
     * 首次登录重置密码
     */
    public void firstSetPwd(String password){
        AdminUserCom loginUser = commonLogic.getAdminUser();

        AdminUser adminUser = adminUserService.getById(loginUser.getAdminUserId());
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setDecodePwd(password);
        adminUser.setNotFirstLogin(true);
        adminUser.updateById();
    }


    /**
     * 新增帐号
     */
    @Transactional
    public void add(AdminUserAddReqBean adminUser, HttpServletRequest request) throws RemoteServiceException {

        AdminUserCom admin = commonLogic.getAdminUser(request);

        if (StringUtils.isEmpty(adminUser.getUserName()) || StringUtils.isEmpty(adminUser.getPassword())) {
            throw new RemoteServiceException("参数错误");
        }
        Integer count = adminUserService.lambdaQuery().eq(AdminUser::getUserName, adminUser.getUserName()).count();
        if (count > 0) {
            throw new RemoteServiceException("帐号已被注册");
        }
        if(CollectionUtils.isEmpty(adminUser.getAdminWebsitIds())){
            throw new RemoteServiceException("请选择部门");
        }
        if(adminUser.getType() != null && admin.getType() == 0 && adminUser.getAdminWebsitIds().size() > 1){
            throw new RemoteServiceException("目前只支持选择1个部门");
        }
        //需要用户roleId
        AdminRole loginRole = adminRoleService.getById(admin.getRoleId());
        AdminRole addUserRole = null;
        if (StringUtils.isEmpty(adminUser.getRoleId()) ||
                (addUserRole = adminRoleService.getById(adminUser.getRoleId())) == null) {
            throw new RemoteServiceException("请为用户选择角色");
        }
        adminUser.setRoleName(addUserRole.getName());
        //  添加用户的角色级别 <= 被添加的用户的角色级别
        if (loginRole.getType() < addUserRole.getType()) {
            throw new RemoteServiceException("无法为用户赋予与自身级别相当的角色");
        }
        //经销商帐号
        if(addUserRole.getName().equals(Constant.NOT_DEL_ROLE_NAME)){
            adminUser.setIsCustomer(true);
            //关联经销商信息
            if(StringUtils.isEmpty(adminUser.getCustomerId())){
                throw new RemoteServiceException("请选择经销商");
            }
//            Integer adminUserCount = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, adminUser.getCustomerId()).count();
//            if(adminUserCount > 0){
//                throw new RemoteServiceException("该经销商已被绑定");
//            }
            KingDeeCustomer kingDeeCustomer = k3CustomerLogic.bindUser(adminUser.getCustomerId());
            adminUser.setCustomerNumber(kingDeeCustomer.getNumber());
            adminUser.setCustomerName(kingDeeCustomer.getName());
            kingDeeCustomer.setIsGroupCompany(adminUser.getIsCustomerCompany());
            kingDeeCustomer.setParentId(adminUser.getParentCustomerId());
            kingDeeCustomer.setIsZr(adminUser.getIsZr());
            kingDeeCustomer.updateById();
            walletLogic.initByAddUser(admin.getAdminCompanyIds(),adminUser.getCustomerId());
        }
        //业务员
        if(addUserRole.getName().equals(Constant.NOT_DEL_ROLE_YWY) || addUserRole.getName().equals(Constant.NOT_DEL_SHANGYONG_ROLE_YWY)){
            adminUser.setIsService(true);
        }

        //用户级别默认取角色级别
        if (adminUser.getType() == null) {
            //数据库和角色表 type值不一致
            adminUser.setType(addUserRole.getType());
        }
        //部门账号
        if (adminUser.getType() == 0) {
            //默认登录用户的CompanyWechatId (admin则无)
            adminUser.setAdminCompanyId(admin.getAdminCompanyId());
            adminUser.setAdminCompanyName(admin.getAdminCompanyName());
        }
        adminUser.setDecodePwd(adminUser.getPassword());
        adminUser.setPassword(SecureUtil.md5(adminUser.getPassword()));
        adminUser.setCreateTime(new Date());
        adminUserService.save(adminUser);

        //添加账户绑定仓库
        if (CollectionUtils.isNotEmpty(adminUser.getCorrespondIds())) {
            List<AdminUserStock> adminUserList = new ArrayList<>();
            for (String correspondId : adminUser.getCorrespondIds()) {
                AdminUserStock adminUserStock = new AdminUserStock();
                adminUserStock.setAdminUserId(adminUser.getAdminUserId());
                adminUserStock.setCorrespondId(correspondId);
                adminUserList.add(adminUserStock);
            }
            adminUserStockService.saveBatch(adminUserList);
        }
        //添加金蝶物料权限
        if (CollectionUtils.isNotEmpty(adminUser.getCategoryIds())) {
            List<AdminUserCategoryRela> adminUserCategoryRelas = new ArrayList<>();
            for (AdminUserCategoryRela categoryRela : adminUser.getCategoryIds()) {
                AdminUserCategoryRela adminUserCategoryRela = new AdminUserCategoryRela();
                adminUserCategoryRela.setAdminUserId(adminUser.getAdminUserId());
                adminUserCategoryRela.setK3CategoryId(categoryRela.getK3CategoryId());
                adminUserCategoryRela.setK3CategoryName(categoryRela.getK3CategoryName());
                adminUserCategoryRela.setK3CategoryNumber(categoryRela.getK3CategoryNumber());
                adminUserCategoryRelas.add(adminUserCategoryRela);
            }
            adminUserCategoryRelaService.saveBatch(adminUserCategoryRelas);
        }


        //部门账号
        if (adminUser.getType() == 0) {
            //添加部门
            this.addAdminUserWebsit(adminUser);
            //todo admin 添加的部门没有companyWechatId
        }
        //公司账号
        else if (adminUser.getType() == 1) {
            AdminCompany companyWechat = null;
            if (StringUtils.isEmpty(adminUser.getAdminCompanyId()) || (companyWechat = adminCompanyService.getById(adminUser.getAdminCompanyId())) == null) {
                throw new RemoteServiceException("admin添加公司主账号时候,必须要有companyWechatId");
            }
            //获取根目录
            AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getParentId, 0)
                    .eq(AdminWebsit::getAdminCompanyId, companyWechat.getAdminCompanyId()).one();

            AdminUserWebsitRela adminUserWebsitRela = new AdminUserWebsitRela();
            adminUserWebsitRela.setAdminUserId(adminUser.getAdminUserId());
            adminUserWebsitRela.setAdminCompanyId(companyWechat.getAdminCompanyId());
            adminUserWebsitRela.setAdminWebsitId(adminWebsit.getAdminWebsitId());
            adminUserWebsitRela.setCreateTime(new Date());
            adminUserWebsitRela.insert();
        }

    }

    //添加用户部门关系
    private void addAdminUserWebsit(AdminUserAddReqBean adminUser) {
        //先清除
        if (CollectionUtils.isEmpty(adminUser.getAdminWebsitIds())) {
            return;
        }
        adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId, adminUser.getAdminUserId()).remove();
        List<AdminWebsit> websits = adminWebsitService.lambdaQuery().in(AdminWebsit::getAdminWebsitId, adminUser.getAdminWebsitIds()).list();
        if (websits.size() == 0) {
            throw new RemoteServiceException("请选择至少1个部门");
        }
        for (AdminWebsit adminWebsit : websits) {
            AdminUserWebsitRela adminUserWebsitRela = new AdminUserWebsitRela();
            adminUserWebsitRela.setAdminUserId(adminUser.getAdminUserId());
            adminUserWebsitRela.setAdminWebsitId(adminWebsit.getAdminWebsitId());
            adminUserWebsitRela.setAdminCompanyId(adminUser.getAdminCompanyId());
            adminUserWebsitRela.setCreateTime(new Date());
            adminUserWebsitRela.insert();
        }

    }

    /**
     * 修改帐号
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(HttpServletRequest request, AdminUserAddReqBean newUser) {

        if(CollectionUtils.isEmpty(newUser.getAdminWebsitIds())){
            throw new RemoteServiceException("请选择部门");
        }
        if(newUser.getAdminWebsitIds().size() > 1){
            throw new RemoteServiceException("目前只支持选择1个部门");
        }

        AdminUserCom admin = commonLogic.getAdminUser(request);

        AdminUser oldUser = adminUserService.getById(newUser.getAdminUserId());
        if(newUser.getType() == null){
            newUser.setType(oldUser.getType());
        }
        //前端传参错误，所以这里赋值下
        newUser.setIsCustomerCompany(newUser.getIsGroupCompany());

        //添加账户绑定仓库
        if (CollectionUtils.isNotEmpty(newUser.getCorrespondIds())) {
            adminUserStockService.lambdaUpdate().eq(AdminUserStock::getAdminUserId,newUser.getAdminUserId()).remove();
            List<AdminUserStock> adminUserList = new ArrayList<>();
            for (String correspondId : newUser.getCorrespondIds()) {
                AdminUserStock adminUserStock = new AdminUserStock();
                adminUserStock.setAdminUserId(newUser.getAdminUserId());
                adminUserStock.setCorrespondId(correspondId);
                adminUserList.add(adminUserStock);
            }
            adminUserStockService.saveBatch(adminUserList);

            //把所有子账号都变更
            if (admin.getIsCustomer() && !admin.getIsMaster()) {
                List<AdminUser> adminUsers = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, admin.getCustomerNumber())
                        .eq(AdminUser::getIsMaster, false).list();


                List<String> adminUserId = adminUsers.stream().map(AdminUser::getAdminUserId).collect(Collectors.toList());

                adminUserStockService.lambdaUpdate().in(AdminUserStock::getAdminUserId,adminUserId).remove();

                for (AdminUser adminUser : adminUsers) {

                    List<AdminUserStock> adminUserListin = new ArrayList<>();
                    for (String correspondId : newUser.getCorrespondIds()) {
                        AdminUserStock adminUserStock = new AdminUserStock();
                        adminUserStock.setAdminUserId(adminUser.getAdminUserId());
                        adminUserStock.setCorrespondId(correspondId);
                        adminUserListin.add(adminUserStock);
                    }
                    adminUserStockService.saveBatch(adminUserListin);

                }
            }

        }

        //添加金蝶物料权限
        if (CollectionUtils.isNotEmpty(newUser.getCategoryIds())) {
            adminUserCategoryRelaService.lambdaUpdate().eq(AdminUserCategoryRela::getAdminUserId,newUser.getAdminUserId()).remove();
            List<AdminUserCategoryRela> adminUserCategoryRelas = new ArrayList<>();
            for (AdminUserCategoryRela categoryRela : newUser.getCategoryIds()) {
                AdminUserCategoryRela adminUserCategoryRela = new AdminUserCategoryRela();
                adminUserCategoryRela.setAdminUserId(newUser.getAdminUserId());
                adminUserCategoryRela.setK3CategoryId(categoryRela.getK3CategoryId());
                adminUserCategoryRela.setK3CategoryName(categoryRela.getK3CategoryName());
                adminUserCategoryRela.setK3CategoryNumber(categoryRela.getK3CategoryNumber());
                adminUserCategoryRelas.add(adminUserCategoryRela);
            }
            adminUserCategoryRelaService.saveBatch(adminUserCategoryRelas);
        }

        //需要用户roleId
        AdminRole loginRole = adminRoleService.getById(admin.getRoleId());
        AdminRole addUserRole = null;
        if (StringUtils.isEmpty(newUser.getRoleId()) || (addUserRole = adminRoleService.getById(newUser.getRoleId())) == null) {
            throw new RemoteServiceException("请为用户选择角色");
        }

        if(oldUser.getIsCustomer() && !addUserRole.getName().equals(Constant.NOT_DEL_ROLE_NAME)){
            throw new RemoteServiceException("经销商帐号不可更改职位/角色");
        }

        //经销商帐号
        if(addUserRole.getName().equals(Constant.NOT_DEL_ROLE_NAME)){
            newUser.setIsCustomer(true);
            //关联经销商信息
            if(StringUtils.isEmpty(newUser.getCustomerId())){
                throw new RemoteServiceException("请选择经销商");
            }
//            Integer adminUserCount = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, newUser.getCustomerId()).count();
//            if(adminUserCount > 0){
//                throw new RemoteServiceException("该经销商已被绑定");
//            }

            kingDeeCustomerService.lambdaUpdate().eq(KingDeeCustomer::getId,oldUser.getCustomerId())
                    .set(KingDeeCustomer::getBindUser,false).update();

            KingDeeCustomer kingDeeCustomer = k3CustomerLogic.bindUser(newUser.getCustomerId());
            newUser.setCustomerNumber(kingDeeCustomer.getNumber());
            newUser.setCustomerName(kingDeeCustomer.getName());
            kingDeeCustomer.setIsGroupCompany(newUser.getIsCustomerCompany());
            kingDeeCustomer.setParentId(newUser.getParentCustomerId());
            kingDeeCustomer.setIsZr(newUser.getIsZr());
            kingDeeCustomer.updateById();
            walletLogic.initByAddUser(admin.getAdminCompanyIds(),newUser.getCustomerId());
        }

        //业务员
        if(oldUser.getIsService() && !addUserRole.getName().equals(Constant.NOT_DEL_ROLE_YWY)){

            if (customerProductTypeRelaService.lambdaQuery().eq(CustomerProductTypeRela::getServiceId,newUser.getAdminUserId()).count() > 0) {
                throw new RemoteServiceException("有钱包关联不可更改角色");
            }
            newUser.setIsService(false);

        }

        //  添加用户的角色级别 <= 被添加的用户的角色级别
        if (loginRole.getType() < addUserRole.getType()) {
            throw new RemoteServiceException("无法为用户赋予与自身级别相当的角色");
        }

        newUser.setUserName(null);
        newUser.setDecodePwd(StringUtils.isEmpty(newUser.getPassword()) ? null : newUser.getPassword());
        newUser.setPassword(StringUtils.isEmpty(newUser.getPassword()) ? null : SecureUtil.md5(newUser.getPassword()));
        newUser.updateById();

//        if (newUser.getType() != (addUserRole.getType() - 1)) {
//            throw new RemoteServiceException("所选角色级别和用户级别不一致!!");
//        }

        //当前为公司主账号
        if (oldUser.getType() == 1) {
            //删除企业部门关系
            adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId, newUser.getAdminUserId()).remove();
            //删除企业部门关系
            AdminUserWebsitRela adminUserCompanyRela = new AdminUserWebsitRela();
            adminUserCompanyRela.setAdminUserId(newUser.getAdminUserId());
            adminUserCompanyRela.setAdminWebsitId("1");
            adminUserCompanyRela.setAdminCompanyId(newUser.getAdminCompanyId());
            adminUserCompanyRela.setCreateTime(new Date());
            adminUserCompanyRela.insert();
        }

        //当前为为部门账号
        if (oldUser.getType() == 0) {
            //删除企业关系
            adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId, newUser.getAdminUserId()).remove();
            if(StringUtils.isEmpty(newUser.getAdminCompanyId())){
                newUser.setAdminCompanyId(admin.getAdminCompanyId());
            }
            //添加部门
            this.addAdminUserWebsit(newUser);
            //todo admin添加的部门没有companyWechatId
        }
        
        //更新所有子账号得权限
        updateChildUserByAdminUP(newUser);
    }

    private void updateChildUserByAdminUP(AdminUserAddReqBean newUser) {

        AdminUser oldUser = adminUserService.getById(newUser.getAdminUserId());

        List<AdminUser> list = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, oldUser.getCustomerId())
                .eq(AdminUser::getIsMaster, false).list();

        for (AdminUser adminUser : list) {
            //复制部门出来
       /*     List<AdminUserWebsitRela> adminUserWebsitReal = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, oldUser.getAdminUserId()).list();
            if(CollectionUtils.isNotEmpty(list)){
                adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId,adminUser.getAdminUserId()).remove();
                for(AdminUserWebsitRela rela : adminUserWebsitReal){
                    rela.setId(null);
                    rela.setAdminUserId(adminUser.getAdminUserId());
                    rela.insert();
                }
            }*/

            //仓库权限
            List<AdminUserStock> stocks = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, oldUser.getAdminUserId()).list();
            if(CollectionUtils.isNotEmpty(stocks)){
                adminUserStockService.lambdaUpdate().eq(AdminUserStock::getAdminUserId,adminUser.getAdminUserId()).remove();
                for (AdminUserStock stock : stocks) {
                    stock.setId(null);
                    stock.setAdminUserId(adminUser.getAdminUserId());
                    stock.insert();
                }
            }
            //分类权限
            List<AdminUserCategoryRela> categoryRelas = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId, oldUser.getAdminUserId()).list();
            if(CollectionUtils.isNotEmpty(categoryRelas)){
                adminUserCategoryRelaService.lambdaUpdate().eq(AdminUserCategoryRela::getAdminUserId,adminUser.getAdminUserId()).remove();
                for(AdminUserCategoryRela rela:categoryRelas){
                    rela.setId(null);
                    rela.setAdminUserId(adminUser.getAdminUserId());
                    rela.insert();
                }
            }
        }

    }

    public List<AdminUser> allList(){
        return adminUserService.list();
    }


    /**
     * 运营后台用户列表
     * @Param isCustomer 1=经销商 0=业务员
     *
     * @return
     */
    public IPage<AdminUserDto> list(String adminWebsitId,String roleId,String customerId,Boolean isCustomer,Boolean isMaster, Boolean status, String userName, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        List<String> roleName = new ArrayList<>();

        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        List<String> adminWebsitIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(adminWebsitId)) {
            adminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminWebsitId);
        }else{
            adminWebsitIds = adminUser.getAdminWebsitIds();
        }

        if (adminUser.getIsCustomer()) {
            String websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            List<AdminWebsit> list = adminWebsitService.lambdaQuery().eq(AdminWebsit::getWebsitNumber, websitNumber).list();
            adminWebsitIds = list.stream().map(AdminWebsit::getAdminWebsitId).collect(Collectors.toList());
        }
        String websitNumber = "";
        if(isCustomer != null && !isCustomer){
            roleName.add(Constant.NOT_DEL_ROLE_YWY);
            roleName.add(Constant.NOT_DEL_SHANGYONG_ROLE_YWY);
            if(adminUser.getAdminWebsit() != null) {
                websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            }
        }


        IPage<AdminUserDto> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize),adminUser.getAdminCompanyIds(),adminWebsitIds,
                userName, null,null,null, status,roleId,isMaster,customerId,isCustomer,roleName,websitNumber,null,null,null);

        return adminUserIPage;
    }


    /**
     * 商户列表
     */
    public IPage<AdminUserDto> list(String adminWebsitId, String userName, String nickName, String linkPhone, String email, Boolean status, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminWebsitId);

        IPage<AdminUserDto> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize),adminUser.getAdminCompanyIds(),adminWebsitIds,
                userName, nickName, linkPhone, email, status,null,true,null,null,null,null,null,null,null);
        return adminUserIPage;
    }

    /**
     * 查询用户列表
     */
    public IPage<AdminUser> getCustomerList(List<String> adminCompanyIds,Boolean isCustomer,Integer pageNo,Integer pageSize){
        IPage<AdminUser> page = adminUserService.lambdaQuery()
                .eq(isCustomer != null,AdminUser::getIsCustomer,isCustomer)
                .in(CollectionUtils.isNotEmpty(adminCompanyIds), AdminUser::getAdminCompanyId, adminCompanyIds)
                .orderByDesc(AdminUser::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }


    /**
     * 导出商户列表
     */
    public ExcelData exportMch(List<AdminUserDto> list) {
        String[] titles = new String[]{"用户名", "昵称","所属部门","联系电话", "邮箱", "地址", "创建时间"};
        List<List<Object>> rows = new ArrayList<>();
        for (AdminUser adminUser : list) {
            List<Object> row = new ArrayList<>();
            row.add(adminUser.getUserName());
            row.add(adminUser.getNickName());
            row.add(adminUser.getLinkPhone());
            row.add(adminUser.getEmail());
            row.add(adminUser.getAddress());
            row.add(DateUtil.formatDate(adminUser.getCreateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("sheet1");
        return excelData;
    }

    public AdminUser getById(String adminUserId){
        AdminUser adminUser = adminUserService.getById(adminUserId);
        return adminUser;
    }
    public AdminUser getByUserName(String userName){
        return adminUserService.lambdaQuery().eq(AdminUser::getUserName,userName).one();
    }

    public Map<String,AdminUser> getUserNameMap(){
        List<AdminUser> list = adminUserService.lambdaQuery().eq(AdminUser::getIsCustomer,false).list();
        Map<String, AdminUser> collect = list.stream().collect(Collectors.toMap(AdminUser::getUserName, v -> v));
        return collect;
    }

    /**
     * 运营后台用户详情
     *
     * @param adminUserId
     * @return
     */
    public AdminUserBean detail(String adminUserId) {
        AdminUser adminUser = adminUserService.getById(adminUserId);
        AdminUserBean adminUserBean = new AdminUserBean();
        BeanUtils.copyProperties(adminUser, adminUserBean);

        K3CustomerBean detail = k3CustomerLogic.detail(adminUser.getCustomerId());

        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminUserId, adminUser.getAdminUserId()).list();
        if (list.size() > 0) {
            String adminCompanyId = list.get(0).getAdminCompanyId();
            AdminCompany adminCompany = adminCompanyService.getById(adminCompanyId);
            adminUserBean.setAdminCompanyId(adminCompanyId);
            adminUserBean.setAdminCompanyName(adminCompany.getAdminCompanyName());
            List<String> collect = list.stream().map(AdminUserWebsitRela::getAdminWebsitId).collect(Collectors.toList());
            adminUserBean.setAdminWebsitIds(collect);

            AdminWebsit adminWebsit = adminWebsitService.getById(list.get(0).getAdminWebsitId());
            adminUserBean.setAdminWebsit(adminWebsit);
        }
        adminUserBean.setEnginSysUrl(externalEnginLogic.getLoginUrl());
        if(detail != null) {
            adminUserBean.setIsZr(detail.getIsZr());
        }
        List<StockCorrespond> stockCorresponds = adminMapper.StockCorrespondList(adminUser.getAdminUserId());
        List<String> nameList = stockCorresponds.stream().map(item -> item.getId().toString()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(nameList))
        adminUserBean.setStockCorrespondList(nameList.stream().toArray(String[]::new));
        //金蝶物料权限
        List<AdminUserCategoryRela> categoryRelaList = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId,adminUser.getAdminUserId()).list();
        List<String> k3CategoryIds = categoryRelaList.stream().map(item -> item.getK3CategoryId()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(nameList)){
            adminUserBean.setK3CategoryList(k3CategoryIds.stream().toArray(String[]::new));
        }
        // 多工程机账号
//        List<AdminUserBindEngin> adminUserBindEngins = adminUserBindEnginService.lambdaQuery()
//                .eq(AdminUserBindEngin::getAdminUserId, adminUserBean.getAdminUserId())
//                .list();
//
//        adminUserBean.setBindEnginList(adminUserBindEngins);

        if (adminUserBean.getIsCustomer()){
            //经销商获得是否前置仓
            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());
            if(kingDeeCustomer != null) {
                adminUserBean.setIsFront(kingDeeCustomer.getIsFront());
                adminUserBean.setFrontPickType(kingDeeCustomer.getFrontPickType());
                adminUserBean.setIsPick(kingDeeCustomer.getIsPick());

                //所属集团
                adminUserBean.setIsCustomerCompany(kingDeeCustomer.getIsGroupCompany());
                adminUserBean.setGroupCompanyId(kingDeeCustomer.getParentId());
            }
        }
        if (!CollectionUtils.isEmpty(adminUserBean.getAdminWebsitIds()) && !CollectionUtils.isEmpty(adminUserBean.getAdminWebsitIds().stream().filter(item -> item.equals("1")).collect(Collectors.toList()))){
            adminUserBean.setIsHongGe(true);
        }
        adminUserBean.setDecodePwd(null);
        adminUserBean.setChangeNum(Convert.toInt(redisUtil.get(Constant.SUPPLY_CHANGE_NUM+adminUser.getAdminUserId())));

        // 商用登录审核员
        if (StrUtil.isNotBlank(adminUser.getRoleName()) ) {
            for (String str : Constant.NOT_DEL_ROLE_SPY) {
                if (adminUser.getRoleName().contains(str)) {
                    adminUserBean.setIsTradeExaminer(true);
                    break;
                } else {
                    adminUserBean.setIsTradeExaminer(false);
                }
            }
        }

        if (Objects.isNull(adminUserBean.getIsTradeExaminer())) {
            adminUserBean.setIsTradeExaminer(false);
        }
//        adminUserBean.setIsTradeExaminer(Constant.NOT_DEL_ROLE_SPY.contains(adminUser.getRoleName()));

        return adminUserBean;
    }

    /**
     * 根据部门查询账号
     */
    public List<AdminUser> queryAdminUserByWebsit(List<String> adminWebsitIds){
        if(CollectionUtils.isEmpty(adminWebsitIds)){
            return new ArrayList<>();
        }
        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery()
                .in(AdminUserWebsitRela::getAdminWebsitId, adminWebsitIds).list();
        List<String> adminUserIds = list.stream().map(AdminUserWebsitRela::getAdminUserId).collect(Collectors.toList());
        if(adminUserIds.size() == 0){
            return new ArrayList<>();
        }
        List<AdminUser> adminUsers = adminUserService.lambdaQuery().in(AdminUser::getAdminUserId, adminUserIds).list();
        return adminUsers;
    }


    /**
     * 退出登录
     */
    public void logout(HttpServletRequest request) {
        String token = CommonUtils.getToken(request);
        redisUtil.del(Constant.RedisPrefix.TOKEN_MGR + token);
    }

    /**
     * 检查工程机系统是否合法
     */
    public void checkEnginUser(HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        Integer result = externalEnginLogic.checkEnginUser(adminUser.getEnginUserName(), adminUser.getEnginPassword());
        if(Objects.isNull(result)){
            throw new RemoteServiceException(4444,"帐号密码验证失败");
        }
    }


    /**
     * 绑定工程机系统帐号
     */
    public void bindEngin(String userName,String password, Boolean isReset, HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        //有可能自己要改
//        if(adminUser.getBindEngin()){
//            throw new RemoteServiceException("请勿重复绑定帐号密码");
//        }
//        Integer count = adminUserService.lambdaQuery()
//                .eq(AdminUser::getEnginUserName, userName)
//                .ne(AdminUser::getAdminUserId,adminUser.getAdminUserId())
//                .count();
//        if(count > 0){
//            throw new RemoteServiceException("请勿重复绑定帐号密码");
//        }

//        if (!isReset) {
//            Integer count = adminUserBindEnginService.lambdaQuery()
//                    .eq(AdminUserBindEngin::getAdminUserId, adminUser.getAdminUserId())
//                    .eq(AdminUserBindEngin::getEnginUserName, userName)
//                    .count();
//            if (count > 0) {
//                throw new RemoteServiceException(userName + "：重复帐号，历史已验证通过");
//            }
//        }

        Integer result = externalEnginLogic.checkEnginUser(userName, password);
        if(Objects.isNull(result)){
            throw new RemoteServiceException(4444,"帐号密码验证失败");
        }

//        if (!isReset) {
//            AdminUserBindEngin adminUserBindEngin = new AdminUserBindEngin();
//            adminUserBindEngin.setAdminUserId(adminUser.getAdminUserId())
//                    .setEnginUserId(result)
//                    .setEnginUserName(userName)
//                    .setEnginPassword(password);
//
//            adminUserBindEnginService.save(adminUserBindEngin);
//        }

        adminUser.setBindEngin(true);
        adminUser.setEnginUserName(userName);
        adminUser.setEnginPassword(password);

        adminUser.updateById();
    }


    /**
     * 根据登录帐号查询权限模块
     */
    public List<AdminModuleTree> queryAdminModule(String adminUserId,String flag) {
        //String adminUserId = CommonUtils.getUserId(request);

        AdminUser adminUser = adminUserService.getById(adminUserId);

        List<AdminModuleTree> adminModuleTrees = new ArrayList<>();
        
        if (adminUser.getUserName().equals("admin")) {
            return this.queryAdminModuleTree(null, true, null, flag);
        } else {
            if(adminUser.getIsCustomer() && !adminUser.getIsMaster()){
                KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());
                if (kingDeeCustomer.getJiaxianType().equals(JiaXianStockEnum.JIAXIAN.getKey()) || adminUser.getIsGongcheng()) 
                    adminModuleTrees = this.queryAdminModuleTree(adminUser.getRoleId(), false, null, flag);
                else
                    adminModuleTrees =  this.queryAdminModuleTree(adminUser.getAdminUserId(), false, null, flag);
            }else {
                adminModuleTrees =  this.queryAdminModuleTree(adminUser.getRoleId(), false, null, flag);
            }
        }

        if (adminUser.getIsShangyong() && adminUser.getIsCustomer()){
            adminModuleTrees.addAll(this.queryAdminModuleTree(Constant.SHANGYONGJINGXIAOSHANG, false, null, flag));
        }

   /*     if (adminUser.getIsShangyong() && adminUser.getIsService()){
            adminModuleTrees.addAll(this.queryAdminModuleTree(Constant.SHANGYONGYEWUYUAN ,false, null, flag));
        }*/
        
        return adminModuleTrees;
    }


    /**
     * 给角色授权
     */
    @Transactional
    public void grantModules(String roleId, List<String> adminModuleIds) {
        //1.清空该角色的权限
        adminUserModuleRelaService.lambdaUpdate().eq(AdminUserModuleRela::getAdminRoleId, roleId).remove();

        //2.生成权限
        List<AdminUserModuleRela> list = new ArrayList<>();
        for (String adminModuleId : adminModuleIds) {
            AdminUserModuleRela adminUserModuleRela = new AdminUserModuleRela();
            adminUserModuleRela.setAdminRoleId(roleId);
            adminUserModuleRela.setCreateTime(new Date());
            adminUserModuleRela.setStatus(true);
            adminUserModuleRela.setAdminModuleId(adminModuleId);
            list.add(adminUserModuleRela);
        }
        adminUserModuleRelaService.saveBatch(list);
    }

    /**
     * 根据角色id查询拥有的权限ids
     */
    public List<String> queryModuleIdChecked(String adminRoleId) {
        AdminRole adminRole = adminRoleService.getById(adminRoleId);
        Boolean admin = adminRole.getName().equals("超级管理员");

        List<AdminModule> list = adminModuleService.list();
        //List<String> moduleIds = list.stream().filter(v -> v.getType() != 1).map(AdminModule::getModuleId).collect(Collectors.toList());

        if (admin) {
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            return list.stream().map(AdminModule::getModuleId).collect(Collectors.toList());
        }
        List<AdminUserModuleRela> relas = adminUserModuleRelaService.lambdaQuery()
                .eq(AdminUserModuleRela::getAdminRoleId, adminRoleId).list();
        if (CollectionUtils.isEmpty(relas)) {
            return new ArrayList<>();
        }
        return relas.stream()
                //.filter(v -> moduleIds.contains(v.getAdminModuleId()))
                .map(AdminUserModuleRela::getAdminModuleId)
                .collect(Collectors.toList());
    }

    /**
     * 根据角色查询所有功能模块权限
     */
    public List<AdminModuleTree> queryAllAdminModuleTree(String adminRoleId, HttpServletRequest request) {
        String userId = CommonUtils.getUserId(request);
        //更改的角色
        AdminRole adminRole = adminRoleService.getById(adminRoleId);
        //查询该角色有的权限d
        List<AdminUserModuleRela> hasModules = adminUserModuleRelaService.lambdaQuery().eq(AdminUserModuleRela::getAdminRoleId, adminRoleId).list();
        List<String> collect = new ArrayList<>();
        if (!CollectionUtils.isEmpty(hasModules)) {
            collect = hasModules.stream().map(AdminUserModuleRela::getAdminModuleId).collect(Collectors.toList());
        }
        List<AdminModuleTree> adminModuleTrees = this.queryAdminModuleTree(adminRoleId, adminRole.getName().equals("超级管理员"), collect, null);
        return adminModuleTrees;
    }


    private List<AdminModuleTree> queryAdminModuleTree(String roleId, Boolean admin, List<String> hasModule, String flag) {

        List<AdminModule> adminModules = null;

        List<String> flags = Arrays.asList("menu","index");

        if (admin != null && !admin) {
            //非超管角色
            List<AdminUserModuleRela> list = adminUserModuleRelaService.lambdaQuery()
                    .eq(StringUtils.isNotEmpty(roleId), AdminUserModuleRela::getAdminRoleId, roleId)
                    .list();
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            List<String> moduleIds = list.stream().map(AdminUserModuleRela::getAdminModuleId).collect(Collectors.toList());
            adminModules = adminModuleService.lambdaQuery()
                    .ne(StringUtils.isNotEmpty(flag) && flags.contains(flag),AdminModule::getType,3)
                    .in(AdminModule::getModuleId, moduleIds)
                    .orderByAsc(AdminModule::getSortNum).list();
        } else {
            //超管角色
            List<AdminUserModuleRela> list = adminUserModuleRelaService.lambdaQuery().list();
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            adminModules = adminModuleService.lambdaQuery()
                    .ne(StringUtils.isNotEmpty(flag) && flags.contains(flag),AdminModule::getType,3)
                    .orderByAsc(AdminModule::getSortNum).list();
        }
        List<AdminModuleTree> trees = new ArrayList<>();
        for (AdminModule adminModule : adminModules) {
            AdminModuleTree adminModuleTree = new AdminModuleTree();
            BeanUtils.copyProperties(adminModule, adminModuleTree);
            if ((hasModule != null && hasModule.contains(adminModule.getModuleId())) || admin) {
                adminModuleTree.setShow(true);
            }
            trees.add(adminModuleTree);
        }

        List<AdminModuleTree> parents = trees.stream().filter(v -> v.getLevel() == 1).collect(Collectors.toList());

        for (AdminModuleTree adminModuleTree : parents) {

            if(flag != null && flag.equals("index")) {
                //首页二级菜单
                this.treeModuleIndex(trees, adminModuleTree.getModuleId(), hasModule, admin,adminModuleTree);
            }else{
                //常规树形菜单
                adminModuleTree.setChildren(this.treeModule(trees, adminModuleTree.getModuleId(), hasModule, admin));
            }
        }

        return parents;
    }

    private List<AdminModuleTree> treeModule(List<AdminModuleTree> list, String parentId, List<String> hasModule, Boolean admin) {
        //最父级资源树
        if (StringUtils.isEmpty(parentId)) {
            return new ArrayList<>();
        }
        List<AdminModuleTree> collect = list.stream().filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        for (AdminModuleTree bean : collect) {
            if ((hasModule != null && hasModule.contains(bean.getModuleId())) || admin) {
                bean.setShow(true);
            }
            bean.setChildren(this.treeModule(list, bean.getModuleId(), hasModule, admin));
        }
        return collect;
    }


    private List<AdminModuleTree> treeModuleIndex(List<AdminModuleTree> list, String parentId, List<String> hasModule, Boolean admin,AdminModuleTree topParent) {
        //最父级资源树
        if (StringUtils.isEmpty(parentId)) {
            return new ArrayList<>();
        }
        List<AdminModuleTree> collect = list.stream().filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        for (AdminModuleTree bean : collect) {
            if ((hasModule != null && hasModule.contains(bean.getModuleId())) || admin) {
                bean.setShow(true);
            }
            if(bean.getType() == 2) {
                topParent.getChildren().add(bean);
            }else{
                this.treeModuleIndex(list, bean.getModuleId(), hasModule, admin,topParent);
            }
        }
        return collect;
    }


    /**
     * 导入登录用户数据
     */
    @Transactional
    public ExcelData importUser(List<Object> rows, HttpServletRequest request) throws Exception {
        AdminUserCom admin = commonLogic.getAdminUser(request);

        List<List<Object>> errorO = new ArrayList<>();
        List<StockCorrespond> stockCorresponds = stockCorrespondService.list();
        List<KingDeeCategory> kingDeeCategorys = kingDeeCategoryService.list();
        List<String> delIds = new ArrayList<>();

        for (Object o : rows) {
            AdminUser saveUser = new AdminUser();
            List<Object> row = (List<Object>) o;
            String userName = (String) row.get(0);
            String nickName = (String) row.get(1);
            String roleName = (String) row.get(2);
            String deptName = (String) row.get(3);
            String customerName = (String) row.get(4);
            String isCustomerCompany = (String) row.get(5);
            String belongCompany = (String) row.get(6);
            String isZr = (String) row.get(7);
            String password = (String) row.get(8);
            String canUseStore = (String) row.get(9);
            String loginMobile = (String) row.get(10);
            String K3CategoryNames = (String) row.get(11);
            List<AdminUser> adminList = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName).list();
            if (adminList != null && adminList.size() > 0) {
                log.info("当前账号已存在" + userName);
                throw new RemoteServiceException("帐号【"+userName+"】已存在");
//                for(AdminUser adminUser:adminList){
//                    delIds.add(adminUser.getAdminUserId());
//                }
            }

            if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(nickName) || StringUtils.isEmpty(roleName)) {
                row.add("帐号数据有误");
                errorO.add(row);
                continue;
            }

            List<AdminRole> loginRole = adminRoleService.lambdaQuery().eq(AdminRole::getName, roleName).list();
            if (loginRole != null && loginRole.size() > 0) {
                saveUser.setRoleName(roleName);
                saveUser.setRoleId(loginRole.get(0).getAdminRoleId());
            } else {
                row.add("角色信息有误");
                errorO.add(row);
                continue;
            }

            if (roleName.equals(Constant.NOT_DEL_ROLE_NAME)) {
                saveUser.setIsCustomer(true);
                //关联经销商信息
                List<KingDeeCustomer> kingDeeCustomers = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getName, customerName).list();
                if (kingDeeCustomers.size() <= 0) {
                    row.add("经销商信息不存在");
                    errorO.add(row);
                    continue;
                }

                KingDeeCustomer kingDeeCustomer = k3CustomerLogic.bindUser(kingDeeCustomers.get(0).getId());
                saveUser.setCustomerNumber(kingDeeCustomer.getNumber());
                saveUser.setCustomerName(kingDeeCustomer.getName());
                saveUser.setCustomerId(kingDeeCustomer.getId());
                if (isCustomerCompany != null && "是".equals(isCustomerCompany)) {
                    kingDeeCustomer.setIsGroupCompany(true);
                }

                if (belongCompany != null) {
                    List<KingDeeCustomer> king = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getName, belongCompany).list();
                    if (king.size() <= 0) {
                        row.add("所属集团信息不存在");
                        errorO.add(row);
                        continue;
                    }
                    kingDeeCustomer.setParentId(king.get(0).getId());
                }


                if (isZr != null && "是".equals(isZr)) {
                    kingDeeCustomer.setIsZr(true);
                }
                kingDeeCustomer.updateById();
                walletLogic.initByAddUser(admin.getAdminCompanyIds(), kingDeeCustomers.get(0).getId());
            }

            //业务员
            if (roleName.equals(Constant.NOT_DEL_ROLE_YWY) || roleName.equals(Constant.NOT_DEL_SHANGYONG_ROLE_YWY)) {
                saveUser.setIsService(true);
            }

            AdminRole addUserRole = adminRoleService.getById(saveUser.getRoleId());

            //用户级别默认取角色级别
            if (saveUser.getType() == null) {
                //数据库和角色表 type值不一致
                saveUser.setType(addUserRole.getType());
            }
            log.info("saveUserType" + saveUser.getType() + "companyId:" + admin.getAdminCompanyId());
            //部门账号
            if (saveUser.getType() == 0) {
                //默认登录用户的CompanyWechatId (admin则无)
                saveUser.setAdminCompanyId(admin.getAdminCompanyId());
                saveUser.setAdminCompanyName(admin.getAdminCompanyName());
            }

            List<AdminWebsit> adminWebsits = adminWebsitService.lambdaQuery().eq(AdminWebsit::getName, deptName.trim()).list();
            List<String> adminWebsitIds = new ArrayList<>();
            if (adminWebsits.size() == 0) {
                row.add("部门不存在");
                errorO.add(row);
                continue;
            }

            saveUser.setRoleName(roleName);
            saveUser.setNickName(nickName);
            saveUser.setUserName(userName);
            saveUser.setDecodePwd(password);
            saveUser.setPassword(SecureUtil.md5(password));
            saveUser.setCreateTime(new Date());
            saveUser.setLoginMobile(loginMobile);
            saveUser.setAdminCompanyId(admin.getAdminCompanyId());
            saveUser.setAdminCompanyName(admin.getAdminCompanyName());
            adminUserService.save(saveUser);

            adminWebsitIds.add(adminWebsits.get(0).getAdminWebsitId());

            AdminUserAddReqBean adminUser = new AdminUserAddReqBean();
            adminUser.setAdminWebsitIds(adminWebsitIds);
            adminUser.setAdminUserId(saveUser.getAdminUserId());
            adminUser.setAdminCompanyId(saveUser.getAdminCompanyId());
            //部门账号
            if (saveUser.getType() == 0) {
                //添加部门
                this.addAdminUserWebsit(adminUser);
            }
            // 公司账号
            else if (saveUser.getType() == 1) {
                AdminCompany companyWechat = null;
                if (StringUtils.isEmpty(adminUser.getAdminCompanyId()) || (companyWechat = adminCompanyService.getById(adminUser.getAdminCompanyId())) == null) {
                    // throw new RemoteServiceException("admin添加公司主账号时候,必须要有companyWechatId");
                    errorO.add(row);
                }
                //获取根目录
                AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                        .eq(AdminWebsit::getParentId, 0)
                        .eq(AdminWebsit::getAdminCompanyId, companyWechat.getAdminCompanyId()).one();

                AdminUserWebsitRela adminUserWebsitRela = new AdminUserWebsitRela();
                adminUserWebsitRela.setAdminUserId(adminUser.getAdminUserId());
                adminUserWebsitRela.setAdminCompanyId(companyWechat.getAdminCompanyId());
                adminUserWebsitRela.setAdminWebsitId(adminWebsit.getAdminWebsitId());
                adminUserWebsitRela.setCreateTime(new Date());
                adminUserWebsitRela.insert();
            }

            List<String> correspondIds = new ArrayList<>();
            for (StockCorrespond stock : stockCorresponds) {
                if (canUseStore!= null&& canUseStore.indexOf(stock.getName()) != -1) {
                    correspondIds.add(stock.getId());
                }
            }

            //添加账户绑定仓库
            if (CollectionUtils.isNotEmpty(correspondIds)) {
                List<AdminUserStock> adminUserList = new ArrayList<>();
                for (String correspondId : correspondIds) {
                    AdminUserStock adminUserStock = new AdminUserStock();
                    adminUserStock.setAdminUserId(saveUser.getAdminUserId());
                    adminUserStock.setCorrespondId(correspondId);
                    adminUserList.add(adminUserStock);
                }
                adminUserStockService.saveBatch(adminUserList);
            }

            List<AdminUserCategoryRela> k3CategoryIds = new ArrayList<>();
            for (KingDeeCategory category : kingDeeCategorys) {
                if (K3CategoryNames != null && K3CategoryNames.indexOf(category.getName()) != -1) {
                    AdminUserCategoryRela rela = new AdminUserCategoryRela();
                    rela.setK3CategoryNumber(category.getNumber());
                    rela.setK3CategoryName(category.getName());
                    rela.setK3CategoryId(category.getId());
                    rela.setAdminUserId(saveUser.getAdminUserId());
                    k3CategoryIds.add(rela);
                }
            }

            if(CollectionUtils.isNotEmpty(k3CategoryIds)){
                adminUserCategoryRelaService.saveBatch(k3CategoryIds);
            }
        }

//        if(CollectionUtils.isNotEmpty(delIds)){
//            adminUserService.lambdaUpdate().in(AdminUser::getAdminUserId,delIds).remove();
//            adminUserCategoryRelaService.lambdaUpdate().in(AdminUserCategoryRela::getAdminUserId,delIds).remove();
//            adminUserWebsitRelaService.lambdaUpdate().in(AdminUserWebsitRela::getAdminUserId,delIds).remove();
//            adminUserStockService.lambdaUpdate().in(AdminUserStock::getAdminUserId,delIds).remove();
//        }


        String[] titles = new String[]{"账号*", "用户名*", "角色名称*", "部门", "经销商", "集团公司", "所属集团",
                "是否折让", "密码", "可用仓库", "登录手机号","金蝶物料权限", "错误原因"};

        ExcelData excelData = new ExcelData();
        excelData.setRows(errorO);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;

    }


    /**
     * 批量修改仓库、存货类别
     */
    public void batchUpdate(List<Object> rows){

        List<StockCorrespond> stockCorresponds = stockCorrespondService.list();
        Map<String, String> stockMap = stockCorresponds.stream().collect(Collectors.toMap(StockCorrespond::getName, StockCorrespond::getId));

        List<KingDeeCategory> kingDeeCategorys = kingDeeCategoryService.list();
        Map<String, KingDeeCategory> categoryMap = kingDeeCategorys.stream().collect(Collectors.toMap(KingDeeCategory::getName, v -> v));

        for (Object o : rows) {
            List<Object> row = (List<Object>) o;
            String userName = (String) row.get(0);
            String nickName = (String) row.get(1);
            String roleName = (String) row.get(2);
            String deptName = (String) row.get(3);
            String customerName = (String) row.get(4);
            String isCustomerCompany = (String) row.get(5);
            String belongCompany = (String) row.get(6);
            String isZr = (String) row.get(7);
            String password = (String) row.get(8);
            String canUseStore = (String) row.get(9);
            String loginMobile = (String) row.get(10);
            String k3CategoryNames = (String) row.get(11);

            AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName).one();
            if(adminUser == null){
                throw new RemoteServiceException("帐号【"+userName+"】不存在");
            }
            if(StringUtils.isNotEmpty(canUseStore)) {
                canUseStore = canUseStore.replaceAll("，",",");
                String[] split = canUseStore.split(",");
                List<String> correspondIds = new ArrayList<>();
                for(String stock : split){
                    if(stockMap.containsKey(stock)){
                        correspondIds.add(stockMap.get(stock));
                    }
                }
//                for (StockCorrespond stock : stockCorresponds) {
//                    if (canUseStore != null && canUseStore.indexOf(stock.getName()) != -1) {
//                        correspondIds.add(stock.getId());
//                    }
//                }
                //添加账户绑定仓库
                if (CollectionUtils.isNotEmpty(correspondIds)) {
                    List<AdminUserStock> adminUserList = new ArrayList<>();
                    for (String correspondId : correspondIds) {
                        AdminUserStock adminUserStock = new AdminUserStock();
                        adminUserStock.setAdminUserId(adminUser.getAdminUserId());
                        adminUserStock.setCorrespondId(correspondId);
                        adminUserList.add(adminUserStock);
                    }
                    adminUserStockService.lambdaUpdate().eq(AdminUserStock::getAdminUserId,adminUser.getAdminUserId()).remove();
                    adminUserStockService.saveBatch(adminUserList);
                }
            }

            if (StringUtils.isNotEmpty(k3CategoryNames)) {

                k3CategoryNames = k3CategoryNames.replaceAll("，",",");
                String[] split = k3CategoryNames.split(",");

                List<AdminUserCategoryRela> k3CategoryIds = new ArrayList<>();
                for(String category:split){
                    if(categoryMap.containsKey(category)){
                        KingDeeCategory kingDeeCategory = categoryMap.get(category);
                        AdminUserCategoryRela rela = new AdminUserCategoryRela();
                        rela.setK3CategoryNumber(kingDeeCategory.getNumber());
                        rela.setK3CategoryName(kingDeeCategory.getName());
                        rela.setK3CategoryId(kingDeeCategory.getId());
                        rela.setAdminUserId(adminUser.getAdminUserId());
                        k3CategoryIds.add(rela);
                    }
                }


//                    if (k3CategoryNames != null && k3CategoryNames.indexOf(category.getName()) != -1) {
//                        AdminUserCategoryRela rela = new AdminUserCategoryRela();
//                        rela.setK3CategoryNumber(category.getNumber());
//                        rela.setK3CategoryName(category.getName());
//                        rela.setK3CategoryId(category.getId());
//                        rela.setAdminUserId(adminUser.getAdminUserId());
//                        k3CategoryIds.add(rela);
//                    }


                if(CollectionUtils.isNotEmpty(k3CategoryIds)){
                    adminUserCategoryRelaService.lambdaUpdate().eq(AdminUserCategoryRela::getAdminUserId,adminUser.getAdminUserId()).remove();
                    adminUserCategoryRelaService.saveBatch(k3CategoryIds);
                }
            }
        }
    }



    /**
     * 删除
     * @param id
     */
    public void delEnginAccount(String id) {
        adminUserBindEnginService.lambdaUpdate().eq(AdminUserBindEngin::getId, id).remove();
    }

    /**
     * 新建子账号
     */
    @Transactional
    public void addChildUser(String userName,String password,List<String> adminModuleIds){

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String oldUserId = adminUser.getAdminUserId();
        String oldUserName = adminUser.getUserName();
        if(!adminUser.getIsCustomer()){
            throw new RemoteServiceException("非经销商帐号不可生成子账号");
        }
        Integer count = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, adminUser.getCustomerId()).count();
        String newUserName = oldUserName + (count < 10 ? "0"+count : count+1);
        //复制个小号出来
        adminUser.setAdminUserId("C"+IdWorker.getIdStr());
        adminUser.setUserName(newUserName);
        adminUser.setNickName(newUserName);
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setIsMaster(false);
        adminUser.insert();

        //复制部门出来
        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(list)){
            adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId,adminUser.getAdminUserId()).remove();
            for(AdminUserWebsitRela rela : list){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }

        //更新权限
        if(CollectionUtils.isNotEmpty(adminModuleIds)){
            adminUserModuleRelaService.lambdaUpdate().eq(AdminUserModuleRela::getAdminRoleId,adminUser.getAdminUserId()).remove();
            for(String adminModuleId : adminModuleIds){
                AdminUserModuleRela rela = new AdminUserModuleRela();
                rela.setAdminModuleId(adminModuleId);
                rela.setAdminRoleId(adminUser.getAdminUserId());
                rela.setStatus(true);
                rela.insert();
            }
        }

        //仓库权限
        List<AdminUserStock> stocks = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(stocks)){
            for (AdminUserStock stock : stocks) {
                stock.setId(null);
                stock.setAdminUserId(adminUser.getAdminUserId());
                stock.insert();
            }
        }
        //分类权限
        List<AdminUserCategoryRela> categoryRelas = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(categoryRelas)){
            for(AdminUserCategoryRela rela:categoryRelas){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }
    }


    /**
     * 修改子账号
     */
    @Transactional
    public void updateChildUser(String adminUserId,String password,List<String> adminModuleIds,String name){
        AdminUser adminUser = adminUserService.getById(adminUserId);
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setNickName(name);
        adminUser.updateById();

        //更新权限
        if(CollectionUtils.isNotEmpty(adminModuleIds)){
           adminUserModuleRelaService.lambdaUpdate().eq(AdminUserModuleRela::getAdminRoleId,adminUser.getAdminUserId()).remove();
           for(String adminModuleId : adminModuleIds){
               AdminUserModuleRela rela = new AdminUserModuleRela();
               rela.setAdminModuleId(adminModuleId);
               rela.setAdminRoleId(adminUserId);
               rela.setStatus(true);
               rela.insert();
           }
        }
    }

    /**
     * 子账号权限
     */
    public List<String> moduleChecked(String adminUserId){
        List<AdminUserModuleRela> relas = adminUserModuleRelaService.lambdaQuery()
                .eq(AdminUserModuleRela::getAdminRoleId, adminUserId).list();
        if (CollectionUtils.isEmpty(relas)) {
            return new ArrayList<>();
        }
        return relas.stream()
                //.filter(v -> moduleIds.contains(v.getAdminModuleId()))
                .map(AdminUserModuleRela::getAdminModuleId)
                .collect(Collectors.toList());
    }


    /**
     * 导出数据
     */
    public ExcelData listExport(List<AdminUserDto> adminUserDtos) {
        String[] titles = new String[]{"账号", "用户名", "角色组称", "部门", "经销商", "集团公司",
                "所属集团", "是否折让", "密码", "可用仓库", "登录手机号","金蝶物料权限","状态","是否商用经销商"};
        List<List<Object>> rows = new ArrayList<>();
        if(adminUserDtos.size() >2000){
            throw new RemoteServiceException("数据量太大，请分批导出");
        }

        for (AdminUserDto user : adminUserDtos) {
            List<Object> row = new ArrayList<>();
            row.add(user.getUserName());
            row.add(user.getNickName());
            row.add(user.getRoleName());
            //部门

            List<StockCorrespond> stockCorresponds = adminMapper.StockCorrespondList(user.getAdminUserId());
            stockCorresponds = stockCorresponds.stream().filter(v -> v != null).collect(Collectors.toList());

            StringBuffer na =  new StringBuffer();
            if(stockCorresponds != null && stockCorresponds.size() > 0){
                for(int i =0; i<stockCorresponds.size();i++){
                    if(stockCorresponds.get(i) != null){
                        na.append(stockCorresponds.get(i).getName());
                        if(i != stockCorresponds.size() -1){
                            na.append(",");
                        }
                    }
                }
                user.setStockCorrespondName(na.toString());
            }
            List<String> nameList = stockCorresponds.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(nameList))
                user.setStockCorrespondList(nameList.stream().toArray(String[]::new));
            //处理
            List<AdminUserCategoryRela> relas = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId,user.getAdminUserId()).list();
            StringBuffer relaBuffer =  new StringBuffer();
            if(relas != null && relas.size() > 0){
                for(int i =0; i < relas.size();i++){
                    if(relas.get(i) != null){
                        relaBuffer.append(relas.get(i).getK3CategoryName());
                        if(i != relas.size() -1){
                            relaBuffer.append(",");
                        }
                    }
                }
                user.setBindCategoryName(relaBuffer.toString());
            }


            List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery()
                    .eq(AdminUserWebsitRela::getAdminUserId, user.getAdminUserId()).list();
            if (list.size() > 0) {
                String adminCompanyId = list.get(0).getAdminWebsitId();
                AdminWebsit adminWebsit = adminWebsitService.getById(adminCompanyId);
                if (null != adminWebsit) {
                    row.add(adminWebsit.getName());
                } else {
                    row.add("");
                }
            } else {
                row.add("");
            }
            row.add(user.getCustomerName());
            row.add(user.getIsCustomerCompany()? "是" : "否");
            KingDeeCustomer king = kingDeeCustomerService.getOne(Wrappers.<KingDeeCustomer>lambdaQuery().eq(KingDeeCustomer::getId, user.getCustomerId()).last("limit 1"));
            if (null != king ) {
                KingDeeCustomer king1 = kingDeeCustomerService.getOne(Wrappers.<KingDeeCustomer>lambdaQuery().eq(KingDeeCustomer::getId, king.getParentId()).last("limit 1"));
                if (null != king1) {
                    row.add(king1.getName());
                } else {
                    row.add("");
                }
                row.add(king.getIsZr() ? "是" : "否");
            } else {
                row.add("");
                row.add("");
            }
            row.add(user.getDecodePwd());
            row.add(user.getStockCorrespondName());
            row.add(user.getLoginMobile());
            row.add(user.getBindCategoryName());
            row.add(user.getStatus()?"正常":"冻结");
            row.add(user.getIsCustomer()?user.getIsShangyong()?"是":"否":"");
            rows.add(row);
        }

        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }


    public AdminUser checkPlatformBind(String userName, String password, String timestamp, String sign) {
        String newSign = JiaSMUtil.jiasmDigest(userName + password, timestamp);
        if (!sign.equals(newSign)) {
            throw new RemoteServiceException("请求不合法");
        }
        AdminUser adminUser = adminUserService.lambdaQuery()
                .eq(AdminUser::getUserName, userName)
                .eq(AdminUser::getPassword, SecureUtil.md5(password))
                .one();
        if (adminUser == null) {
            throw new RemoteServiceException("帐号密码错误");
        }

        if (!adminUser.getStatus()) {
            throw new RemoteServiceException("帐号冻结中，请联系相关管理人员");
        }
        if (!adminUser.getBindEngin()) {
            throw new RemoteServiceException("当前经销商，未绑定工程系统账号");
        }
        return adminUser;
    }
    public void changing(Integer changeNum, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        adminUser.setChangeNum(changeNum);
        redisUtil.set(Constant.SUPPLY_CHANGE_NUM+adminUser.getAdminUserId(),Convert.toStr(changeNum));
        //部门帐号
        if(adminUser.getType().equals(0) || adminUser.getType().equals(1)){
            adminUser = commonLogic.websitAccount(adminUser, request);
        }

        //查询所有下级业务员
        if(!adminUser.getIsCustomer()){
            //List<String> allAdminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminUserCom.getAdminWebsitId());
            //List<String> serviceIds = adminMapper.queryChildServiceId(allAdminWebsitIds,Constant.NOT_DEL_ROLE_YWY);
            List<String> serviceIds = adminMapper.queryChildServiceId(adminUser.getAdminWebsitIds(),null,adminUser.getAdminWebsitId());
            adminUser.setServiceIds(serviceIds);
            //添加自己
            if(CollectionUtils.isEmpty(serviceIds)) {
                serviceIds = new ArrayList<>();
                serviceIds.add(adminUser.getAdminUserId());
                adminUser.setServiceIds(serviceIds);
            }
        }
        String token = CommonUtils.getToken(request);
        redisUtil.set(Constant.RedisPrefix.TOKEN_MGR + token, adminUser, 20 * 60 * 60 * 1000);
    }

    public IPage<AdminUserDto> listJiaXian(String adminWebsitId, String roleId, String customerId, Boolean isCustomer, Boolean isMaster, Boolean status, String userName, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        String roleName = "";

        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        List<String> adminWebsitIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(adminWebsitId)) {
            adminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminWebsitId);
        }else{
            adminWebsitIds = adminUser.getAdminWebsitIds();
        }

        if (adminUser.getIsCustomer()) {
            String websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            List<AdminWebsit> list = adminWebsitService.lambdaQuery().eq(AdminWebsit::getWebsitNumber, websitNumber).list();
            adminWebsitIds = list.stream().map(AdminWebsit::getAdminWebsitId).collect(Collectors.toList());
        }
        String websitNumber = "";
        if(isCustomer != null && !isCustomer){
            roleName = Constant.NOT_DEL_ROLE_YWY;
            if(adminUser.getAdminWebsit() != null) {
                websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            }
        }

        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getHigherPrantNumber, adminUser.getCustomerNumber())
                .select(KingDeeCustomer::getId).list();
        List<String> customerNumberS=new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (KingDeeCustomer kingDeeCustomer : list) {
                customerNumberS.add(kingDeeCustomer.getId());
            }
        }
        if (adminUser.getIsCustomer() && CollectionUtils.isEmpty(list) )
            return new Page<AdminUserDto>();

        List<String> customerNumbers = (isCustomer != null && !isCustomer) || (isMaster!= null && isMaster)?null:customerNumberS;
        IPage<AdminUserDto> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize),adminUser.getAdminCompanyIds(),adminWebsitIds,
                userName, null,null,null, status,roleId,isMaster,null,isCustomer,null,websitNumber,customerNumbers,1,null);

        return adminUserIPage;
    }

    public void addJiaXian(String userName, String password, String customerId) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String oldUserId = adminUser.getAdminUserId();
        String oldUserName = adminUser.getUserName();
        if(!adminUser.getIsCustomer()){
            throw new RemoteServiceException("非经销商帐号不可生成子账号");
        }
        AdminRole adminRole = adminRoleService.getById(Constant.SUPPLY_ROLE_CHILD_USER);
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(customerId);
        if (!kingDeeCustomer.getHigherPrantNumber().equals(adminUser.getCustomerNumber()))
            throw new RemoteServiceException("非该经销商子经销商帐号不可生成子账号");
        Integer count = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, kingDeeCustomer.getId()).count();
        String newUserName = kingDeeCustomer.getNumber() + (count < 10 ? "0"+count : count+1);
        //复制个小号出来
        adminUser.setAdminUserId("C"+IdWorker.getIdStr());

        adminUser.setUserName(newUserName);
        adminUser.setNickName(kingDeeCustomer.getName());

        adminUser.setRoleName(adminRole.getName());
        adminUser.setCustomerId(kingDeeCustomer.getId());
        adminUser.setCustomerName(kingDeeCustomer.getName());
        adminUser.setCustomerNumber(kingDeeCustomer.getNumber());
        adminUser.setRoleId(adminRole.getAdminRoleId());
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setIsMaster(false);
        adminUser.setDecodePwd(password);
        adminUser.setIsJiaxian(true);
        adminUser.insert();

        //复制部门出来
        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(list)){
            adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId,adminUser.getAdminUserId()).remove();
            for(AdminUserWebsitRela rela : list){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }

        //仓库权限
        List<AdminUserStock> stocks = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(stocks)){
            for (AdminUserStock stock : stocks) {
                stock.setId(null);
                stock.setAdminUserId(adminUser.getAdminUserId());
                stock.insert();
            }
        }
        //分类权限
        List<AdminUserCategoryRela> categoryRelas = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(categoryRelas)){
            for(AdminUserCategoryRela rela:categoryRelas){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }

    }

    public IPage<AdminUserDto> listGongCheng(String adminWebsitId, String roleId, String customerId, Boolean isCustomer, Boolean isMaster,
                                             Boolean status, String userName, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        String roleName = "";

        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        List<String> adminWebsitIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(adminWebsitId)) {
            adminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminWebsitId);
        }else{
            adminWebsitIds = adminUser.getAdminWebsitIds();
        }

        if (adminUser.getIsCustomer()) {
            String websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            List<AdminWebsit> list = adminWebsitService.lambdaQuery().eq(AdminWebsit::getWebsitNumber, websitNumber).list();
            adminWebsitIds = list.stream().map(AdminWebsit::getAdminWebsitId).collect(Collectors.toList());
        }
        String websitNumber = "";
        if(isCustomer != null && !isCustomer){
            roleName = Constant.NOT_DEL_ROLE_YWY;
            if(adminUser.getAdminWebsit() != null) {
                websitNumber = adminUser.getAdminWebsit().getWebsitNumber();
            }
        }

        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getHigherPrantNumber, adminUser.getCustomerNumber())
                .select(KingDeeCustomer::getId).list();
        List<String> customerNumberS=new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (KingDeeCustomer kingDeeCustomer : list) {
                customerNumberS.add(kingDeeCustomer.getId());
            }
        }
        if (adminUser.getIsCustomer() && CollectionUtils.isEmpty(list) )
            return new Page<AdminUserDto>();

        List<String> customerNumbers = (isCustomer != null && !isCustomer) || (isMaster!= null && isMaster)?null:customerNumberS;
        IPage<AdminUserDto> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize),adminUser.getAdminCompanyIds(),null,
                userName, null,null,null, status,roleId,isMaster,null,isCustomer,null,websitNumber,customerNumbers,0,1);

        return adminUserIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addGongCheng(String userName, String password, String customerId,String nickName,
                             Integer work_login_limit, Integer home_login_limit, Integer span_login_limit) {



        AdminUserCom adminUserKing = commonLogic.getAdminUser();
    /*    if (!adminUser.getIsCustomer())
            throw new RemoteServiceException("非经销商账号不可创建二级经销商");*/
        KingDeeCustomer byId = new KingDeeCustomer();
        if (adminUserKing.getIsCustomer()) {
            byId = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, adminUserKing.getCustomerNumber()).last("limit 1").one();
        }else {
            byId = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getId, customerId).last("limit 1").one();
        }

        byId.setHigherPrantNumber(byId.getNumber());
        byId.setHigherPrantName(byId.getName());


        Integer count = kingDeeCustomerService.lambdaQuery()
                .like(KingDeeCustomer::getNumber, "CUST" + byId.getNumber())
                .orderByDesc(KingDeeCustomer::getId).count();
        int num = count+1;
        String number = "CUST" + byId.getNumber();



        while (true){
            byId.setNumber(number+(num>9?num:"0"+num));
            if (kingDeeCustomerService.lambdaQuery()
                    .eq(KingDeeCustomer::getNumber, byId.getNumber()).count()>0) {
                num = num +1;
            }else {
                break;
            }
        }

        byId.setJiaxianType(CuseromtTypeEnum.GONGCHENG.getKey());
        byId.setId(IdWorker.getIdStr());
        byId.setName(nickName);
        byId.setExamineStatus(ExamineStatusEnum.OK.getKey());
        byId.setChargeName(byId.getChargeName());
        byId.setMobile(byId.getMobile());
        byId.setInvoiceAddress(byId.getInvoiceAddress());
        byId.setForbidStatus(byId.getForbidStatus());
        byId.setUrl(byId.getUrl());
        if (!com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(byId.getAfterNumber())) {
            byId.setAfterNumber(byId.getAfterNumber());
            byId.setBinding("YES");
            byId.setBindingName(adminUserKing.getNickName());
            byId.setBindingTime(new Date());
        }
        byId.insert();

        CustomerBillLimitConfig customerBillLimitConfig = new CustomerBillLimitConfig();
        customerBillLimitConfig.setCustomerId(byId.getId());
        customerBillLimitConfig.setCustomerNumber(byId.getNumber());
        customerBillLimitConfig.setWorkLoginLimit(work_login_limit);
        customerBillLimitConfig.setHomeLoginLimit(home_login_limit);
        customerBillLimitConfig.setSpanLoginLimit(span_login_limit);
        customerBillLimitConfig.setState(true);
        customerBillLimitConfig.insert();


        AdminUser adminUser = adminUserService.lambdaQuery()
                .eq(AdminUser::getCustomerNumber, byId.getNumber()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
        if (adminUser == null){
             adminUser = adminUserService.lambdaQuery()
                    .eq(AdminUser::getRoleName,"经销商").eq(AdminUser::getIsMaster, true).last("limit 1").one();
        }

        String oldUserId = adminUser.getAdminUserId();
        String oldUserName = adminUser.getUserName();


        AdminRole adminRole = adminRoleService.getById(Constant.SUPPLY_ROLE_CHILD_GONGCHENG);


        //复制个小号出来
        adminUser.setAdminUserId(IdWorker.getIdStr());

        adminUser.setUserName(byId.getNumber());
        adminUser.setNickName(nickName);

        adminUser.setRoleName(adminRole.getName());
        adminUser.setCustomerId(byId.getId());
        adminUser.setCustomerName(byId.getName());
        adminUser.setCustomerNumber(byId.getNumber());
        adminUser.setRoleId(adminRole.getAdminRoleId());
        adminUser.setPassword(SecureUtil.md5(password));
        adminUser.setIsMaster(false);
        adminUser.setDecodePwd(password);
        adminUser.setIsGongcheng(true);
        adminUser.insert();

        //复制部门出来
        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(list)){
            adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId,adminUser.getAdminUserId()).remove();
            for(AdminUserWebsitRela rela : list){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }

        //仓库权限
        List<AdminUserStock> stocks = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(stocks)){
            for (AdminUserStock stock : stocks) {
                stock.setId(null);
                stock.setAdminUserId(adminUser.getAdminUserId());
                stock.insert();
            }
        }
        //分类权限
        List<AdminUserCategoryRela> categoryRelas = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId, oldUserId).list();
        if(CollectionUtils.isNotEmpty(categoryRelas)){
            for(AdminUserCategoryRela rela:categoryRelas){
                rela.setId(null);
                rela.setAdminUserId(adminUser.getAdminUserId());
                rela.insert();
            }
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void updateGongCheng(String adminUserId, String nickName, Integer workLoginLimit, Integer homeLoginLimit,
                                Integer spanLoginLimit) {
        AdminUser adminUser = adminUserService.getById(adminUserId);
        adminUser.setNickName(nickName);
        adminUser.updateById();

        kingDeeCustomerService.lambdaUpdate()
                .eq(KingDeeCustomer::getNumber,adminUser.getCustomerNumber())
                .set(KingDeeCustomer::getName,nickName)
                .update();

        customerBillLimitConfigService
                .lambdaUpdate()
                .eq(CustomerBillLimitConfig::getCustomerId,adminUser.getCustomerId())
                .set(CustomerBillLimitConfig::getWorkLoginLimit,workLoginLimit)
                .set(CustomerBillLimitConfig::getHomeLoginLimit,homeLoginLimit)
                .set(CustomerBillLimitConfig::getSpanLoginLimit,spanLoginLimit)
                .update();

        tradeLoginOrderService
                .lambdaUpdate()
                .eq(TradeLoginOrder::getCustomerId,adminUser.getCustomerId())
                .set(TradeLoginOrder::getCustomerName,nickName)
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    public AdminUserDto detailGongCheng(String adminUserId) {
        AdminUserDto adminUserDto = BeanUtil.toBean(adminUserService.getById(adminUserId), AdminUserDto.class);
        CustomerBillLimitConfig customerBillLimitConfig = customerBillLimitConfigService
                .lambdaQuery()
                .eq(CustomerBillLimitConfig::getCustomerId, adminUserDto.getCustomerId())
                .last("limit 1").one();

        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUserDto.getCustomerId());
        KingDeeCustomer kingCustomer = kingDeeCustomerService.lambdaQuery().
                eq(KingDeeCustomer::getNumber,kingDeeCustomer.getHigherPrantNumber()).one();
        if (customerBillLimitConfig != null) {
            adminUserDto.setWorkLoginLimit(customerBillLimitConfig.getWorkLoginLimit());
            adminUserDto.setHomeLoginLimit(customerBillLimitConfig.getHomeLoginLimit());
            adminUserDto.setSpanLoginLimit(customerBillLimitConfig.getSpanLoginLimit());
        }

        adminUserDto.setParentId(kingCustomer.getId());
        return adminUserDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delGongCheng(String userName) {
        AdminUser adminUser = adminMapper.selectByUserName(userName);
        kingDeeCustomerService.lambdaUpdate().eq(KingDeeCustomer::getNumber,adminUser.getCustomerNumber()).remove();
        adminMapper.delByUserName(userName);

    }

    @Transactional(rollbackFor = Exception.class)
    public void importData(InputStream inputStream, HttpServletRequest request) {

        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("工程登录名额", "barCode");
        reader.addHeaderAlias("家装登录名额", "specification");
        reader.addHeaderAlias("跨区登录名额", "id");
        reader.addHeaderAlias("上级经销商", "salesCompany");
        reader.addHeaderAlias("子经销商名称", "address");
        reader.addHeaderAlias("密码", "materialType");

        List<CustomerCode> customerCodes = reader.readAll(CustomerCode.class);

        for (CustomerCode customerCode : customerCodes) {

            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getName, customerCode.getSalesCompany()).last("limit 1").one();

            if (kingDeeCustomer == null)
                throw new RemoteServiceException(customerCode.getSalesCompany());

            this.addGongCheng(null,"123456",kingDeeCustomer.getId(),customerCode.getAddress(),
                    Convert.toInt(customerCode.getBarCode()),Convert.toInt(customerCode.getSpecification()),Convert.toInt(customerCode.getId()));
        }
    }

    public IPage<AdminUserDto> listService(String adminWebsitId, String roleId, String customerId, Boolean isCustomer, Boolean isMaster, Boolean status, String userName, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        List<String> roleName = new ArrayList<>();


        roleName.add(Constant.NOT_DEL_SHANGYONG_ROLE_YWY);

        IPage<AdminUserDto> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize),null,null,
                userName, null,null,null, status,roleId,isMaster,customerId,isCustomer,roleName,null,null,null,null);

        return adminUserIPage;
    }

    public void addChildUserSync() {

        List<AdminUser> adminUserList = adminUserService.lambdaQuery().eq(AdminUser::getIsCustomer, true)
                .eq(AdminUser::getIsMaster, true).list();

        for (AdminUser adminUser : adminUserList) {

            List<AdminUser> adminUserListZi = adminUserService.lambdaQuery().eq(AdminUser::getIsCustomer, true)
                    .eq(AdminUser::getIsMaster, false)
                    .eq(AdminUser::getCustomerId, adminUser.getCustomerId())
                    .list();

            for (AdminUser user : adminUserListZi) {
                //仓库权限
                List<AdminUserStock> stocks = adminUserStockService.lambdaQuery()
                        .eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();


                adminUserStockService.lambdaUpdate().eq(AdminUserStock::getAdminUserId,user.getAdminUserId()).remove();

                if(CollectionUtils.isNotEmpty(stocks)){
                    for (AdminUserStock stock : stocks) {
                        stock.setId(null);
                        stock.setAdminUserId(user.getAdminUserId());
                        stock.insert();
                    }
                }
                //分类权限
                List<AdminUserCategoryRela> categoryRelas = adminUserCategoryRelaService.lambdaQuery()
                        .eq(AdminUserCategoryRela::getAdminUserId, adminUser.getAdminUserId()).list();

                adminUserCategoryRelaService.lambdaUpdate()
                        .eq(AdminUserCategoryRela::getAdminUserId, user.getAdminUserId()).remove();

                if(CollectionUtils.isNotEmpty(categoryRelas)){
                    for(AdminUserCategoryRela rela:categoryRelas){
                        rela.setId(null);
                        rela.setAdminUserId(user.getAdminUserId());
                        rela.insert();
                    }
                }
            }

        }


    }
}
