package com.testor.module.ZLOA.sysUserOA.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.auth.AuthEnumCode;
import com.testor.biz.auth.model.LoginParam;
import com.testor.biz.auth.model.TokenResponse;
import com.testor.biz.auth.model.UserInfo;
import com.testor.biz.auth.model.UserInfoResponse;
import com.testor.biz.auth.service.AuthService;
import com.testor.biz.excel.ExcelEnum;
import com.testor.biz.sys.org.OrgEnumCode;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.model.dto.DeptAndPost;
import com.testor.biz.sys.org.model.dto.SysOrgCreateAndUpdateRequest;
import com.testor.biz.sys.org.model.dto.SysOrgParam;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.model.dto.TSysPostParam;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.role.service.SysRoleService;
import com.testor.biz.sys.user.UserHelper;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.model.dto.SysUserListResponse;
import com.testor.biz.sys.user.model.dto.SysUserParam;
import com.testor.biz.sys.user.model.dto.UserExport;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.util.AESEncryptionUtil;
import com.testor.module.ZLOA.sysUserOA.model.dto.LoginDto;
import com.testor.module.ZLOA.sysUserOA.service.TSysUserOaService;
import com.testor.module.sys.SysOrgVO;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.AccountLockService;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.module.video.model.domain.TSysUserImpotParam;
import com.testor.module.video.util.Beans;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.jwt.JwtHelper;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.request.RequestUtil;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import com.tongtech.tfw.backend.core.helper.datetime.DatetimeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @title TSysLoginController
 * @description <TODO description class purpose>
 * @Author: qiao
 * @version:1.0.0
 * @create：4/19/23 6:16 PM
 */
@Validated
@RestController
@Api(value = "Login Controller", tags = {"登录模块"})
@RequestMapping({"/sys"})
@Slf4j
public class TSysLoginController extends SuperController {

    @Autowired
    private TSysUserOaService userOaService;

    @Autowired
    private AuthService authService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private NewSysOrgService newSysOrgService;

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @Autowired
    private TSysPostService tSysPostService;

    @Autowired
    private AccountLockService accountLockService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysRoleService roleService;

    //    @ApiOperation(
//            value = "用户登录",
//            notes = "User Login 用户登录"
//    )
//    @PostMapping({"/login/adOne"})
    public BaseResponse<TokenResponse> adOne(@RequestBody LoginParam loginParam) {
        BaseResponse<TokenResponse> baseResponse = new BaseResponse();
        //ToDo ad账号验证
        Boolean aBoolean = getalarmPictureOne(loginParam.getLoginname(), loginParam.getPassword());
        if (aBoolean) {
            SysUser sysUser = this.authService.login(loginParam.getLoginname());
            if (ObjectHelper.isNotEmpty(sysUser)) {
                if (!"0".equals(sysUser.getStatus())) {
                    throw new ApiException(AuthEnumCode.STATUS.transform());
                } else {
                    UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                    String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);
                    baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
                    ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                            this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                            .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                            .eq(SysUser::getUserId, sysUser.getUserId())).update();
                    return baseResponse;
                }
            } else {
                throw new ApiException(AuthEnumCode.USERNAME.transform());
            }
        }


        String loginName = loginParam.getLoginname();
        String password = UserHelper.userPassword(loginParam.getPassword());
        if (StringHelper.isNotEmpty(loginName) && StringHelper.isNotEmpty(password)) {
            SysUser sysUser = this.authService.login(loginName);
            if (ObjectHelper.isNotEmpty(sysUser)) {
                if (!password.equals(sysUser.getLoginPwd())) {
                    throw new ApiException(AuthEnumCode.PASSWORD.transform());
                } else if (!"0".equals(sysUser.getStatus())) {
                    throw new ApiException(AuthEnumCode.STATUS.transform());
                } else {
                    UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                    String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);
                    baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
                    ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                            this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                            .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                            .eq(SysUser::getUserId, sysUser.getUserId())).update();
                    return baseResponse;
                }
            } else {
                throw new ApiException(AuthEnumCode.USERNAME.transform());
            }
        } else {
            throw new ApiException(AuthEnumCode.USERNAME.transform());
        }
    }

    //    @ApiOperation(
//            value = "用户登录",
//            notes = "User Login 用户登录"
//    )
//    @PostMapping({"/login/adTwo"})
    public BaseResponse<TokenResponse> login(@RequestBody LoginParam loginParam) {
        BaseResponse<TokenResponse> baseResponse = new BaseResponse();
        //ToDo ad账号验证
        Boolean aBoolean = getalarmPictureTwo(loginParam.getLoginname(), loginParam.getPassword());
        if (aBoolean) {
            SysUser sysUser = this.authService.login(loginParam.getLoginname());
            if (ObjectHelper.isNotEmpty(sysUser)) {
                if (!"0".equals(sysUser.getStatus())) {
                    throw new ApiException(AuthEnumCode.STATUS.transform());
                } else {
                    UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                    String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);
                    baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
                    ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                            this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                            .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                            .eq(SysUser::getUserId, sysUser.getUserId())).update();
                    return baseResponse;
                }
            } else {
                throw new ApiException(AuthEnumCode.USERNAME.transform());
            }
        }


        String loginName = loginParam.getLoginname();
        String password = UserHelper.userPassword(loginParam.getPassword());
        if (StringHelper.isNotEmpty(loginName) && StringHelper.isNotEmpty(password)) {
            SysUser sysUser = this.authService.login(loginName);
            if (ObjectHelper.isNotEmpty(sysUser)) {
                if (!password.equals(sysUser.getLoginPwd())) {
                    throw new ApiException(AuthEnumCode.PASSWORD.transform());
                } else if (!"0".equals(sysUser.getStatus())) {
                    throw new ApiException(AuthEnumCode.STATUS.transform());
                } else {
                    UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                    String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);
                    baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
                    ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                            this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                            .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                            .eq(SysUser::getUserId, sysUser.getUserId())).update();
                    return baseResponse;
                }
            } else {
                throw new ApiException(AuthEnumCode.USERNAME.transform());
            }
        } else {
            throw new ApiException(AuthEnumCode.USERNAME.transform());
        }
    }

    @ApiOperation(
            value = "用户登录",
            notes = "User Login 用户登录"
    )
    @PostMapping({"/login/adThree"})
    public BaseResponse<TokenResponse> adThree(@Validated @RequestBody LoginDto loginParam) {
        //if(StringUtils.isNotBlank(loginParam.getType()) && loginParam.getType().equals("1")){
            String loginName = loginParam.getLoginname();
            String password = UserHelper.userPassword(loginParam.getPassword());

            if (StringHelper.isEmpty(loginName)) {
                throw new ApiException(ResponseInfo.builder().code(721).msg("账号不能为空").build());
            }
            if (StringHelper.isEmpty(loginParam.getPassword())) {
                throw new ApiException(ResponseInfo.builder().code(721).msg("密码不能为空").build());
            }

            verifyThePassword(loginParam.getPassword());

            //校验验证码
            accountLockService.checkDefaultKaptcha(loginParam.getUuid(), loginParam.getCaptcha());
            String username = loginParam.getLoginname();
            String ip = RequestUtil.getIpAddr(RequestUtil.getRequest());

            if (accountLockService.isLocked(username)) {
                // 账号或 IP 已被锁定，给出相应提示
                throw new ApiException(ResponseInfo.builder().code(721).msg("输入密码错误次数过多，账号已被锁定").build());
            }
            //if (accountLockService.isLocked(ip)) {
            // IP 已被锁定，给出相应提示
            //   throw new ApiException(ResponseInfo.builder().code(721).msg("输入密码错误次数过多，IP已被锁定").build());
            //}

            BaseResponse<TokenResponse> baseResponse = new BaseResponse();
            //ToDo ad账号验证
            Boolean aBoolean = getalarmPictureThree(loginParam.getLoginname(), loginParam.getPassword());
            if (aBoolean) {
                SysUser sysUser = this.authService.login(loginParam.getLoginname());
                if (ObjectHelper.isNotEmpty(sysUser)) {
                    if (!"0".equals(sysUser.getStatus())) {
                        throw new ApiException(AuthEnumCode.STATUS.transform());
                    } else {
                        UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                        String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);
                        baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
                        ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                                this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                                .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                                .eq(SysUser::getUserId, sysUser.getUserId())).update();
                        //重置锁定次数
                        accountLockService.resetAttempts(ip);
                        accountLockService.resetAttempts(username);
                        return baseResponse;
                    }
                } else {
                    //ip锁定增加次数
                    accountLockService.increaseAttempts(ip);
                    throw new ApiException(AuthEnumCode.USERNAME.transform());
                }
            }


            SysUser sysUser = this.authService.login(loginName);
            if (ObjectHelper.isNotEmpty(sysUser)) {
                if (!password.equals(sysUser.getLoginPwd())) {
                    //锁定增加次数
                    accountLockService.increaseAttempts(username);
                    accountLockService.increaseAttempts(ip);
                    throw new ApiException(ResponseInfo.builder().code(721).msg("账号或密码输入错误"+accountLockService.getAttempts(username)+"次，输入3次错误密码锁定账号15分钟").build());
                } else if (!"0".equals(sysUser.getStatus())) {
                    throw new ApiException(AuthEnumCode.STATUS.transform());
                } else {
                    UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
                    String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), sysUser.getUserId(), JSON.toJSONString(userInfoResponse.getUserInfo()), "Token Issuer", "", 36000L);

                    String regex = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,}$";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(loginParam.getPassword());
                    TokenResponse build = TokenResponse.builder().token(jwt).expired(36000L).build();
                    if (!matcher.matches()) {
                        baseResponse.setCode(703);
                        baseResponse.setMsg("检测到您的密码为弱密码，请修改密码");
                        build = TokenResponse.builder().token(jwt).expired(36000L).build();
                        baseResponse.setData(build);
                    } else if (loginParam.getPassword().equals("ZLmy1110!@#$%^&*")) {
                        baseResponse.setCode(703);
                        baseResponse.setMsg("检测到您的密码为默认密码，请修改密码");
                        build = TokenResponse.builder().token(jwt).expired(36000L).build();
                        baseResponse.setData(build);
                    } else {
                        baseResponse.setData(build);
                    }
                    ((LambdaUpdateChainWrapper) ((LambdaUpdateChainWrapper<SysUser>) ((LambdaUpdateChainWrapper<SysUser>)
                            this.sysUserService.lambdaUpdate().set(SysUser::getLoginDate, new Date()))
                            .set(SysUser::getLoginIp, RequestUtil.getIpAddr(RequestUtil.getRequest())))
                            .eq(SysUser::getUserId, sysUser.getUserId())).update();
                    //重置锁定次数
                    accountLockService.resetAttempts(ip);
                    accountLockService.resetAttempts(username);
                    return baseResponse;
                }
            } else {
                accountLockService.increaseAttempts(ip);
                throw new ApiException(AuthEnumCode.USERNAME.transform());
            }
        //}else {
            //throw new ApiException(ResponseInfo.builder().code(721).msg("不再支持浏览器和中粮贸易移动助手登录，请在E+内访问此系统").build());
        //}

}

    @SneakyThrows
    @ApiOperation(
            value = "获取token",
            notes = "获取token"
    )
    @PostMapping({"/getToken"})
    public BaseResponse getToken(@RequestBody Map<String, String> requestData) {
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        SecretKey secretKey = new SecretKeySpec(AESEncryptionUtil.getSecretKry().getBytes(), "AES");
        String encryptedData = requestData.get("data");
        String decryptedData = AESEncryptionUtil.decrypt(encryptedData, secretKey);

        // 处理解密后的数据
        System.out.println("解密数据： " + decryptedData);
        UserInfo userInfo = new UserInfo();
        userInfo.setOrgId(decryptedData);
        String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), "147258", JSON.toJSONString(userInfo), "Token Issuer", "", 36000L);
        String encryptedResponse = AESEncryptionUtil.encrypt(jwt, secretKey);
        baseResponse.setData(encryptedResponse);
        return baseResponse;
    }

    public static void main(String[] args) throws Exception {
        SecretKey secretKey = new SecretKeySpec(AESEncryptionUtil.getSecretKry().getBytes(), "AES");
        //要加密的数据
        String dataToSend = "0af16801d6834133a56c4b0c4c4194db";
        //加密
        String encryptedData = AESEncryptionUtil.encrypt(dataToSend, secretKey);
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://127.0.0.1:18083/sys/getToken";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, String> requestData = new HashMap<>();
        requestData.put("data", encryptedData);
        HttpEntity<Map<String, String>> request = new HttpEntity<>(requestData, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println(response.getBody());
            String encryptedResponseData = (String) response.getBody().get("data");
            //解密数据
            String decryptedResponseData = AESEncryptionUtil.decrypt(encryptedResponseData, secretKey);
            System.out.println("解密的响应数据: " + decryptedResponseData);
        }
    }

    private void verifyThePassword(String password) {
        if (password.length() < 6 || password.length() > 18) {
            throw new ApiException(ResponseInfo.builder().code(721).msg("密码格式错误").build());
        }
    }


    /**
     * 生成图形验证码
     */
    @GetMapping("/login/kaptcha")
    public BaseResponse getKaptcha(HttpServletResponse response, HttpSession session) {
        BaseResponse baseResponse = new BaseResponse();
        Map<String, Object> kaptcha = accountLockService.getKaptcha(response, session);
        baseResponse.setData(kaptcha);
        return baseResponse;
    }

    @PostMapping("/sysUserImport")
    @ApiOperation(value = "用户批量导入", notes = "")
    public void imports(@RequestParam("file") MultipartFile file) throws Exception {
        userOaService.imports(request, response, file);
    }

    @PostMapping("/sysUserImports")
    @ApiOperation(value = "用户批量导入(带部门岗位)", notes = "")
    public BaseResponse sysUserImports(@RequestParam("file") MultipartFile file) throws Exception {
        List<TSysUserImpotParam> tSysUserImpotParams = userOaService.sysUserImports(request, response, file);
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setData(tSysUserImpotParams);
        return baseResponse;
    }

    @PostMapping("/sysVideoImport")
    @ApiOperation(value = "设备导入", notes = "")
    public void sysVideoImport(@RequestParam("file") MultipartFile file) throws Exception {
        userOaService.sysVideoImport(request, response, file);
    }

    public Boolean getalarmPictureOne(String userName, String password) {
        Boolean b = false;
        String url = new String("ldap://" + "cofco.com" + ":" + "389");
        Hashtable<String, String> env = new Hashtable<String, String>();//实例化一个Env
        DirContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式，这么写就行
//        env.put(Context.SECURITY_PRINCIPAL, userName); //用户名
        env.put(Context.SECURITY_PRINCIPAL, "cofco\\\\" + userName); //用户名
        env.put(Context.SECURITY_CREDENTIALS, password);//密码
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
        env.put(Context.PROVIDER_URL, url);//Url

        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            b = true;
            log.info("身份验证成功");
        } catch (AuthenticationException e) {
            b = false;
            log.error("身份验证失败{}", e);
        } catch (javax.naming.CommunicationException e) {
            b = false;
            log.error("AD域连接失败{}", e);
        } catch (Exception e) {
            b = false;
            log.error("身份验证未知异常{}", e);
        } finally {
            try {
                ctx.close();
            } catch (Exception e) {
                System.out.println("关闭失败，对象为空");
                e.printStackTrace();
            }
        }

        return b;
    }

    public Boolean getalarmPictureThree(String userName, String password) {
        Boolean b = false;
        String url = new String("ldap://" + "cofco.com" + ":" + "389");
        Hashtable<String, String> env = new Hashtable<String, String>();//实例化一个Env
        DirContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式，这么写就行
        //        env.put(Context.SECURITY_PRINCIPAL, userName); //用户名
        env.put(Context.SECURITY_PRINCIPAL, "cofco\\" + userName); //用户名
        env.put(Context.SECURITY_CREDENTIALS, password);//密码
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
        env.put(Context.PROVIDER_URL, url);//Url

        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            b = true;
            log.info("身份验证成功");
        } catch (AuthenticationException e) {
            b = false;
            log.error("身份验证失败{}", e);
        } catch (javax.naming.CommunicationException e) {
            b = false;
            log.error("AD域连接失败{}", e);
        } catch (Exception e) {
            b = false;
            log.error("身份验证未知异常{}", e);
        } finally {
            try {
                ctx.close();
            } catch (Exception e) {
                System.out.println("关闭失败，对象为空");
                e.printStackTrace();
            }
        }

        return b;
    }

    public Boolean getalarmPictureTwo(String userName, String password) {
        Boolean b = false;
        String url = new String("ldap://" + "cofco.com" + ":" + "389");
        Hashtable<String, String> env = new Hashtable<String, String>();//实例化一个Env
        DirContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式，这么写就行
//        env.put(Context.SECURITY_PRINCIPAL, userName); //用户名
        env.put(Context.SECURITY_PRINCIPAL, "UID=" + userName + ",OU=中国粮油食品(集团)有限公司,DC=cofco,DC=com"); //用户名
        env.put(Context.SECURITY_CREDENTIALS, password);//密码
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
        env.put(Context.PROVIDER_URL, url);//Url

        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            b = true;
            log.info("身份验证成功");
        } catch (AuthenticationException e) {
            b = false;
            log.error("身份验证失败{}", e);
        } catch (javax.naming.CommunicationException e) {
            b = false;
            log.error("AD域连接失败{}", e);
        } catch (Exception e) {
            b = false;
            log.error("身份验证未知异常{}", e);
        } finally {
            try {
                ctx.close();
            } catch (Exception e) {
                System.out.println("关闭失败，对象为空");
                e.printStackTrace();
            }
        }

        return b;
    }

    @ApiOperation(
            value = "根据机构ID查询机构",
            notes = "根据机构ID查询机构"
    )
    @GetMapping({"/getByOrgId"})
    public BaseResponse<SysOrgVO> getByOrgId(String orgId) {
        BaseResponse<SysOrgVO> baseResponse = new BaseResponse();
        if (StringHelper.isEmpty(orgId)) {
            throw new ApiException(OrgEnumCode.REQUIRED_ITEMS_MISSING.transform());
        } else {
            NewSysOrg sysOrg = newSysOrgService.getById(orgId);
            if (ObjectHelper.isEmpty(sysOrg)) {
                throw new ApiException(OrgEnumCode.ORG_ID_NOT_EXISTENT.transform());
            } else {
                SysOrgVO sysOrgVO = Beans.objectToBean(sysOrg, SysOrgVO.class);
                if (!StringHelper.isEmpty(sysOrgVO.getParentId()) && !"0".equals(sysOrgVO.getParentId())) {
                    SysOrg parentOrg = sysOrgService.getById(sysOrg.getParentId());
                    sysOrgVO.setParentOrgName(parentOrg.getOrgName());
                } else {
                    sysOrgVO.setParentOrgName("");
                }

                baseResponse.setData(sysOrgVO);
                return baseResponse;
            }
        }
    }

    @ApiOperation(
            value = "【新增机构信息及部门信息】",
            notes = "新增机构信息及部门信息， 如果新增部门 isDept传 1 新增机构传 0"
    )
    @PostMapping({"/org/add"})
    public BaseResponse<SysOrg> addEntity(@Valid @RequestBody SysOrgCreateAndUpdateRequest addRequest) throws Exception {
        BaseResponse<SysOrg> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new ApiException(OrgEnumCode.ORG_PARAM_IS_NULL.transform());
        } else {
            List<SysOrg> sysOrgList = this.sysOrgService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("org_code", addRequest.getOrgCode())).ne("status", "1"));
            if (!ObjectHelper.isEmpty(sysOrgList)) {
                throw new ApiException(OrgEnumCode.ORG_CODE_ALREADY_EXISTS.transform());
            } else {
                String parentId = addRequest.getParentId();
                if (!StringHelper.isEmpty(parentId) && !"0".equals(parentId)) {
                    SysOrg parentOrg = (SysOrg) this.sysOrgService.getById(parentId);
                    addRequest.setParentIds(parentOrg.getParentIds() + "," + parentOrg.getOrgId());
                } else {
                    addRequest.setParentId("0");
                    addRequest.setParentIds("0");
                }
                int count = sysOrgService.count(new QueryWrapper<SysOrg>().eq("is_dept", addRequest.getIsDept()).eq("org_name", addRequest.getOrgName())
                        .eq("parent_id", addRequest.getParentId()).ne("status", "1"));
                if (count > 0) {
                    throw new ApiException(OrgEnumCode.ORG_NAME_ALREADY_EXISTS.transform());
                } else {
                    SysOrg data = (SysOrg) BeanHelper.beanToBean(addRequest, SysOrg.class);
                    String bit = IdHelper.getId32bit();
                    data.setOrgId(bit);
                    boolean flag = this.sysOrgService.save(data);
                    if (flag) {
                        if ("0".equals(addRequest.getIsDept())) {
                            SysOrg sysOrg = new SysOrg();
                            String parent = addRequest.getParentId();
                            if (!StringHelper.isEmpty(parent) && !"0".equals(parent)) {
                                SysOrg parentOrg = (SysOrg) this.sysOrgService.getById(parent);
                                sysOrg.setParentId(bit);
                                sysOrg.setParentIds(parentOrg.getParentIds() + "," + parentOrg.getOrgId() + "," + bit);
                            } else {
                                sysOrg.setParentId("0");
                                sysOrg.setParentIds("0");
                            }

                            String dept = IdHelper.getId32bit();
                            sysOrg.setOrgId(dept);
                            sysOrg.setOrgName("安全环保部");
                            sysOrg.setIsDept("1");
                            this.sysOrgService.save(sysOrg);
                            TSysPostParam tSysPostParam = new TSysPostParam();
                            tSysPostParam.setDeptId(dept);
                            List<TSysPost> posts = new ArrayList();
                            TSysPost tSysPost = new TSysPost();
                            tSysPost.setPostName("安全生产岗");
                            posts.add(tSysPost);
                            tSysPostParam.setTSysPosts(posts);
                            this.tSysPostService.addEntity(tSysPostParam);
                        }

                        baseResponse.setData(data);
                    }

                    return baseResponse;
                }
            }
        }
    }

    @ApiOperation(
            value = "【根据机构id获取子部门及岗位】",
            notes = "根据机构id获取子部门及岗位"
    )
    @GetMapping({"/getDeptAndPost"})
    public BaseResponse<BaseResponseList<DeptAndPost>> getDeptAndPost(SysOrgParam param) {
        BaseResponse<BaseResponseList<DeptAndPost>> baseResponse = new BaseResponse();
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<SysOrg> resultPage = new Page(page, limit);
        QueryWrapper<SysOrg> queryWrapper = this.getPost(param);
        Page<SysOrg> resultList = (Page) this.sysOrgService.page(resultPage, queryWrapper);
        BaseResponseList<DeptAndPost> baseResponseList = new BaseResponseList();
        List<SysOrg> records = resultList.getRecords();
        List<DeptAndPost> deptAndPosts = new ArrayList();
        Iterator var11 = records.iterator();

        /*while (var11.hasNext()) {
            SysOrg record = (SysOrg) var11.next();
            DeptAndPost deptAndPost = (DeptAndPost) BeanHelper.beanToBean(record, DeptAndPost.class);
            String orgId = deptAndPost.getOrgId();
            List<TSysPost> list = this.tSysPostService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("dept_id", orgId)).ne("status", "1"));
            deptAndPost.setTSysPosts(list);
            deptAndPosts.add(deptAndPost);
        }*/

        while (var11.hasNext()) {
            SysOrg record = (SysOrg) var11.next();
            DeptAndPost deptAndPost = BeanHelper.beanToBean(record, DeptAndPost.class);
            String orgId = deptAndPost.getOrgId();

            // 使用旧版排序方式
            List<TSysPost> list = this.tSysPostService.list(
                    new QueryWrapper<TSysPost>()
                            .eq("dept_id", orgId)
                            .ne("status", "1")
                            .orderBy(true, false, "create_date")  // 降序排序
            );

            deptAndPost.setTSysPosts(list);
            deptAndPosts.add(deptAndPost);
        }

        baseResponseList.setData(deptAndPosts);
        baseResponseList.setTotal(this.sysOrgService.count(queryWrapper) + "");
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    public QueryWrapper<SysOrg> getPost(SysOrgParam param) {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper();
        if (!StringHelper.isEmpty(param.getOrgId())) {
            ((QueryWrapper) queryWrapper.and((i) -> {
                QueryWrapper var10000 = (QueryWrapper) ((QueryWrapper) ((QueryWrapper) i.eq("org_id", param.getOrgId())).or()).like("parent_id", param.getOrgId());
            })).eq("is_dept", "1");
            queryWrapper.ne("status", "1");
        }

        if (StringHelper.isNotEmpty(param.getOrgName())) {
            queryWrapper.like("org_name", param.getOrgName());
        }

        return queryWrapper;
    }

    @ApiOperation(
            value = "用户导出",
            notes = "用户导出 export user data"
    )
    @GetMapping({"/export"})
    public void exportAllEntity(SysUserParam params, @RequestParam(value = "cols", required = false) List<String> cols, @RequestParam(value = "ids", required = false) List<String> ids, HttpServletResponse response) {
        SysUserParam param = (SysUserParam) ObjectHelper.defaultIfNull(params, new SysUserParam());
        if (StringHelper.isBlank(param.getOrgId())) {
            param.setOrgId((this.sysUserService.getById(this.getUserId())).getOrgId());
        }

        QueryWrapper<SysUser> queryWrapper = this.createQuery(param);
        if (ObjectHelper.isNotEmpty(ids) && !ids.isEmpty()) {
            queryWrapper.in("user_id", ids);
        }

        List<SysUser> resultList = this.sysUserService.list(queryWrapper);
        List<SysUserListResponse> records = resultList.stream().map(b -> {
            return Beans.objectToBean(b, SysUserListResponse.class);
        }).collect(Collectors.toList());
        List<UserExport> userExports = records.stream().map((e) -> {
            return Beans.objectToBean(e, UserExport.class);
        }).peek(UserExport::convertSex).collect(Collectors.toList());
        Iterator var10 = userExports.iterator();

        while (var10.hasNext()) {
            UserExport userExport = (UserExport) var10.next();
            userExport.setOrgName(this.sysOrgService.getOrgFullPathName(userExport.getOrgId()));
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("用户信息数据-" + DatetimeHelper.getDateTime8Length(), "UTF-8");
            fileName = StringHelper.replace(fileName, "+", "%20");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            if (ObjectHelper.isNotEmpty(cols)) {
                Set<String> includeColumnFiledNames = new HashSet(cols);
                ((ExcelWriterBuilder) EasyExcel.write(out, UserExport.class).includeColumnFiledNames(includeColumnFiledNames)).sheet("数据").doWrite(userExports);
                out.flush();
                out.close();
            } else {
                EasyExcel.write(out, UserExport.class).sheet("数据").doWrite(userExports);
                out.flush();
                out.close();
            }
        } catch (IOException var12) {
            log.error("Export Error ", var12);
            throw new ApiException(ExcelEnum.EXPORT_ERROR.transform());
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    private QueryWrapper<SysUser> createQuery(SysUserParam queryParam) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
        if (!StringHelper.isEmpty(queryParam.getLoginName())) {
            queryWrapper.like("login_name", queryParam.getLoginName());
        }

        if (!StringHelper.isEmpty(queryParam.getUserName())) {
            queryWrapper.like("user_name", queryParam.getUserName());
        }

        if (!StringHelper.isEmpty(queryParam.getPhoneNo())) {
            queryWrapper.like("phone_no", queryParam.getPhoneNo());
        }

        if (!StringHelper.isEmpty(queryParam.getUserType())) {
            queryWrapper.eq("user_type", queryParam.getUserType());
        }

        if (!StringHelper.isEmpty(queryParam.getOrgId())) {
            List<String> orgList = (List) this.sysOrgService.getChildrenById(queryParam.getOrgId()).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            if (orgList.isEmpty()) {
                queryWrapper.eq("org_id", queryParam.getOrgId());
            } else {
                orgList.add(queryParam.getOrgId());
                queryWrapper.in("org_id", orgList);
            }
        }

        if (StringHelper.isEmpty(queryParam.getStatus())) {
            queryWrapper.in("status", Arrays.asList("0", "2"));
        } else if (!"1".equals(queryParam.getStatus())) {
            queryWrapper.eq("status", queryParam.getStatus());
        }

        if (!StringHelper.isEmpty(queryParam.getOrderBy())) {
            if (!StringHelper.isEmpty(queryParam.getOrderType()) && "asc".equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc("user_name");
        }

        return queryWrapper;
    }

}
