package com.mosty.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.mapper.DeptMapper;
import com.mosty.base.mapper.TbOrgMapper;
import com.mosty.base.mapper.TbUserMapper;
import com.mosty.base.model.dto.base.GetDeptListDTO;
import com.mosty.base.model.dto.base.SysDeptDTO;
import com.mosty.base.model.entity.base.TbOrg;
import com.mosty.base.model.entity.base.TbUser;
import com.mosty.base.model.query.base.GetSysDeptListQuery;
import com.mosty.base.model.query.base.SysDeptQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.service.DeptService;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.SysUserDept;
import com.mosty.common.core.business.entity.vo.SysRoleVO;
import com.mosty.common.core.business.mapper.SysUserDeptMapper;
import com.mosty.common.core.business.mapper.SysUserMapper;
import com.mosty.common.core.business.service.SysRoleService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author dw
 * @since 2022/8/1
 **/
@Service
@AllArgsConstructor
public class DeptServiceImpl extends ServiceImpl<DeptMapper, SysDept>
        implements DeptService {

    private final SysRoleService sysRoleService;
    private final TbOrgMapper tbOrgMapper;
    private final SysUserMapper sysUserMapper;
    private final TbUserMapper tbUserMapper;
    private final SysUserDeptMapper sysUserDeptMapper;

    @Override
    public DeptInfoVo getOrgByDeptId(String deptid) {
        DeptInfoVo vo = new DeptInfoVo();
        SysDept dept = this.baseMapper.selectById(deptid);
        if (dept != null) {
            vo.setOrgType(dept.getOrgType());
            vo.setOrgLevel(dept.getOrgLevel());
            String rootPath = dept.getRootPath();
            // 省局
            if (dept.getParentId() == 0) {
                this.setDept(vo, dept);
                return vo;
            }
            if (rootPath != null) {
                String[] paths = rootPath.split("_");
                if (paths.length == 2) {
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept1.getOrgLevel())) {
                        this.setDsz(vo, dept1);
                    }
                    return vo;
                } else if (paths.length == 3) {
//                    if ("30".equals(dept.getOrgLevel())) {
//
//                    }
                    this.setFxj(vo, dept);
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept1.getOrgLevel())) {
                        this.setDsz(vo, dept1);
                    }
                    return vo;
                } else if (paths.length >= 4) {
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[2]);
                    this.setFxj(vo, dept1);
                    SysDept dept2 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept2.getOrgLevel())) {
                        this.setDsz(vo, dept2);
                    }
                }
            }
        }
        return vo;
    }

    @Override
    public List<DeptInfoVo> getDeptAll() {
        List<SysDept> deptList = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .ne(SysDept::getOrgCode, "510000000000")
                        .ne(SysDept::getOrgCode, "511400000000")
                        .ne(SysDept::getOrgCode, "510100000000")
                        .ne(SysDept::getOrgCode, "5100002626")
        );
        List<DeptInfoVo> list = new ArrayList<>();
        deptList.forEach(item -> {
            DeptInfoVo dept = this.getOrgByDeptId(String.valueOf(item.getId()));
            list.add(dept);
        });
        return list;
    }

    @Override
    public List<DeptInfoVo> getChildDept(GetDeptListDTO dto) {
        SysDept dept = this.baseMapper.selectById(dto.getDeptid());
        List<DeptInfoVo> list = new ArrayList<>();
        DeptInfoVo vo = this.getOrgByDeptId(String.valueOf(dept.getId()));
        list.add(vo);
        // 查询下级部门
        List<SysDept> tempList = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getParentId, dept.getId())
                        .notIn(!CollectionUtils.isEmpty(dto.getInDeptids()), SysDept::getId, dto.getInDeptids())
                        .in(!CollectionUtils.isEmpty(dto.getLevels()), SysDept::getOrgLevel, dto.getLevels())
                        .eq(SysDept::getXtZxbz, "0")
        );
        tempList.forEach(item -> {
            DeptInfoVo temp = this.getOrgByDeptId(String.valueOf(item.getId()));
            list.add(temp);
        });
        return list;
    }

    @Override
    public DeptInfoVo getOrgByOrgcode(String orgcode) {
        DeptInfoVo vo = new DeptInfoVo();
        SysDept dept = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getOrgCode, orgcode)
        );
        if (dept != null) {
            vo.setOrgType(dept.getOrgType());
            vo.setOrgLevel(dept.getOrgLevel());
            vo.setOrgJc(dept.getOrgJc());
            vo.setOrgQc(dept.getOrgQc());
            String rootPath = dept.getRootPath();
            // 省局
            if (dept.getParentId() == 0) {
                this.setDept(vo, dept);
                return vo;
            }
            if (rootPath != null) {
                String[] paths = rootPath.split("_");
                if (paths.length == 2) {
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept1.getOrgLevel())) {
                        this.setDsz(vo, dept1);
                    }
                    return vo;
                } else if (paths.length == 3) {
//                    if ("30".equals(dept.getOrgLevel())) {
//                    }
                    this.setFxj(vo, dept);
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept1.getOrgLevel())) {
                        this.setDsz(vo, dept1);
                    }
                    return vo;
                } else if (paths.length >= 4) {
                    this.setDept(vo, dept);
                    SysDept dept1 = this.baseMapper.selectById(paths[2]);
                    this.setFxj(vo, dept1);
                    SysDept dept2 = this.baseMapper.selectById(paths[1]);
                    if ("20".equals(dept2.getOrgLevel())) {
                        this.setDsz(vo, dept2);
                    }
                }
            }
        } else {
            return null;
        }
        return vo;
    }

    @Override
    public List<SysDeptDTO> getPcsByFxjdm(String orgcode) {
        List<SysDeptDTO> rList = new ArrayList<>();
        SysDept dept = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getOrgCode, orgcode)
        );
        if (dept != null) {
            List<SysDept> list = this.baseMapper.selectList(
                    new LambdaQueryWrapper<SysDept>()
                            .eq(SysDept::getParentId, dept.getId())
                            .like(SysDept::getOrgName, "派出所")
            );
            list.forEach(item -> {
                SysDeptDTO dto = new SysDeptDTO();
                BeanUtils.copyProperties(item, dto);
                rList.add(dto);
            });
        }
        return rList;
    }

    @Override
    public List<SysDept> getOrg(SysDeptQuery deptQuery) {
        List<String> orgBizType = StringUtils.isNotBlank(deptQuery.getOrgBizTypes()) ? Arrays.asList(deptQuery.getOrgBizTypes().split(",")) : null;
        List<String> orgLevel = StringUtils.isNotBlank(deptQuery.getOrgLevels()) ? Arrays.asList(deptQuery.getOrgLevels().split(",")) : null;
        return this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .in(!CollectionUtils.isEmpty(orgBizType), SysDept::getOrgBizType, orgBizType)
                        .in(!CollectionUtils.isEmpty(orgLevel), SysDept::getParentId, orgLevel)
        );
    }

    @Override
    public List<SysDept> getOrganizationList(GetSysDeptListQuery query) {
        if (null == query) {
            return null;
        }

        //组装查询参数
        QueryWrapper<SysDept> qw = new QueryWrapper<>();

        //主键
        if (null != query.getId()) {
            qw.eq("id", query.getId());
        }

        //组织机构代码
        if (!StringUtils.isBlank(query.getOrgCode())) {
            qw.eq("org_code", query.getOrgCode());
        }

        //组织机构名称
        if (!StringUtils.isBlank(query.getOrgName())) {
            qw.like("org_name", query.getOrgName());
        }

        //组织机构类型
        if (!StringUtils.isBlank(query.getOrgType())) {
            qw.in("org_type", Arrays.asList(query.getOrgType().split(",")));
        }

        //不需要的组织机构类型
        if (!StringUtils.isBlank(query.getOrgTypeRid())) {
            qw.notIn("org_type", Arrays.asList(query.getOrgTypeRid().split(",")));
        }

        //组织机构等级
        if (!StringUtils.isBlank(query.getOrgLevel())) {
            qw.in("org_level", Arrays.asList(query.getOrgLevel().split(",")));
        }

        //不需要的组织机构等级
        if (!StringUtils.isBlank(query.getOrgLevelRid())) {
            qw.notIn("org_level", Arrays.asList(query.getOrgLevelRid().split(",")));
        }

        //组织机构业务类型
        if (!StringUtils.isBlank(query.getOrgBizType())) {
            qw.in("org_biz_type", Arrays.asList(query.getOrgBizType().split(",")));
        }

        //不需要的组织机构业务类型
        if (!StringUtils.isBlank(query.getOrgBizTypeRid())) {
            qw.notIn("org_biz_type", Arrays.asList(query.getOrgBizTypeRid().split(",")));
        }

        //组织机构编号
        if (!StringUtils.isBlank(query.getOrgNo())) {
            qw.eq("org_no", query.getOrgNo());
        }

        //上级组织机构主键ID
        if (null != query.getParentId()) {
            qw.eq("parent_id", query.getParentId());
        }

        //组织机构简称
        if (!StringUtils.isBlank(query.getOrgJc())) {
            qw.like("org_jc", query.getOrgJc());
        }

        //组织机构全称
        if (!StringUtils.isBlank(query.getOrgQc())) {
            qw.like("org_qc", query.getOrgQc());
        }

        //组织机构地址
        if (!StringUtils.isBlank(query.getAddress())) {
            qw.like("address", query.getAddress());
        }

        //组织机构电话
        if (!StringUtils.isBlank(query.getLinkTel())) {
            qw.like("link_tel", query.getLinkTel());
        }

        //组织机构联系人
        if (!StringUtils.isBlank(query.getLinkMan())) {
            qw.like("link_man", query.getLinkMan());
        }

        //组织机构联系人电话
        if (!StringUtils.isBlank(query.getLinkManTel())) {
            qw.like("link_man_tel", query.getLinkManTel());
        }

        //组织机构主页地址
        if (!StringUtils.isBlank(query.getWebUrl())) {
            qw.like("web_url", query.getWebUrl());
        }

        //组织机构邮箱地址
        if (!StringUtils.isBlank(query.getEmail())) {
            qw.like("email", query.getEmail());
        }

        //组织机构行政区划
        if (!StringUtils.isBlank(query.getXzqh())) {
            qw.in("xzqh", Arrays.asList(query.getXzqh().split(",")));
        }

        //注销标志（0 有效， 1 失效）
        if (null != query.getXtZxbz()) {
            qw.eq("xt_zxbz", query.getXtZxbz());
        }

        //正序字段（使用英语逗号“,”分隔）
        if (!StringUtils.isBlank(query.getOrderByAsc())) {
            for (String s : query.getOrderByAsc().split(",")) {
                qw.orderByAsc(s);
            }
        } else {
            qw.orderByAsc("org_code");
        }

        //倒序字段（使用英语逗号“,”分隔）
        if (!StringUtils.isBlank(query.getOrderByDesc())) {
            for (String s : query.getOrderByDesc().split(",")) {
                qw.orderByDesc(s);
            }
        }

        return this.baseMapper.selectList(qw);
    }

    @Override
    public void resetRootPath() {
        List<SysDept> deptList = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .isNotNull(SysDept::getBz)
                        .ne(SysDept::getBz, "")
        );
        deptList.forEach(dept -> {
            if (StringUtils.isNotBlank(dept.getRootPath())) {
                // 同步rootPath
                if (!dept.getRootPath().contains("_510000000000")) {
                    dept.setRootPath("_510000000000" + dept.getRootPath());
                }
                List<String> rootPathList = Arrays.asList(dept.getRootPath().split("_"));
                rootPathList = rootPathList.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
                String root = rootPathList.stream().map(rootPath -> {
                    SysDept sysDept = this.baseMapper.selectOne(
                            new LambdaQueryWrapper<SysDept>()
                                    .eq(SysDept::getOrgCode, rootPath)
                    );
                    if (sysDept != null) {
                        return String.valueOf(sysDept.getId());
                    }
                    return "";
                }).collect(Collectors.joining("_"));
                dept.setRootPath(root + "_" + dept.getId());
                // 同步parentId
                if (!"0".equals(dept.getBz()) && !"".equals(dept.getBz()) && dept.getBz() != null) {
                    String parentCode = dept.getBz();
                    SysDept sysDept = this.baseMapper.selectOne(
                            new LambdaQueryWrapper<SysDept>()
                                    .eq(SysDept::getOrgCode, parentCode)
                    );
                    dept.setParentId(sysDept.getId());
                    dept.setBz("");
                }
                this.baseMapper.updateById(dept);
            }
        });
    }

    @Override
    public String getSsbm(String ssbmdm, String isChild) {
        isChild = StringUtils.isNotBlank(isChild) ? isChild : "1";
        UserInfo user = UserInfoManager.getUser();
        // 如果用户信息存在，先查询用户权限
        SysRoleVO role = null;
        if (StringUtils.isBlank(ssbmdm)) {
            if (user != null) {
                ssbmdm = user.getDeptCode();
                // 查询用户权限
                List<SysRoleVO> userRoles = sysRoleService.getUserRoleList(user.getUserId());
                if (!CollectionUtils.isEmpty(userRoles)) {
                    int level = Integer.parseInt(userRoles.get(0).getDataPermissionLevel());
                    role = userRoles.get(0);
                    for (SysRoleVO item : userRoles) {
                        if (level > Integer.parseInt(item.getDataPermissionLevel())) {
                            level = Integer.parseInt(item.getDataPermissionLevel());
                            role = item;
                        }
                    }
                }
            }
            if (role != null && !"5".equals(role.getDataPermissionLevel())) {
                String level = role.getDataPermissionLevel();
                if ("1".equals(level) || "2".equals(level)) {
                    return "1".equals(isChild) ? ssbmdm.substring(0, 2) : ssbmdm;
                } else if ("3".equals(level)) {
                    return "1".equals(isChild) ? ssbmdm.substring(0, 4) : ssbmdm;
                } else if ("4".equals(level)) {
                    //区县获取上级部门 截取到最后一个0
                    if (StringUtils.isNotEmpty(user.getFxjDeptCode())) {
                        return "1".equals(isChild) ? this.getssbm(user.getFxjDeptCode()) : ssbmdm;
                    } else {
                        return "1".equals(isChild) ? ssbmdm.substring(0, 6) : ssbmdm;
                    }
                } else if ("6".equals(level)) {
                    return ssbmdm;
                }
            } else {
                if ("1".equals(isChild)) {
                    SysDept dept = this.baseMapper.selectOne(
                            new LambdaQueryWrapper<SysDept>()
                                    .eq(SysDept::getXtZxbz, "0")
                                    .eq(SysDept::getOrgCode, ssbmdm)
                    );
                    if (dept == null) {
                        throw new BusinessException("部门信息不存在！");
                    }
                    if (StringUtils.isBlank(dept.getOrgLevel())) {
                        return ssbmdm;
                    }
                    switch (dept.getOrgLevel()) {
                        case "10":
                        case "11":
                        case "12":
                            return ssbmdm.substring(0, 2);
                        case "20":
                        case "21":
                        case "22":
                            return ssbmdm.substring(0, 4);
                        case "30":
                        case "31":
                        case "32":
                            return ssbmdm.substring(0, 6);
                        case "40":
                            return ssbmdm.substring(0, 8);
                        default:
                            return ssbmdm;
                    }
                }
            }
        } else {
            if ("1".equals(isChild)) {
                SysDept dept = this.baseMapper.selectOne(
                        new LambdaQueryWrapper<SysDept>()
                                .eq(SysDept::getXtZxbz, "0")
                                .eq(SysDept::getOrgCode, ssbmdm)
                );
                if (dept == null) {
                    throw new BusinessException("部门信息不存在！");
                }
                if (StringUtils.isBlank(dept.getOrgLevel())) {
                    return ssbmdm;
                }
                switch (dept.getOrgLevel()) {
                    case "10":
                    case "11":
                    case "12":
                        return ssbmdm.substring(0, 2);
                    case "20":
                    case "21":
                    case "22":
                        return ssbmdm.substring(0, 4);
                    case "30":
                    case "31":
                    case "32":
                        return ssbmdm.substring(0, 6);
                    case "40":
                        return ssbmdm.substring(0, 8);
                    default:
                        return ssbmdm;
                }
            }
        }
        return ssbmdm;
    }

    @Override
    public List<SysDept> getDeptByType(String type, String ssbmdm) {
        String level = "40";
        if ("01".equals(type)) {
            level = "20";
        } else if ("02".equals(type)) {
            level = "30";
        } else if ("03".equals(type)) {
            level = "40";
        }
        String parentId = null;
        if (StringUtils.isNotBlank(ssbmdm)) {
            SysDept dept = this.baseMapper.selectOne(
                    new LambdaQueryWrapper<SysDept>()
                            .eq(SysDept::getOrgCode, ssbmdm)
            );
            if (dept == null) throw new BusinessException("部门未找到");
            SysDept parentDept = this.baseMapper.selectById(dept.getId());
            parentId = String.valueOf(parentDept.getId());
        }
        return this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getXtZxbz, "0")
                        .eq(SysDept::getOrgLevel, level)
                        .eq(StringUtils.isNotBlank(parentId), SysDept::getParentId, parentId)
                        .orderByAsc(SysDept::getOrgNo)
        );
    }


    @Override
    public List<String> getParentOrgCode(String ssbmdm) {
        SysDept dept = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getOrgCode, ssbmdm)
        );
        if (dept != null && !StringUtils.isBlank(dept.getRootPath())) {
            List<String> arr = Arrays.asList(dept.getRootPath().split("_"));
            return arr.stream().map(item -> {
                SysDept tempDept = this.baseMapper.selectById(item);
                if (tempDept != null) return tempDept.getOrgCode();
                return null;
            }).collect(Collectors.toList()).stream().filter(Objects::nonNull).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public SysDept getParentDept(String ssbmid) {
        SysDept dept = this.baseMapper.selectById(ssbmid);
        if (dept != null) {
            return this.baseMapper.selectById(dept.getParentId());
        }
        return null;
    }

    @Override
    public SysDept getSysDeptBySsbmdm(String ssbmdm) {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getOrgCode, ssbmdm)
        );
    }

    // 设置所属单位
    private void setDept(DeptInfoVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDeptid(String.valueOf(dept.getId()));
            vo.setDeptcode(dept.getOrgCode());
            vo.setDeptname(dept.getOrgName());
            vo.setOrgJc(dept.getOrgJc());
            vo.setOrgQc(dept.getOrgQc());
        }
    }

    // 设置分县局
    private void setFxj(DeptInfoVo vo, SysDept dept) {
        if (dept != null) {
            vo.setFxjid(String.valueOf(dept.getId()));
            vo.setFxjcode(dept.getOrgCode());
            vo.setFxjname(dept.getOrgName());
            vo.setFxjjc(dept.getOrgJc());
            vo.setFxjqc(dept.getOrgQc());
        }
    }

    // 设置地市州
    private void setDsz(DeptInfoVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDszid(String.valueOf(dept.getId()));
            vo.setDszcode(dept.getOrgCode());
            vo.setDszname(dept.getOrgName());
            vo.setDszjc(dept.getOrgJc());
            vo.setDszqc(dept.getOrgQc());
        }
    }

    @Override
    public void tbZjjgDm() {
        List<TbOrg> tbOrgList = this.tbOrgMapper.selectList(new LambdaQueryWrapper<TbOrg>().orderByAsc(TbOrg::getOrgId));
        if (!CollectionUtils.isEmpty(tbOrgList)) {
            for (TbOrg tbOrg : tbOrgList) {
                SysDept sysDept = this.getSysDeptBySsbmdm(tbOrg.getOrgId());
                if (ObjectUtils.isEmpty(sysDept)) {
                    sysDept = new SysDept();
                    sysDept.setOrgCode(tbOrg.getOrgId());
                    sysDept.setOrgName(tbOrg.getOrgName());
                    sysDept.setOrgType("01");
                    sysDept.setOrgLevel(tbOrg.getOrgLevel());
                    if (tbOrg.getOrgName().contains("派出所")) {
                        sysDept.setOrgBizType("02");
                    } else if (tbOrg.getOrgName().contains("特")) {
                        sysDept.setOrgBizType("03");
                    } else if (tbOrg.getOrgName().contains("治安")) {
                        sysDept.setOrgBizType("04");
                    } else if (tbOrg.getOrgName().contains("禁毒")) {
                        sysDept.setOrgBizType("05");
                    } else if (tbOrg.getOrgName().contains("交警")) {
                        sysDept.setOrgBizType("06");
                    } else if (tbOrg.getOrgName().contains("刑侦")) {
                        sysDept.setOrgBizType("07");
                    } else if (tbOrg.getOrgName().contains("指挥")) {
                        sysDept.setOrgBizType("08");
                    } else {
                        sysDept.setOrgBizType("09");
                    }
                    sysDept.setOrgNo("99");
                    sysDept.setOrgJc(tbOrg.getOrgJc());
                    sysDept.setOrgQc(tbOrg.getOrgName());
                    sysDept.setXtZxbz(0);

                    this.baseMapper.insert(sysDept);
                    //最后添加
                    SysDept sysDept1 = this.getSysDeptBySsbmdm(tbOrg.getParentId());
                    if (!ObjectUtils.isEmpty(sysDept1)) {
                        sysDept.setRootPath(sysDept1.getRootPath() + "_" + sysDept.getId());
                        sysDept.setParentId(sysDept1.getId());
                    }
                    this.baseMapper.updateById(sysDept);
                }
            }
        }


    }

    @Override
    public void tbZzjgRy() {
        List<TbUser> tbUsers = this.tbUserMapper.selectList(new LambdaQueryWrapper<TbUser>());
        if (!CollectionUtils.isEmpty(tbUsers)) {
            for (TbUser user : tbUsers) {
                SysUser sysUser1 = this.sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getIdEntityCard, user.getSfzh()).eq(SysUser::getXtZxbz, "0"));
                if (ObjectUtils.isEmpty(sysUser1)) {
                    SysUser sysUser = new SysUser();
                    sysUser.setPositionName(user.getZw());
                    sysUser.setIsVirtualUser("02");
                    sysUser.setLoginName(user.getName());
                    sysUser.setPassword("E10ADC3949BA59ABBEcm9OiHRC56E057F20F883E");
                    sysUser.setUserName(user.getName());
                    sysUser.setUserType("01");
                    sysUser.setMobile(user.getDhhm());
                    sysUser.setTelePhone(user.getDh());
                    sysUser.setIdEntityCard(user.getSfzh());
                    sysUser.setTypeName("正式民警");
                    sysUser.setInDustRialId(user.getJh());
                    sysUser.setInDustRialId(user.getJh());
                    //计算男女
                    int gender = Integer.parseInt(user.getSfzh().substring(16, 17));
                    if (gender % 2 == 1) {
                        sysUser.setSex("1");
                    } else {
                        sysUser.setSex("2");
                    }
                    sysUser.setNation("01");
                    sysUser.setType("03");
                    sysUser.setXtZxbz(0);
                    this.sysUserMapper.insert(sysUser);
                    //根据所属部门查询单位
                    SysDept sysDept = this.getSysDeptBySsbmdm(user.getSsbmdm());
                    if (!ObjectUtils.isEmpty(sysDept)) {
                        if (sysDept.getOrgName().contains("派出所")) {
                            sysUser.setType("03");
                        } else if (sysDept.getOrgName().contains("特")) {
                            sysUser.setType("01");
                        } else if (sysDept.getOrgName().contains("交警"))  {
                            sysUser.setType("02");
                        }
                        this.sysUserMapper.updateById(sysUser);
                        SysUserDept sysUserDept = new SysUserDept();
                        sysUserDept.setUserId(sysUser.getId());
                        sysUserDept.setDeptId(sysDept.getId());
                        this.sysUserDeptMapper.insert(sysUserDept);
                    }

                } else {
                    SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, sysUser1.getId()));
                    SysDept sysDept = this.getSysDeptBySsbmdm(user.getSsbmdm());
                    if (!ObjectUtils.isEmpty(sysDept)) {
                        if(ObjectUtils.isEmpty(sysUserDept)){
                            sysUserDept =new SysUserDept();
                            sysUserDept.setUserId(sysUser1.getId());
                        }
                        sysUserDept.setDeptId(sysDept.getId());
                        this.sysUserDeptMapper.insert(sysUserDept);
                    }
                }


            }
        }
    }

    public String getssbm(String ssbmdm) {
        if (StringUtils.isNotEmpty(ssbmdm) && ssbmdm.length() == 12) {
            String[] split = ssbmdm.split("");
            for (int i = split.length - 1; i >= 0; i--) {
                String s = split[i];
                if (!s.equals("0")) {
                    ssbmdm = ssbmdm.substring(0, i + 1);
                    break;
                }
            }
        }
        return ssbmdm;
    }


}
