package com.testor.module.sys.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.file.FileEnumCode;
import com.testor.biz.file.model.domain.TSysFileBiz;
import com.testor.biz.file.service.TSysFileBizService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.role.model.domain.SysRole;
import com.testor.biz.sys.role.service.SysRoleService;
import com.testor.biz.sys.user.UserEnumCode;
import com.testor.biz.sys.user.UserHelper;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.model.dto.SysUserDeleteBatchRequest;
import com.testor.biz.sys.user.model.dto.SysUserDeleteRequest;
import com.testor.biz.sys.user.model.dto.UserImport;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.biz.sys.userRole.model.domain.SysUserRole;
import com.testor.biz.sys.userRole.service.SysUserRoleService;
import com.testor.biz.sys.userposition.service.TSysUserPositionService;
import com.testor.common.constant.IamBindStatusEnum;
import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.ledger.model.domain.TContractorInfo;
import com.testor.module.contractor.ledger.model.domain.TContractorLedger;
import com.testor.module.contractor.ledger.model.domain.TContractorPerson;
import com.testor.module.contractor.ledger.model.dto.TContractorPersonParam;
import com.testor.module.contractor.ledger.service.TContractorInfoService;
import com.testor.module.contractor.ledger.service.TContractorLedgerService;
import com.testor.module.contractor.ledger.service.TContractorPersonService;
import com.testor.module.iam.model.domain.IamUserMapping;
import com.testor.module.iam.service.IamSysUserService;
import com.testor.module.iam.service.IamUserMappingService;
import com.testor.module.sys.constant.OnlyCurrentOrgStateEnum;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.model.domian.SysUserExtend;
import com.testor.module.sys.model.dto.*;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.module.sys.service.SysUserExtendService;
import com.testor.module.sys.service.TSysUserService;
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.context.ContextUtils;
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.models.supers.SuperModel;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author rsq
 * @program zlmy_boot
 * @return
 **/
@RestController
@Api(
        value = "SysUser",
        tags = {"SysUser 用户"}
)
@RequestMapping({"/new/user"})
public class NewSysUserController extends SuperController {
    private static final Logger log = LoggerFactory.getLogger(NewSysUserController.class);
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private NewSysOrgService sysOrgService;

    @Autowired
    private TSysFileBizService tSysFileBizService;

    @Autowired
    private TSysUserService tSysUserService;

    @Autowired
    private IamUserMappingService iamUserMappingService;

    @Autowired
    private IamSysUserService iamSysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private TSysUserPositionService tSysUserPositionService;

    @Autowired
    private TSysPostService tSysPostService;

    @Autowired
    private SysUserExtendService sysUserExtendService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private TContractorLedgerService tContractorLedgerService;

    @Autowired
    private TContractorInfoService tContractorInfoService;

    @Autowired
    private TContractorPersonService tContractorPersonService;


    @ApiOperation(
            value = "根据用户ID查询用户信息",
            notes = "根据用户ID查询用户信息 get User By Id"
    )
    @GetMapping({"/get"})
    public BaseResponse<SysUserResponse> getEntity(String userId) {

        UserInfo loginUser = ContextUtils.getLoginUser();
        if (loginUser == null) {
            throw new ApiException(ResponseInfo.builder().code(1006).msg("未登录").build());
        }
        BaseResponse<SysUserResponse> baseResponse = new BaseResponse();
        if (StringHelper.isEmpty(userId)) {
            throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
        } else {
            SysUser user = (SysUser) this.sysUserService.getById(userId);
            if (ObjectHelper.isEmpty(user)) {
                throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
            } else {
                //判断用户的id是否可以被查看
                /*String orgId = loginUser.getOrgId();
                List<NewSysOrg> childrenById = sysOrgService.getChildrenById(orgId);
                List<String> idList = childrenById.stream()
                        .map(SysOrg::getOrgId)
                        .collect(Collectors.toList());
                int count = sysUserService.count(new QueryWrapper<SysUser>().in("org_id", idList).eq("user_id", userId));
                if (count == 0) {
                    throw new ApiException(ResponseInfo.builder().code(1006).msg("无权查看").build());
                }*/
                SysUserResponse sysUserResponse = BeanHelper.beanToBean(user, SysUserResponse.class);
                NewSysOrg org = this.sysOrgService.getById(user.getOrgId());
                if (!ObjectHelper.isEmpty(org)) {
                    sysUserResponse.setOrgName(org.getOrgName());
                }
                IamUserMapping iamUserMapping = iamUserMappingService.getByUserId(userId);
                if (!ObjectHelper.isEmpty(iamUserMapping)) {
                    sysUserResponse.setIamUserId(iamUserMapping.getIamUserId());
                }
                SysUserExtend sysUserExtend = sysUserExtendService.getById(user.getUserId());
                if (!ObjectHelper.isEmpty(sysUserExtend)) {
                    sysUserResponse.setUserTypeCode(sysUserExtend.getUserTypeCode());
                }
                baseResponse.setData(sysUserResponse);
                return baseResponse;
            }
        }
    }


    @ApiOperation(
            value = "【获取用户列表信息】",
            notes = "获取用户列表信息 List User"
    )
    @GetMapping({"/list"})
    public BaseResponse<BaseResponseList<SysUserListResponse>> listEntity(@Valid SysUserParam param) {
        BaseResponse<BaseResponseList<SysUserListResponse>> baseResponse = new BaseResponse();
        List<NewSysOrg> sysOrgList;
        if (StringHelper.isEmpty(param.getOrgId())) {
            sysOrgList = this.sysOrgService.list((new QueryWrapper()).select(new String[]{"org_id", "org_name"}));
        } else {
            sysOrgList = this.sysOrgService.getChildrenDept(param.getOrgId());
        }

        Page<SysUserListResponse> resultPage = iamSysUserService.querySysUserList(param);
        List<SysUserListResponse> records = (List) resultPage.getRecords().stream().peek((bean) -> {
            sysOrgList.stream().filter((sysOrg) -> {
                return sysOrg.getOrgId().equals(bean.getDeptId());
            }).forEach((sysOrg) -> {
                bean.setDeptName(sysOrg.getOrgName());
            });
        }).collect(Collectors.toList());
        BaseResponseList<SysUserListResponse> baseResponseList = new BaseResponseList();
        baseResponseList.setData(records);
        baseResponseList.setTotal(resultPage.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(
            value = "【组织结构及人员信息列表】",
            notes = "获取组织结构及人员信息列表"
    )
    @GetMapping({"/pageUserList"})
    public BaseResponse<BaseResponseList<SysUserListResponse>> pageUserList(@Valid SysUserParam param) {
        if (StringUtils.isBlank(param.getOrgId())) {
            param.setOrgId(ContextUtils.getLoginUser().getOrgId());
        }
        String onlyCurrentOrgState = param.getOnlyCurrentOrgState();
        if (StringUtils.isNotBlank(onlyCurrentOrgState) && OnlyCurrentOrgStateEnum.YES.getCode().equalsIgnoreCase(onlyCurrentOrgState)) {
            param.setOrgIdList(Collections.singletonList(param.getOrgId()));
        } else {
            List<NewSysOrg> sysOrgList = this.sysOrgService.getChildrenById(param.getOrgId());
            param.setOrgIdList(sysOrgList.stream().map(NewSysOrg::getOrgId).collect(Collectors.toList()));
        }
        String status = param.getStatus();
        if (StringUtils.isBlank(status)) {
            List<String> statusList = new ArrayList<>();
            statusList.add(BizConstants.STATUS_DISABLE);
            statusList.add(BizConstants.STATUS_ENABLE);
            param.setStatusList(statusList);
        } else {
            param.setStatusList(Collections.singletonList(status));
        }
        BaseResponse<BaseResponseList<SysUserListResponse>> baseResponse = new BaseResponse<>();
        IPage<SysUserListResponse> page = iamSysUserService.pageUserList(param);
        BaseResponseList<SysUserListResponse> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(page.getRecords());
        baseResponseList.setTotal(page.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    @ApiOperation(
            value = "修改用户基本信息",
            notes = "修改用户基本信息 edit user"
    )
    @PutMapping({"/update"})
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<SysUser> updateEntity(@Valid @RequestBody CustomerRemovalDto updateRequest) {
        BaseResponse<SysUser> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(updateRequest)) {
            throw new ApiException(UserEnumCode.USER_PARAM_IS_NULL.transform());
        } else if (StringHelper.isEmpty(updateRequest.getUserId())) {
            throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
        } else {
            SysOrg sysOrg = (SysOrg) this.sysOrgService.getById(updateRequest.getOrgId());
            if (!StringHelper.isEmpty(updateRequest.getOrgId()) && ObjectHelper.isNotEmpty(sysOrg)) {
                SysUser newUser = (SysUser) BeanHelper.beanToBean(updateRequest, SysUser.class);
                SysUser oldUser = (SysUser) this.sysUserService.getById(newUser.getUserId());
                if (!newUser.getLoginName().equals(oldUser.getLoginName())) {
                    SysUser temp = (SysUser) this.sysUserService.getOne((Wrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper()).eq("login_name", newUser.getLoginName())).ne("status", "1")).last("LIMIT 1"));
                    if (ObjectHelper.isNotEmpty(temp)) {
                        throw new ApiException(UserEnumCode.LOGIN_NAME_ALREADY_EXISTS.transform());
                    }
                }

                if (StringHelper.isEmpty(newUser.getLoginPwd())) {
                    newUser.setLoginPwd(oldUser.getLoginPwd());
                } else {
                    newUser.setLoginPwd(UserHelper.userPassword(newUser.getLoginPwd()));
                }

                if (ObjectHelper.isNotEmpty(updateRequest.getFiles()) && !updateRequest.getFiles().isEmpty()) {
                    List<TSysFileBiz> fileBizList = updateRequest.getFiles();
                    boolean fileBizResult = this.tSysFileBizService.saveFileBizs(fileBizList, updateRequest.getUserId(), this.getUserId());
                    if (!fileBizList.isEmpty() && !fileBizResult) {
                        throw new ApiException(FileEnumCode.FILE_BIZ_SAVE_FAILED.transform());
                    }
                }
                // 绑定IAM账户
                if (StringUtils.isNoneBlank(updateRequest.getIamUserId())) {
                    IamUserMapping byUserId = iamUserMappingService.getByUserId(newUser.getUserId());
                    //如果当前用户的e+账号和输入的不一致
                    if (byUserId == null || !byUserId.getIamUserId().equals(updateRequest.getIamUserId())) {
                        //换绑
                        if (!iamUserMappingService.bindIamUser(newUser.getUserId(), updateRequest.getIamUserId())) {
                            throw new ApiException(IamBindStatusEnum.BIND_BY_OTHER_USER.transform());
                        }
                        //换绑成功后注销账号
                        else {

                        }

                    }
                } else {
                    this.iamUserMappingService.remove((Wrapper) (new QueryWrapper()).eq("user_id", updateRequest.getUserId()));
                }
                newUser.setDeptId(updateRequest.getOrgId());
                newUser.setOrgId(sysOrg.getParentId());
                newUser.setOrgName(sysOrg.getOrgName());
                //判断用户是否迁移
                if (!oldUser.getOrgId().equals(updateRequest.getNewOrgId())) {
                    //转移用户
                    tSysUserService.customerRemoval(updateRequest);
                }
                this.sysUserService.updateById(newUser);
                sysUserExtendService.addOrUpdateUserType(newUser.getUserId(), updateRequest.getUserTypeCode());
                return baseResponse;
            } else {
                throw new ApiException(UserEnumCode.USER_ORG_ID_ERROR.transform());
            }
        }
    }


    @ApiOperation(
            value = "根据用户ID删除用户信息",
            notes = "根据用户ID删除用户信息 delete user by id"
    )
    @Transactional(
            rollbackFor = {Exception.class}
    )
    @PutMapping({"/delete"})
    public BaseResponse<SysUser> deleteEntity(@Valid @RequestBody SysUserDeleteRequest deleteRequest) {
        BaseResponse<SysUser> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(deleteRequest)) {
            throw new ApiException(UserEnumCode.REQUIRED_ITEMS_MISSING.transform());
        } else {
            SysUser sysUser =   this.sysUserService.getById(deleteRequest.getUserId());
            if (ObjectHelper.isEmpty(sysUser)) {
                throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
            } else {
                this.tSysFileBizService.remove((Wrapper) (new QueryWrapper()).eq("biz_id", deleteRequest.getUserId()));
                sysUser.setStatus("1");
                this.sysUserService.removeById(sysUser.getUserId());
                this.sysUserRoleService.remove((Wrapper) (new QueryWrapper()).eq("user_id", sysUser.getUserId()));
                this.iamUserMappingService.remove((Wrapper) (new QueryWrapper()).eq("user_id", sysUser.getUserId()));
                this.tSysUserPositionService.remove((Wrapper) (new QueryWrapper()).eq("user_id", sysUser.getUserId()));
                return baseResponse;
            }
        }
    }

    @ApiOperation(
            value = "根据用户ID删除用户信息（批量）",
            notes = "根据用户ID删除用户信息（批量）delete user by ids"
    )
    @Transactional(
            rollbackFor = {Exception.class}
    )
    @PutMapping({"/batch_delete"})
    public BaseResponse<SysUser> deleteEntities(@Valid @RequestBody SysUserDeleteBatchRequest deleteBatchRequest) {
        BaseResponse<SysUser> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(deleteBatchRequest)) {
            throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
        } else {
            List<String> ids = Arrays.stream(deleteBatchRequest.getUserId()).collect(Collectors.toList());
            this.sysUserRoleService.remove((Wrapper) (new QueryWrapper()).in("user_id", ids));
            this.iamUserMappingService.remove((Wrapper) (new QueryWrapper()).eq("user_id", ids));
            this.tSysUserPositionService.remove((Wrapper) (new QueryWrapper()).in("user_id", ids));
            this.sysUserService.removeByIds(ids);
            return baseResponse;
        }
    }

    @ApiOperation(
            value = "【新增用户基本信息】",
            notes = "新增用户基本信息 Add user"
    )
    @PostMapping({"/add"})
    public BaseResponse<SysUser> addEntity(@Valid @RequestBody SysUserCreateAndUpdateRequest addRequest) {
        BaseResponse<SysUser> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new ApiException(UserEnumCode.USER_PARAM_IS_NULL.transform());
        } else if (StringHelper.isEmpty(addRequest.getLoginPwd())) {
            throw new ApiException(UserEnumCode.REQUIRED_ITEMS_MISSING.transform());
        } else if (!StringHelper.isEmpty(addRequest.getOrgId()) && !ObjectHelper.isEmpty(this.sysOrgService.getById(addRequest.getOrgId()))) {
            SysUser existsSysUser = (SysUser) this.sysUserService.getOne((Wrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper()).eq("login_name", addRequest.getLoginName())).ne("status", "1")).last("LIMIT 1"));
            if (ObjectHelper.isNotEmpty(existsSysUser)) {
                throw new ApiException(UserEnumCode.LOGIN_NAME_ALREADY_EXISTS.transform());
            } else {
                String userId = IdHelper.getId32bit();
                if (ObjectHelper.isNotEmpty(addRequest.getFiles()) && !addRequest.getFiles().isEmpty()) {
                    List<TSysFileBiz> fileBizList = addRequest.getFiles();
                    boolean fileBizResult = this.tSysFileBizService.saveFileBizs(fileBizList, userId, this.getUserId());
                    if (!fileBizList.isEmpty() && !fileBizResult) {
                        throw new ApiException(FileEnumCode.FILE_BIZ_SAVE_FAILED.transform());
                    }
                }

                SysUser data = (SysUser) BeanHelper.beanToBean(addRequest, SysUser.class);
                NewSysOrg one = (NewSysOrg) this.sysOrgService.getOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("org_id", data.getOrgId())).ne("status", "1"));
                data.setOrgName(one.getOrgName());
                data.setOrgId(one.getParentId());
                data.setDeptId(addRequest.getOrgId());
                TSysPost tSysPost = (TSysPost) this.tSysPostService.getOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("id", data.getPostId())).ne("status", "1"));
                if (ObjectHelper.isNotEmpty(tSysPost)) {
                    data.setPostName(tSysPost.getPostName());
                }

                if (StringHelper.isEmpty(data.getLoginPwd())) {
                    data.setLoginPwd("123456");
                }

                data.setLoginPwd(UserHelper.userPassword(data.getLoginPwd()));
                data.setUserId(userId);
                // 绑定IAM账户
                if (StringUtils.isNoneBlank(addRequest.getIamUserId())) {
                    if (!iamUserMappingService.bindIamUser(userId, addRequest.getIamUserId())) {
                        throw new ApiException(IamBindStatusEnum.BIND_BY_OTHER_USER.transform());
                    }
                }
                this.sysUserService.save(data);
                sysUserExtendService.addOrUpdateUserType(userId, addRequest.getUserTypeCode());
                return baseResponse;
            }
        } else {
            throw new ApiException(UserEnumCode.USER_ORG_ID_ERROR.transform());
        }
    }

    @ApiOperation(
            value = "【获取IAM账号绑定的用户】",
            notes = "获取IAM账号绑定的用户"
    )
    @GetMapping({"/getBindUser"})
    public BaseResponse<List<SysUserListResponse>> getBindUser() {
        BaseResponse<List<SysUserListResponse>> baseResponse = new BaseResponse<>();
        String loginUserId = ContextUtils.getLoginUserId();
        IamUserMapping byUserId = iamUserMappingService.getByUserId(loginUserId);
        String iamUserId = byUserId.getIamUserId();
        List<SysUser> sysUsers = iamSysUserService.getUserByIamId(iamUserId);
        List<SysOrg> sysOrgList = this.sysOrgService.list((new QueryWrapper()).select(new String[]{"org_id", "org_name"}));

        List<SysUserListResponse> sysUserListResponses = Beans.listToBean(sysUsers, SysUserListResponse.class);
        if (!CollectionUtils.isEmpty(sysUserListResponses)) {
            sysUserListResponses.stream().peek((bean) -> {
                sysOrgList.stream().filter((sysOrg) -> {
                    return sysOrg.getOrgId().equals(bean.getDeptId());
                }).forEach((sysOrg) -> {
                    bean.setDeptName(sysOrg.getOrgName());
                });
            }).collect(Collectors.toList());
        }

        baseResponse.setData(sysUserListResponses);
        return baseResponse;
    }


    @ApiOperation(
            value = "【绑定iam账号】",
            notes = "绑定iam账号"
    )
    @GetMapping({"/bindIam"})
    public BaseResponse bindIam(@RequestParam String userId, @RequestParam String iamId) {
        BaseResponse baseResponse = new BaseResponse<>();
        Boolean aBoolean = iamUserMappingService.bindIamUser(userId, iamId);
        baseResponse.setData(aBoolean);
        return baseResponse;
    }

    @ApiOperation(value = "【根据当前机构id获取子组织机构树及子部门、人员、承包商信息、承包商人员信息】 ", notes = "personnelInfo 为空时或0时，获取人员信息、为1时人员信息查看 isSubordinates 是否包含下属 0否 1是")
    @GetMapping(value = "/getTreeOrgAndParties")
    public BaseResponse<NewTreeVo> getTreeOrgDeptAndParties(String orgId, String personnelInfo,@RequestParam(value = "isSubordinates",defaultValue = "0") String isSubordinates) {
        BaseResponse<NewTreeVo> baseResponse = new BaseResponse<>();
        // 获取所有非删除状态的SysOrg记录
        List<NewSysOrg> allOrgs = sysOrgService.list(new QueryWrapper<NewSysOrg>()
                .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE));
        // 使用Map来存储orgId到SysOrg的映射
        Map<String, NewSysOrg> orgMap = allOrgs.stream()
                .collect(Collectors.toMap(NewSysOrg::getOrgId, Function.identity()));
        // 构建树结构
        NewTreeVo rootNewTreeVo = buildTree(orgId, orgMap, personnelInfo,1,isSubordinates);
        baseResponse.setData(rootNewTreeVo);
        return baseResponse;
    }

    @ApiOperation(value = "【根据当前机构id获取子组织机构树及子部门、人员信息】 ", notes = "personnelInfo 为空时或0时，获取人员信息")
    @GetMapping(value = "/getOrgAndTree")
    public BaseResponse<NewTreeVo> getOrgAndTree(String orgId, String personnelInfo) {
        BaseResponse<NewTreeVo> baseResponse = new BaseResponse<>();
        // 获取所有非删除状态的SysOrg记录
        List<NewSysOrg> allOrgs = sysOrgService.list(new QueryWrapper<NewSysOrg>()
                .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE));
        // 使用Map来存储orgId到SysOrg的映射
        Map<String, NewSysOrg> orgMap = allOrgs.stream()
                .collect(Collectors.toMap(NewSysOrg::getOrgId, Function.identity()));
        // 构建树结构
        NewTreeVo rootNewTreeVo = buildTree(orgId, orgMap, personnelInfo,0,"1");
        baseResponse.setData(rootNewTreeVo);
        return baseResponse;
    }

    /**
     * 构建树
     * @param orgId
     * @param orgMap
     * @param personnelInfo 是否存放人员信息 空/0是 其他否
     * @param relatedParties 是否存放相关方信息 0否 1是
     * @return
     */
    private NewTreeVo buildTree(String orgId, Map<String, NewSysOrg> orgMap, String personnelInfo,int relatedParties,String isSubordinates) {
        SysOrg rootOrg = orgMap.get(orgId);
        if (rootOrg == null) {
            return null; // 根节点不存在
        }

        // 将SysOrg转为NewTreeVo
        NewTreeVo rootNewTreeVo = BeanHelper.beanToBean(rootOrg, NewTreeVo.class);

        // 递归构建子节点
        List<NewTreeVo> children = buildChildren(rootNewTreeVo.getOrgId(), orgMap, personnelInfo,isSubordinates);

        if (relatedParties == 1) {
            //添加相关方信息
            NewTreeVo newTreeVo = buildRelatedParties(personnelInfo);
            children.add(newTreeVo);
        }
        rootNewTreeVo.setChildren(children);

        return rootNewTreeVo;
    }

    public NewTreeVo buildRelatedParties(String personnelInfo){
        NewTreeVo newTreeVo = new NewTreeVo();  // 创建树的根节点
        newTreeVo.setOrgName("相关方");  // 设置根节点名称为“相关方”
        String orgId = ContextUtils.getLoginUser().getOrgId();  // 获取当前登录用户的组织ID

        // 获取当前组织的所有承包商台账信息
        List<Object> infoIds = tContractorLedgerService.listObjs(new QueryWrapper<TContractorLedger>().select(TContractorLedger.INFO_ID).eq(TContractorLedger.ORG_ID, orgId).groupBy(TContractorLedger.INFO_ID));

        List<NewTreeVo> children = new ArrayList<>();  // 创建一个空的子节点列表

        // 遍历每个承包商台账
        for (Object infoId : infoIds) {
            NewTreeVo childNewTreeVo = new NewTreeVo();  // 为每个承包商创建一个新的子节点
            String infoIdStr = infoId.toString();  // 获取承包商的infoId
            TContractorInfo tContractorInfo = tContractorInfoService.getById(infoIdStr);  // 获取承包商的详细信息

            if (tContractorInfo != null) {
                childNewTreeVo.setOrgName(tContractorInfo.getName());  // 设置子节点名称为承包商的名称
            }
            childNewTreeVo.setOrgId(infoIdStr);  // 设置子节点的orgId为承包商台账的ID
            TContractorPersonParam tContractorPersonParam = new TContractorPersonParam();
            tContractorPersonParam.setInfoId(infoIdStr);  // 设置参数，查询该承包商的人员信息

            //是否获取人员信息
            if (StringUtils.isBlank(personnelInfo) || "0".equals(personnelInfo)) {
                // 获取承包商的有效人员
                List<TContractorPerson> tContractorPeoples = tContractorPersonService.listAllEntity(tContractorPersonParam);
                List<SysUser> users = new ArrayList<>();  // 创建一个空的用户列表
                if (tContractorPeoples != null && !tContractorPeoples.isEmpty()) {
                    // 遍历每个有效人员，转换为SysUser对象
                    for (TContractorPerson tContractorPeople : tContractorPeoples) {
                        SysUser sysUser = new SysUser();
                        sysUser.setUserId(tContractorPeople.getId());  // 设置用户ID
                        sysUser.setUserName(tContractorPeople.getName());  // 设置用户姓名
                        sysUser.setUserType("1");
                        users.add(sysUser);  // 将用户添加到用户列表
                    }
                }
                childNewTreeVo.setUsers(users);  // 将用户列表添加到子节点
            }
            children.add(childNewTreeVo);  // 将当前承包商子节点添加到父节点的children列表中
        }

        // 设置根节点的子节点为所有承包商子节点
        newTreeVo.setChildren(children);

        // 返回构建好的树形结构
        return newTreeVo;
    }

    private List<NewTreeVo> buildChildren(String parentId, Map<String, NewSysOrg> orgMap, String personnelInfo, String isSubordinates) {
        List<NewTreeVo> children = new ArrayList<>();

        // 找到所有子节点
        List<SysOrg> childOrgs = orgMap.values().stream()
                .filter(org -> parentId.equals(org.getParentId()))
                .sorted(Comparator.comparing(SysOrg::getIsDept).reversed()) // 按照IS_DEPT降序排序
                .collect(Collectors.toList());

        // 递归处理每个子节点
        for (SysOrg childOrg : childOrgs) {
            NewTreeVo childNewTreeVo = BeanHelper.beanToBean(childOrg, NewTreeVo.class);

            // 如果是部门，查找所有用户,personnelInfo为空 或者为0
            if ("1".equals(childOrg.getIsDept()) && (StringUtils.isBlank(personnelInfo) || "0".equals(personnelInfo))) {
                List<SysUser> users = sysUserService.list(new QueryWrapper<SysUser>()
                        .eq(SysUser.DEPT_ID, childOrg.getOrgId()).eq(SysUser.STATUS, "0")).stream()
                        .map(sysUserVo -> {
                            sysUserVo.setUserType("0");
                            return sysUserVo;
                        })
                        .collect(Collectors.toList());;
                childNewTreeVo.setUsers(users);
            }
            // 继续递归处理子节点的子节点
            if ("1".equals(isSubordinates)) {
                List<NewTreeVo> grandChildren = buildChildren(childNewTreeVo.getOrgId(), orgMap, personnelInfo, isSubordinates);
                childNewTreeVo.setChildren(grandChildren);
            }
            children.add(childNewTreeVo);
        }

        return children;
    }

    @ApiOperation(
            value = "根据用户ID查询该用户所拥有的角色列表",
            notes = "根据用户ID查询该用户所拥有的角色列表 get roles by user"
    )
    @GetMapping({"/show"})
    public BaseResponse<List<Map<String, Object>>> showEntities(String userId) {
        BaseResponse<List<Map<String, Object>>> baseResponse = new BaseResponse();
        if (StringHelper.isEmpty(userId)) {
            throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
        } else {
            SysUser user = this.sysUserService.getById(userId);
            NewSysOrg org = this.sysOrgService.getById(user.getOrgId());
            LambdaQueryWrapper<SysRole> roleAllQuery = new LambdaQueryWrapper();
            String treeLevel = String.valueOf(org.getTreeLevel());
            roleAllQuery.ne(SuperModel::getStatus, "1").eq(SysRole::getTreeLevel, treeLevel);
            List<SysRole> roles = this.sysRoleService.list(roleAllQuery);
            List<SysUserRole> checkedRoles = this.sysUserRoleService.list((Wrapper) (new QueryWrapper()).eq("user_id", userId));
            List<String> checkedRoleIds = (List) checkedRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            List<Map<String, Object>> data = BeanHelper.beansToMaps(roles);
            Iterator var10 = data.iterator();
            while (var10.hasNext()) {
                Map<String, Object> role = (Map) var10.next();
                if (checkedRoleIds.contains(String.valueOf(role.get("roleId")))) {
                    role.put("isChecked", true);
                } else {
                    role.put("isChecked", false);
                }
            }

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


    @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 = ObjectHelper.defaultIfNull(params, new SysUserParam());
        if (StringHelper.isBlank(param.getOrgId())) {
            param.setOrgId(ContextUtils.getLoginUser().getOrgId());
        }

        String onlyCurrentOrgState = param.getOnlyCurrentOrgState();
        if (StringUtils.isNotBlank(onlyCurrentOrgState) && OnlyCurrentOrgStateEnum.YES.getCode().equalsIgnoreCase(onlyCurrentOrgState)) {
            param.setOrgIdList(Collections.singletonList(param.getOrgId()));
        } else {
            List<NewSysOrg> sysOrgList = this.sysOrgService.getChildrenById(param.getOrgId());
            param.setOrgIdList(sysOrgList.stream().map(NewSysOrg::getOrgId).collect(Collectors.toList()));
        }
        iamSysUserService.export(param, cols, ids, response);

    }
    @ApiOperation(
            value = "根据名称下载模板",
            notes = "根据名称下载模板 download export template with name"
    )
    @GetMapping({"/downloadImportTemplate"})
    public void download(String fileName, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        fileName = StringHelper.replace(fileName, "+", "%20");
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), UserImport.class).sheet("数据").doWrite(new ArrayList<>());
    }


}
