package com.xunmei.sync.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.utils.IDHelper;
import com.xunmei.common.core.utils.bean.BeanUtils;
import com.xunmei.sync.domain.FjnxOrg;
import com.xunmei.sync.domain.FjnxOrgBusinessRelation;
import com.xunmei.sync.domain.FjnxUser;
import com.xunmei.sync.dto.fjnxsync.FJNXOrgDto;
import com.xunmei.sync.dto.fjnxsync.FJNXUserDto;
import com.xunmei.sync.dto.fjnxsync.FJNXXmlOrgDto;
import com.xunmei.sync.dto.fjnxsync.FJNXXmlUserDto;
import com.xunmei.sync.mapper.FjnxOrgBusinessRelationMapper;
import com.xunmei.sync.service.*;
import com.xunmei.system.api.RemoteOrgService;
import com.xunmei.system.api.RemoteUserService;
import com.xunmei.system.api.domain.Org;
import com.xunmei.system.api.domain.SysOrg;
import com.xunmei.system.api.domain.SysUser;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhulu
 * @date 2022/5/30 16:02
 */
@Slf4j
@Service
public class FJNXSyncServiceImpl implements IFJNXSyncService {

    @Autowired
    IFJNXOrgSyncService ifjnxOrgSyncService;

    @Autowired
    IFJNXUserSyncService ifjnxUserSyncService;

    @Autowired
    IFJNXOrgService ifjnxOrgService;

    @Autowired
    IFJNXUserService ifjnxUserService;

    @Autowired
    RemoteOrgService remoteOrgService;

    @Autowired
    RemoteUserService remoteUserService;

    @Resource
    FjnxOrgBusinessRelationMapper fjnxOrgBusinessRelationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String SyncUserInfo() {
        FJNXXmlUserDto fjnxXmlUserDto = ifjnxUserSyncService.getUserInfoByFileInfo();
        if (fjnxXmlUserDto == null || ObjectUtil.isEmpty(fjnxXmlUserDto.getUserVos())){
            return "未获取到用户信息数据";
        }


        // 将同步到的用户数据线保存下来
        List<FjnxUser> fjnxUserList = FjnxXmlUsersDtoConvertToFjnxUsers(fjnxXmlUserDto.getUserVos());
        ifjnxUserService.saveOrUpdateBatch(fjnxUserList);

        // 获取系统当前存在的用户信息
        SysUser request = new SysUser();
        request.setSource(1);
        R<List<SysUser>> existUserResult = remoteUserService.getAllSyncUser(request,SecurityConstants.INNER);
        if (existUserResult.getCode() != 200) {
            return "remoteUserService.getAllSyncUser 调用失败:" + existUserResult.getMsg();
        }
        List<SysUser> existUserList = existUserResult.getData();

        // 获取系统当前存在的机构信息
        R<List<SysOrg>> existAllOrgResult = remoteOrgService.getAllOrg(SecurityConstants.INNER);
        if (existAllOrgResult.getCode() != 200) {
            return "remoteOrgService.getAllOrg 调用失败:" + existAllOrgResult.getMsg();
        }
        List<SysOrg> existOrgList = existAllOrgResult.getData();

        //将FJNXUser 转换为SysUser 并保存
        if (ObjectUtil.isEmpty(existUserList)) {
            final R<Boolean> booleanR = remoteUserService.batchSaveSyncUser(FjnxUsersConvertToUsers(fjnxXmlUserDto.getUserVos(), existOrgList), SecurityConstants.INNER);
            if (booleanR != null && booleanR.getCode() != 200) {
                log.error("调用远程服务接口remoteUserService.batchSaveSyncOrg 失败：{}", booleanR.getMsg());
                return "remoteUserService.batchSaveSyncUser 调用失败:" + booleanR.getMsg();
            }
            return null;
        }
        List<SysUser> addList = new ArrayList<>();
        List<SysUser> updateList = new ArrayList<>();
        List<SysUser> deleteList = new ArrayList<>();
        List<String> fjnxUserCodeList = new ArrayList<>();

        fjnxXmlUserDto.getUserVos().forEach(fjnxUser -> {
            String orgCode = fjnxUser.getDepCode();
            if (!StringUtil.isNullOrEmpty(orgCode) && !StringUtil.isNullOrEmpty(fjnxUser.getUserId())) {
                Optional<SysOrg> optionalOrg = existOrgList.stream().filter(x -> orgCode.equals(x.getCode())).findFirst();
                if (optionalOrg.isPresent()) {
                    Optional<SysUser> optionalUser = existUserList.stream().filter(x -> fjnxUser.getUserId().equals(x.getCode())).findFirst();
                    if (optionalUser.isPresent()) {
                        updateList.add(FjnxUserConvertToUser(fjnxUser, optionalUser.get(), optionalOrg.get()));
                    } else {
                        addList.add(FjnxUserConvertToUser(fjnxUser, optionalOrg.get()));
                    }
                } else {
                    log.error("同步人员【{}】所属机构编码【{}】在当前数据库中未找到,{}", fjnxUser.getUserId() + fjnxUser.getUserName(), fjnxUser.getDepCode(), fjnxUser);
                }
                fjnxUserCodeList.add(fjnxUser.getUserId());
            }
        });

        // 人员在本系统中存在 但是在统一运营门户中不存在
        deleteList = existUserList.stream().filter(entity -> !fjnxUserCodeList.contains(entity.getCode())&& entity.getSource()==1).collect(Collectors.toList());
        deleteList.forEach(x -> x.setDeleted(1));
        existUserList.addAll(addList);

        final R<Boolean> booleanR = remoteUserService.batchSaveSyncUser(existUserList, SecurityConstants.INNER);
        if (booleanR != null && booleanR.getCode() != 200) {
            log.error("调用远程服务接口remoteUserService.batchSaveSyncOrg 失败：{}", booleanR.getMsg());
            return "remoteUserService.batchSaveSyncUser 调用失败:" + booleanR.getMsg();
        }
        return null;
    }

    @Override
    @Transactional
    public String SyncOrgInfo() {
        /*
         * 1、从统一门户接口获取机构数据，得到FJNXOrgDto 数组对象
         * 2、保存FJNXOrgDto数组到 t_fjnx_org表,根据机构业务关系表转换机构businessParentCode
         * 3、获取系统当前现有所有机构
         * 4、数据对比，判断出新增、删除、修改数组
         * 5、调用机构接口保存机构数据
         * */
        FJNXXmlOrgDto fjnxXmlOrgDto = ifjnxOrgSyncService.getOrgInfoByFileInfo();
        if (fjnxXmlOrgDto == null || ObjectUtil.isEmpty(fjnxXmlOrgDto.getOrgVos()))
        {
            return "未获取到机构信息数据";
        }


        List<FjnxOrg> fjnxOrgList = ConvertXmlOrgDtoToOrgJinx(fjnxXmlOrgDto.getOrgVos());
        ifjnxOrgService.saveOrUpdateBatch(fjnxOrgList);


        R<List<SysOrg>> existAllOrgResult = remoteOrgService.getAllOrg(SecurityConstants.INNER);
        if (existAllOrgResult.getCode() != 200) {
            return existAllOrgResult.getMsg();
        }
        List<SysOrg> existOrgList = existAllOrgResult.getData();


//        List<OrgExtendInfo> orgExtendInfoList = new ArrayList<>();
        // 第一同步所有机构
        if (ObjectUtil.isEmpty(existOrgList)) {
            List<SysOrg> rList = FjnxOrgsConvertToSysOrgs(fjnxOrgList);
            resetParentIdAndPath(rList);
            final R<Boolean> listR = remoteOrgService.batchSaveSyncOrg(rList, SecurityConstants.INNER);
            if (listR != null && listR.getCode() != 200) {
                log.error("调用远程服务接口remoteOrgService.batchSaveSyncOrg 失败：{}", listR.getMsg());
                return listR.getMsg();
            }
            return null;
        }

        List<SysOrg> addList = new ArrayList<>();
        List<SysOrg> updateList = new ArrayList<>();
        List<SysOrg> deleteList;
        List<String> fjnxOrgCodeList = new ArrayList<>();
        fjnxOrgList.forEach(fjnxOrg -> {
            String fjnxorgCode = fjnxOrg.getOrgCode();
            if (!StringUtil.isNullOrEmpty(fjnxorgCode)) {
                if (ObjectUtil.isNotEmpty(existOrgList)) {
                    Optional<SysOrg> optional = existOrgList.stream().filter(x -> fjnxOrg.getOrgCode().equals(x.getCode())).findFirst();
                    if (optional.isPresent()) {
                        updateList.add(FjnxOrgConvertToSysOrg(optional.get(), fjnxOrg));
                    } else {
                        addList.add(FjnxOrgConvertToSysOrg(fjnxOrg));
                    }
                } else {
                    addList.add(FjnxOrgConvertToSysOrg(fjnxOrg));
                }
                fjnxOrgCodeList.add(fjnxOrg.getOrgCode());
            } else {
                log.error("机构编码为空停止转换为系统机构，机构名称{}", fjnxOrg.getOrgName());
            }
        });

        // 机构在本系统中存在 但是在统一运营门户中不存在
        deleteList = existOrgList.stream().filter(entity -> !fjnxOrgCodeList.contains(entity.getCode()) && !StringUtil.isNullOrEmpty(entity.getCode())).collect(Collectors.toList());
        deleteList.forEach(x -> x.setDeleted(1));

        existOrgList.addAll(addList);

        resetParentIdAndPath(existOrgList);

        final R<Boolean> listR = remoteOrgService.batchSaveSyncOrg(existOrgList, SecurityConstants.INNER);
        if (ObjectUtil.isNotEmpty(listR) && listR.getCode() != 200) {
            log.error("调用远程服务接口remoteOrgService.batchSaveSyncOrg 失败：{}", listR.getMsg());
            return listR.getMsg();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String SyncOrgAndUserInfo() {
        this.SyncOrgInfo();
        this.SyncUserInfo();
        return null;
    }


    /**
     * 刷新机构业务Path
     */
    @Transactional
    @Override
    public void RefreshBusinessPath() {
//        List<Org> allOrgList = orgRepository.findAll();
//        // 将所有的 BusinessPath 先刷成跟 path字段值一致
//        allOrgList.forEach(x -> x.setBusinessPath(x.getPath()));
//
//        List<FjnxOrgBusinessRelation> orgBusinessRelationList = orgBusinessRelationMapper.selectList(Wrappers.emptyWrapper());
//        if (ObjectUtil.isEmpty(orgBusinessRelationList)) {
//            orgRepository.saveAll(allOrgList);
//            return;
//        }
//
//        // 从顶层机构往下开始刷新businessPath 根据机构业务管理数据 调整某些机构BusinessPath
//        // TODO 目前只支持平级机构可以标记为业务父级
//        orgBusinessRelationList.stream().sorted(Comparator.comparing(FjnxOrgBusinessRelation::getOrgLevel)).forEach(obr -> {
//            Optional<Org> currentOrgOpt = allOrgList.stream().filter(org -> obr.getOrgId().equals(org.getId())).findFirst();
//            Optional<Org> businessParentOrgOpt = allOrgList.stream().filter(org -> obr.getBusinessParentId().equals(org.getId())).findFirst();
//            if (currentOrgOpt.isPresent() && businessParentOrgOpt.isPresent()) {
//                Org currentOrg = currentOrgOpt.get();
//                resetBusinessPath(currentOrg, businessParentOrgOpt.get());
//                updateChildBusinessPath(currentOrg, allOrgList);
//            }
//        });
//        orgRepository.saveAll(allOrgList);
//        return;
    }

    public void resetParentIdAndPath(List<SysOrg> orgList) {
        orgList.stream().forEach(x->{
            x.setPath("");
        });
        final List<SysOrg> collect = orgList.stream().filter(topOrg -> StringUtil.isNullOrEmpty(topOrg.getParentGuid()) && 0 == topOrg.getDeleted()).collect(Collectors.toList());
        collect.forEach(org -> {
            org.setParentId(-1L);
//            org.setLevel(1);
            org.setPath(org.getId() + "-");
        });

        orgList.forEach(org -> {

//            if (org.getParentId() != null) {
//                return;
//            }

            if (org.getDeleted().equals(1)) {
                // 已删除
                return;
            }

            if (!StringUtil.isNullOrEmpty(org.getParentGuid())) {
                Optional<SysOrg> parentOrgOptional = orgList.stream().filter(pOrg -> !StringUtil.isNullOrEmpty(pOrg.getGuid()) && pOrg.getGuid().equals(org.getParentGuid())).findFirst();
                if (parentOrgOptional.isPresent()) {
                    org.setParentId(parentOrgOptional.get().getId());
                    if (StringUtil.isNullOrEmpty(parentOrgOptional.get().getPath())) {
                        List<SysOrg> childOrg = new ArrayList<>();
                        childOrg.add(org);
                        resetParentOrgPath(parentOrgOptional.get(), childOrg, orgList);
                    } else {
                        org.setPath(parentOrgOptional.get().getPath() + org.getId() + "-");
                    }
                } else {
                    log.error("机构【{}】机构编码【{}】父级机构编码【{}】，父级机构未找到；{}", org.getName(), org.getGuid(), org.getParentGuid(), org);
                }
            } else {
                org.setParentId(-1L);
//                org.setLevel(1);
                org.setPath(org.getId() + "-");
            }
        });
    }

    public void resetParentOrgPath(SysOrg parentOrg, List<SysOrg> childOrg, List<SysOrg> orgList) {
        Optional<SysOrg> parentOrgOptional = orgList.stream().filter(pOrg -> !StringUtil.isNullOrEmpty(pOrg.getGuid()) && pOrg.getGuid().equals(parentOrg.getParentGuid())).findFirst();
        if (parentOrgOptional.isPresent()) {
            parentOrg.setParentId(parentOrgOptional.get().getId());
            if (!StringUtil.isNullOrEmpty(parentOrgOptional.get().getPath())) {
                retOrgPath(parentOrgOptional.get(), parentOrg);
                retChildOrgPath(parentOrg, childOrg);
            } else {

                childOrg.add(parentOrg);
                resetParentOrgPath(parentOrgOptional.get(), childOrg, orgList);
            }
        } else {
            log.error("机构【{}】机构编码【{}】父级机构编码【{}】，父级机构未找到；{}", parentOrg.getName(), parentOrg.getGuid(), parentOrg.getParentGuid(), parentOrg);
        }
    }

    public void retOrgPath(SysOrg parentOrg, SysOrg org) {
        org.setParentId(parentOrg.getId());
/*        if (parentOrg.getLevel() != null) {
            parentOrg.setLevel(parentOrg.getLevel() + 1);
        }*/
        org.setPath(parentOrg.getPath() + org.getId() + "-");
    }

    public void retChildOrgPath(SysOrg parentOrg, List<SysOrg> childOrgs) {
        if (ObjectUtil.isNotEmpty(childOrgs)) {
            if (ObjectUtil.isNotEmpty(parentOrg)) {
                Optional<SysOrg> orgOptional = childOrgs.stream().filter(org -> org.getParentId().equals(parentOrg.getId())).findFirst();
                if (orgOptional.isPresent()) {
                    SysOrg childOrg = orgOptional.get();
                    retOrgPath(parentOrg, childOrg);
                    childOrgs.remove(childOrg);
                    retChildOrgPath(childOrg, childOrgs);
                } else {
                    log.error("机构【{}】机构编码【{}】父级机构编码【{}】，父级机构未找到；{}", parentOrg.getName(), parentOrg.getGuid(), parentOrg.getParentGuid(), parentOrg);
                }
            }
        }
    }

//    private void updateChildBusinessPath(Org businessParentOrg, List<Org> allOrgList) {
//        List<Org> childrenOrgs = allOrgList.stream().filter(aorg -> businessParentOrg.getId().equals(aorg.getParentId())).collect(Collectors.toList());
//        for (final Org org : childrenOrgs) {
//            resetBusinessPath(org, businessParentOrg);
//            this.updateChildBusinessPath(org, allOrgList);
//        }
//    }
//
//    public Org resetBusinessPath(Org org, Org businessParentOrg) {
//
//        org.setBusinessPath(businessParentOrg.getBusinessPath() + org.getId() + "-");
//        System.out.println(org.getBusinessPath());
//        return org;
//    }
//
//    private List<SysOrg> FjnxOrgsConvertToSysOrgs(List<OrgFjnx> fjnxOrgDtoList) {
//        List<SysOrg> result = new ArrayList<>();
//        if (ObjectUtil.isNotEmpty(fjnxOrgDtoList)) {
//            fjnxOrgDtoList.stream().forEach(x -> {
//                result.add(FjnxOrgConvertToSysOrg(x));
//            });
//        }
//        return result;
//    }

    private SysOrg FjnxOrgConvertToOrg(FjnxOrg fjnxOrgDto) {
        SysOrg org = new SysOrg();
        org.setId(IDHelper.id());
        org.setName(fjnxOrgDto.getOrgName());
        org.setShortName(fjnxOrgDto.getShortName());
        org.setGuid(fjnxOrgDto.getOrgCode());
        org.setParentGuid(fjnxOrgDto.getOrgParent());
        org.setCode(fjnxOrgDto.getOrgCode());
        org.setPhone(fjnxOrgDto.getOrgPhone());
        org.setAddress(fjnxOrgDto.getOrgAddress());
//        org.setCodePath(fjnxOrgDto.getOrgPath());
        org.setSort(fjnxOrgDto.getOrgOrder());
        org.setUpdateTime(fjnxOrgDto.getUpdateTime());
        org.setRemark(fjnxOrgDto.getRemark());
//        org.setLevel(fjnxOrgDto.getOrgPath().split("/").length);
        // TODO 机构状态和机构类型转换
        //org.setIsLock(fjnxOrgDto.getUsableFlag());
        org.setIsLock(fjnxOrgDto.getUsableFlag());
        return org;

    }

    private List<SysOrg> FjnxOrgsConvertToSysOrgs(List<FjnxOrg> fjnxOrgList) {
        List<SysOrg> result = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(fjnxOrgList)) {
            fjnxOrgList.forEach(x -> {
                result.add(FjnxOrgConvertToSysOrg(x));
            });
        }
        return result;
    }

    private SysOrg FjnxOrgConvertToSysOrg(FjnxOrg fjnxOrgDto) {
        SysOrg org = new SysOrg();
        org.setId(IDHelper.id());
        org.setName(fjnxOrgDto.getOrgName());
        org.setShortName(fjnxOrgDto.getShortName());
        org.setCode(fjnxOrgDto.getOrgCode());
        org.setGuid(fjnxOrgDto.getOrgCode());
        org.setParentGuid(fjnxOrgDto.getBusinessParentCode());
        org.setPhone(fjnxOrgDto.getOrgPhone());
        org.setAddress(fjnxOrgDto.getOrgAddress());
        org.setSort(fjnxOrgDto.getOrgOrder());
        org.setUpdateTime(fjnxOrgDto.getUpdateTime());
        org.setRemark(fjnxOrgDto.getRemark());
        //org.setLevel(fjnxOrgDto.getOrgPath().split("/").length);
        org.setIsLock(fjnxOrgDto.getUsableFlag());
        org.setDeleted(0);
        org.setSource(1);
        // todo 机构类型转换
        return org;
    }
//
//    private OrgExtendInfo FjnxOrgConvertToOrgExtendInfo(Long orgId, FJNXOrgDto fjnxOrgDto) {
//        OrgExtendInfo orgExtendInfo = new OrgExtendInfo();
//        orgExtendInfo.setOrgId(orgId);
//        orgExtendInfo.setOrgCode(fjnxOrgDto.getOrgCode());
//        orgExtendInfo.setBankType(fjnxOrgDto.getBankType());
//        orgExtendInfo.setBelongCode(fjnxOrgDto.getBelongCode());
//        orgExtendInfo.setBelongDate(fjnxOrgDto.getBelongDate());
//        orgExtendInfo.setCorporcode(fjnxOrgDto.getCorporCode());
//        orgExtendInfo.setMajorBack(fjnxOrgDto.getMajorBank());
//        orgExtendInfo.setOrgNature(fjnxOrgDto.getOrgNature());
//        orgExtendInfo.setPrincipalType(fjnxOrgDto.getPrincipalType());
//        orgExtendInfo.setPrincipalDuty(fjnxOrgDto.getPrincipalDuty());
//        orgExtendInfo.setSocialTrustCode(fjnxOrgDto.getSocialTrustCode());
//        orgExtendInfo.setOrgLevel(fjnxOrgDto.getOrgLevel());
//        orgExtendInfo.setOrgChief(fjnxOrgDto.getOrgChief());
//        return orgExtendInfo;
//
//    }
//
//    private OrgExtendInfo FjnxOrgConvertToOrgExtendInfo(OrgExtendInfo orgExtendInfo, FJNXOrgDto fjnxOrgDto) {
////        OrgExtendInfo orgExtendInfo = new OrgExtendInfo();
////        orgExtendInfo.setOrgId(orgId);
////        orgExtendInfo.setOrgCode(fjnxOrgDto.getOrgCode());
//        orgExtendInfo.setBankType(fjnxOrgDto.getBankType());
//        orgExtendInfo.setBelongCode(fjnxOrgDto.getBelongCode());
//        orgExtendInfo.setBelongDate(fjnxOrgDto.getBelongDate());
//        orgExtendInfo.setCorporcode(fjnxOrgDto.getCorporCode());
//        orgExtendInfo.setMajorBack(fjnxOrgDto.getMajorBank());
//        orgExtendInfo.setOrgNature(fjnxOrgDto.getOrgNature());
//        orgExtendInfo.setPrincipalType(fjnxOrgDto.getPrincipalType());
//        orgExtendInfo.setPrincipalDuty(fjnxOrgDto.getPrincipalDuty());
//        orgExtendInfo.setSocialTrustCode(fjnxOrgDto.getSocialTrustCode());
//        orgExtendInfo.setOrgLevel(fjnxOrgDto.getOrgLevel());
//        orgExtendInfo.setOrgChief(fjnxOrgDto.getOrgChief());
//        return orgExtendInfo;
//
//    }


    private Org FjnxOrgConvertToOrg(Org org, FJNXOrgDto fjnxOrgDto) {
        org.setName(fjnxOrgDto.getOrgName());
        org.setShortName(fjnxOrgDto.getShortName());
        org.setGuid(fjnxOrgDto.getOrgCode());
        org.setParentGuid(fjnxOrgDto.getOrgParent());
        org.setCode(fjnxOrgDto.getOrgCode());
        org.setPhone(fjnxOrgDto.getOrgPhone());
        org.setAddress(fjnxOrgDto.getOrgAddress());
//        org.setCodePath(fjnxOrgDto.getOrgPath());
        org.setSort(fjnxOrgDto.getOrgOrder());
        org.setUpdateTime(fjnxOrgDto.getUpdateTime());
        org.setRemark(fjnxOrgDto.getRemark());
        org.setLevel(fjnxOrgDto.getOrgPath().split("/").length);
        // TODO 机构状态和机构类型转换
        org.setIsLock(fjnxOrgDto.getUsableFlag());
        return org;

    }

    private SysOrg FjnxOrgConvertToSysOrg(SysOrg org, FjnxOrg fjnxOrg) {
        org.setName(fjnxOrg.getOrgName());
        org.setShortName(fjnxOrg.getShortName());
        org.setCode(fjnxOrg.getOrgCode());
        org.setGuid(fjnxOrg.getOrgCode());
        org.setParentGuid(fjnxOrg.getBusinessParentCode());
        org.setPhone(fjnxOrg.getOrgPhone());
        org.setAddress(fjnxOrg.getOrgAddress());
        org.setSort(fjnxOrg.getOrgOrder());
        org.setUpdateTime(fjnxOrg.getUpdateTime());
        org.setRemark(fjnxOrg.getRemark());
//        org.setLevel(fjnxOrg.getOrgPath().split("/").length);
        // TODO 机构状态和机构类型转换
        org.setIsLock(fjnxOrg.getUsableFlag());
        org.setSource(1);
        return org;

    }


    private List<FjnxUser> FjnxXmlUsersDtoConvertToFjnxUsers(List<FJNXUserDto> fjnxUserDtoList) {
        List<FjnxUser> result = new ArrayList<>();
        Date syncDateTime = new Date();
        if (ObjectUtil.isNotEmpty(fjnxUserDtoList)) {
            fjnxUserDtoList.forEach(userDto -> {

                FjnxUser tempFjnxUser = new FjnxUser();
                BeanUtils.copyBeanProp(tempFjnxUser, userDto);
                tempFjnxUser.setLastSyncTime(syncDateTime);
                result.add(tempFjnxUser);
            });
        }
        return result;
    }


    private List<SysUser> FjnxUsersConvertToUsers(List<FJNXUserDto> fjnxUserDtoList, List<SysOrg> orgList) {
        List<SysUser> result = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(fjnxUserDtoList)) {
            fjnxUserDtoList.forEach(x -> {
                Optional<SysOrg> optionalOrg = orgList.stream().filter(org -> org.getCode().equals(x.getDepCode())).findFirst();
                if (optionalOrg.isPresent()) {
                    result.add(FjnxUserConvertToUser(x, optionalOrg.get()));
                } else {
                    log.error("同步人员【{}】所属机构编码【{}】在当前数据库中未找到,{}", x.getUserId() + x.getUserName(), x.getDepCode(), x);
                }

            });
        }
        return result;
    }

    private SysUser FjnxUserConvertToUser(FJNXUserDto fjnxUserDto, SysOrg org) {
        SysUser user = new SysUser();
        user.setCode(fjnxUserDto.getUserId());
        user.setName(fjnxUserDto.getUserName());
        user.setUsername(fjnxUserDto.getLoginName());
        user.setPhone(fjnxUserDto.getMobile());
        user.setGender(fjnxUserDto.getSex());
        user.setCard(fjnxUserDto.getIdCard());
        user.setJobNumber(fjnxUserDto.getTeller());
//        user.setApproveStatus(ApproveStatus.PASS);
        user.setUpdateTime(fjnxUserDto.getUpdateTime());
        user.setOrgId(org.getId());
        user.setOrgName(org.getName());
        user.setOrgPath(org.getPath());
        //0 禁用 1 启用已改密码 2 启用未改密码
        user.setIsLock(fjnxUserDto.getUserStatus());
        user.setSource(1);
        // TODO 机构状态和机构类型转换
        //user.setIsLock(fjnxOrgDto.getUsableFlag());
        return user;

    }

    private SysUser FjnxUserConvertToUser(FJNXUserDto fjnxUserDto, SysUser user, SysOrg org) {
        user.setCode(fjnxUserDto.getUserId());
        user.setName(fjnxUserDto.getUserName());
        user.setUsername(fjnxUserDto.getLoginName());
        user.setPhone(fjnxUserDto.getMobile());
        user.setGender(fjnxUserDto.getSex());
        user.setCard(fjnxUserDto.getIdCard());
        user.setJobNumber(fjnxUserDto.getTeller());
        user.setApproveStatus(1L);
        user.setUpdateTime(fjnxUserDto.getUpdateTime());
        user.setOrgId(org.getId());
        user.setOrgName(org.getName());
        user.setOrgPath(org.getPath());
        //0 禁用 1 启用已改密码 2 启用未改密码
        user.setIsLock(fjnxUserDto.getUserStatus());
        // TODO 机构状态和机构类型转换
        //user.setIsLock(fjnxOrgDto.getUsableFlag());
        user.setSource(1);
        return user;

    }

    private List<FjnxOrg> ConvertXmlOrgDtoToOrgJinx(List<FJNXOrgDto> list) {
        if (ObjectUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<FjnxOrgBusinessRelation> fjnxOrgBusinessRelationList = fjnxOrgBusinessRelationMapper.selectList(Wrappers.emptyWrapper());
        final ArrayList<FjnxOrg> resultList = new ArrayList<>();
        Date syncDateTime = new Date();
        list.forEach(item -> {
            FjnxOrg tempOrg = new FjnxOrg();
            BeanUtils.copyBeanProp(tempOrg, item);

            tempOrg.setLastSyncTime(syncDateTime);
            tempOrg.setBusinessParentCode(tempOrg.getOrgParent());

            Optional<FjnxOrgBusinessRelation> first = fjnxOrgBusinessRelationList.stream().filter(b -> b.getOrgCode().equals(item.getOrgCode())).findFirst();
            if (first.isPresent()) {
                if (list.stream().anyMatch(y -> y.getOrgCode().equals(first.get().getBusinessParentCode()))) {
                    tempOrg.setBusinessParentCode(first.get().getBusinessParentCode());
                } else {
                    log.error("设置fjnx业务父级机构失败，机构名称:{}，机构编码:{}，业务父级机构编码:{}", item.getOrgName(), first.get().getOrgCode(), first.get().getBusinessParentCode());
                }
            }
            resultList.add(tempOrg);
        });
        return resultList;
    }

}
