package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.PersonnelBusiness;
import com.yeejoin.amos.boot.module.hygf.api.entity.StdUserEmpower;
import com.yeejoin.amos.boot.module.hygf.api.entity.UnitInfo;
import com.yeejoin.amos.boot.module.hygf.api.entity.UserMessage;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UnitInfoMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IPersonnelBusinessService;
import com.yeejoin.amos.boot.module.hygf.api.util.DesUtil;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.GroupUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * 人员业务信息表服务实现类
 *
 * @author system_generator
 * @date 2023-09-01
 */
@Service
public class PersonnelBusinessServiceImpl extends BaseService<PersonnelBusinessDto, PersonnelBusiness, PersonnelBusinessMapper> implements IPersonnelBusinessService {
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    UnitInfoMapper unitInfoMapper;
    @Autowired
    UserEmpowerMapper userEmpowerMapper;
    @Autowired
    UserMessageMapper userMessageMapper;
    @Value("${dealer.appcode}")
    private String appCodes;
    @Value("${amos.secret.key}")
    String secretKey;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Value("${hygf.user.group.id}")
    private long userGroupId;

    @Value("${hygf.user.group.empty}")
    private long userGroupempty;


    private final Logger logger = LoggerFactory.getLogger(PersonnelBusinessServiceImpl.class);

    /**
     * 分页查询
     */
    public Page<PersonnelBusinessDto> queryForPersonnelBusinessPage(Page<PersonnelBusinessDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<PersonnelBusinessDto> queryForPersonnelBusinessList() {
        return this.queryForList("", false);
    }

    @Override
    public IPage<CompanyDtoUserDto> getCompanyDtoUserDto(CompanyDtoUserDto dto) {

        Map<String, String> map = personnelBusinessMapper.getorgcode(dto.getAmosUnitId());
        dto.setAmosUnitOrgCode(map.get("orgCode"));
        IPage<CompanyDtoUserDto> pag = personnelBusinessMapper.getCompanyDtoUserDtopage(dto);

        return pag;
    }

    @Transactional
    public void savePersonnelBusiness(UserDataDto model) {
        UserDataZHDto userDataZHDto = model.getUserDataZHDto();
        UserDataJBDto userDataJBDto = model.getUserDataJBDto();
        FeignClientResult<AgencyUserModel> userResult = null;
        //新增平台用户
        try {
            // 1 创建平台用户
            List<RoleModel> userRoleList = new ArrayList<>();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(userDataZHDto.getUserName());
            agencyUserModel.setRealName(userDataJBDto.getRealName());
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            agencyUserModel.setRePassword(DesUtil.encode(userDataZHDto.getRePassword(), secretKey));
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(userDataJBDto.getEmergencyTelephone());
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userDataZHDto.getRole());
            orgRoles.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userRoleList);
            // agencyUserModel.setAppCodes(split);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            // 将创建用户加入用户组
            userResult = Privilege.agencyUserClient.create(agencyUserModel);
            if (userResult == null || userResult.getStatus() != 200) {
                throw new BadRequest("新增人员失败！" + userResult.getDevMessage());
            }
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            for (Long aLong : userDataZHDto.getRole()) {
                Privilege.groupUserClient.create(aLong, userId);
            }


            //新增人员基础信息表
            PublicAgencyUser publicAgencyUser = new PublicAgencyUser();
            publicAgencyUser.setRealName(userDataJBDto.getRealName());
            publicAgencyUser.setGender(userDataJBDto.getGender());
            publicAgencyUser.setJobNumber(userDataJBDto.getJobNumber());
            publicAgencyUser.setIdType(userDataJBDto.getIdType());
            publicAgencyUser.setIdNumber(userDataJBDto.getIdNumber());
            publicAgencyUser.setAmosId(userDataJBDto.getAmosUnitId());

            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.seleteOne(userDataJBDto.getAmosUnitId());
            if (companyResult == null || companyResult.getStatus() != 200) {
                throw new BadRequest("新增人员失败！" + companyResult.getDevMessage());
            }
            publicAgencyUser.setAmosOrgCode(companyResult.getResult().getOrgCode());
            publicAgencyUser.setAmosUserId(userResult.getResult().getUserId());
            publicAgencyUser.setAmosUserName(userDataZHDto.getUserName());
            publicAgencyUser.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            publicAgencyUser.setRole(JSON.toJSONString(userDataZHDto.getRole()));
            publicAgencyUser.setLockStatus("UNLOCK");
            publicAgencyUser.setLockTime(new Date());
            publicAgencyUser.setHeight(userDataJBDto.getHeight());
            publicAgencyUser.setWeight(userDataJBDto.getWeight());
            publicAgencyUser.setEmergencyTelephone(userDataJBDto.getEmergencyTelephone());
            publicAgencyUser.setDomicileAddress(userDataJBDto.getDomicileAddress());
            publicAgencyUser.setPosition(userDataJBDto.getPosition() != null ? JSON.toJSONString(userDataJBDto.getPosition()) : null);
            publicAgencyUser.setNowAddress(userDataJBDto.getNowAddress());
            publicAgencyUser.setNativePlace(userDataJBDto.getNativePlace());
            publicAgencyUser.setPoliticalOutlook(userDataJBDto.getPoliticalOutlook());
            publicAgencyUserMapper.insert(publicAgencyUser);

            PersonnelBusiness re = new PersonnelBusiness();
            FeignClientResult<CompanyModel> companyResult1 = Privilege.companyClient.seleteOne(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            if (companyResult1 == null || companyResult1.getStatus() != 200) {
                throw new BadRequest("新增人员失败！" + companyResult1.getDevMessage());
            }
            re.setRegionalCompaniesSeq(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            re.setRegionalCompaniesName(companyResult1.getResult().getCompanyName());
            re.setRegionalCompaniesCode(companyResult1.getResult().getOrgCode());
            re.setCertificate(model.getUserDataZZDto() != null ? JSON.toJSONString(model.getUserDataZZDto().getCertificate()) : null);
            re.setAmosUnitId(companyResult.getResult().getSequenceNbr());
            re.setAmosUnitName(companyResult.getResult().getCompanyName());
            re.setAmosUnitOrgCode(companyResult.getResult().getOrgCode());
            re.setFoundationId(publicAgencyUser.getSequenceNbr());
            re.setAmosDealerId(model.getAmosDealerId());
            personnelBusinessMapper.insert(re);

            //增加人员权限
            List<String> lisk = new ArrayList<>();
            StdUserEmpower stdUserEmpower = new StdUserEmpower();

            lisk.add(re.getRegionalCompaniesCode());
            stdUserEmpower.setAmosUserId(publicAgencyUser.getAmosUserId());
            stdUserEmpower.setAmosOrgCode(lisk);
            stdUserEmpower.setPermissionType("HYGF");
            userEmpowerMapper.insert(stdUserEmpower);


        } catch (Exception e) {
            if (userResult != null && userResult.getResult() != null
                    && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
            }
            log.error(e.getMessage(), e);
            throw new BadRequest(e.getMessage());
        }

    }


    @Transactional
    public void updatePersonnelBusiness(UserDataDto model, long id) {

        PublicAgencyUser publicAgencyUser = publicAgencyUserMapper.selectById(id);


        UserDataZHDto userDataZHDto = model.getUserDataZHDto();
        UserDataJBDto userDataJBDto = model.getUserDataJBDto();
        FeignClientResult<AgencyUserModel> userResult = null;

        try {
            List<Long> newRole = userDataZHDto.getRole();
            List<Long> oldRole = JSONArray.parseArray(publicAgencyUser.getRole(), Long.class);
            if(userDataZHDto.getHasOperationRecords()) {
                for (Long item : oldRole) {
                    if (!newRole.contains(item)) {
                        throw new BadRequest("角色只能增加, 不能删除");
                    }
                }
            }

            //去掉空角色
            List<Long> role = userDataZHDto.getRole();
            if(CollectionUtil.isNotEmpty(role)){
                if(role.contains(userGroupempty)){
                    logger.info("移除空角色");
                    role.remove(userGroupempty);
                }
            }
            // 1 修改平台用户
            List<RoleModel> userRoleList = new ArrayList<>();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(userDataZHDto.getUserName());
            agencyUserModel.setRealName(userDataJBDto.getRealName());
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            agencyUserModel.setRePassword(DesUtil.encode(userDataZHDto.getRePassword(), secretKey));
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(userDataJBDto.getEmergencyTelephone());
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userDataZHDto.getRole());
            orgRoles.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userRoleList);
            //agencyUserModel.setAppCodes(split);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            // 将创建用户加入用户组
            userResult = Privilege.agencyUserClient.update(agencyUserModel, publicAgencyUser.getAmosUserId());
            if (userResult == null || userResult.getStatus() != 200) {
                throw new BadRequest("修改人员失败！" + userResult.getDevMessage());
            }
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            for (Long aLong : userDataZHDto.getRole()) {
                Privilege.groupUserClient.create(aLong, userId);
            }


            //修改人员基础信息表
            publicAgencyUser.setRealName(userDataJBDto.getRealName());
            publicAgencyUser.setGender(userDataJBDto.getGender());
            publicAgencyUser.setJobNumber(userDataJBDto.getJobNumber());
            publicAgencyUser.setIdType(userDataJBDto.getIdType());
            publicAgencyUser.setIdNumber(userDataJBDto.getIdNumber());
            publicAgencyUser.setAmosId(userDataJBDto.getAmosUnitId());

            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.seleteOne(userDataJBDto.getAmosUnitId());
            if (companyResult == null || companyResult.getStatus() != 200) {
                throw new BadRequest("修改人员失败！" + companyResult.getDevMessage());
            }
            publicAgencyUser.setAmosOrgCode(companyResult.getResult().getOrgCode());
            publicAgencyUser.setAmosUserName(userDataZHDto.getUserName());
            publicAgencyUser.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            publicAgencyUser.setRole(JSON.toJSONString(userDataZHDto.getRole()));
            publicAgencyUser.setLockStatus("UNLOCK");
            publicAgencyUser.setLockTime(new Date());
            publicAgencyUser.setHeight(userDataJBDto.getHeight());
            publicAgencyUser.setWeight(userDataJBDto.getWeight());
            publicAgencyUser.setEmergencyTelephone(userDataJBDto.getEmergencyTelephone());
            publicAgencyUser.setDomicileAddress(userDataJBDto.getDomicileAddress());
            publicAgencyUser.setPosition(userDataJBDto.getPosition() != null ? JSON.toJSONString(userDataJBDto.getPosition()) : null);
            publicAgencyUser.setNowAddress(userDataJBDto.getNowAddress());
            publicAgencyUser.setNativePlace(userDataJBDto.getNativePlace());
            publicAgencyUser.setPoliticalOutlook(userDataJBDto.getPoliticalOutlook());
            publicAgencyUserMapper.updateById(publicAgencyUser);


            LambdaQueryWrapper<PersonnelBusiness> qug = new LambdaQueryWrapper<>();
            qug.eq(PersonnelBusiness::getFoundationId, publicAgencyUser.getSequenceNbr());
            PersonnelBusiness re = personnelBusinessMapper.selectOne(qug);

            FeignClientResult<CompanyModel> companyResult1 = Privilege.companyClient.seleteOne(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            if (companyResult1 == null || companyResult1.getStatus() != 200) {
                throw new BadRequest("修改人员失败！" + companyResult1.getDevMessage());
            }
            re.setRegionalCompaniesSeq(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            re.setRegionalCompaniesName(companyResult1.getResult().getCompanyName());
            re.setRegionalCompaniesCode(companyResult1.getResult().getOrgCode());
            re.setCertificate(model.getUserDataZZDto() != null ? JSON.toJSONString(model.getUserDataZZDto().getCertificate()) : null);
            re.setAmosUnitId(companyResult.getResult().getSequenceNbr());
            re.setAmosUnitName(companyResult.getResult().getCompanyName());
            re.setAmosUnitOrgCode(companyResult.getResult().getOrgCode());
            personnelBusinessMapper.updateById(re);

            //增加人员权限
            List<String> lisk = new ArrayList<>();
            LambdaQueryWrapper<StdUserEmpower> uo = new LambdaQueryWrapper();
            uo.eq(StdUserEmpower::getAmosUserId, publicAgencyUser.getAmosUserId());
            StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(uo);
            // lisk.add(publicAgencyUser.getAmosOrgCode());
            lisk.add(re.getRegionalCompaniesCode());
            if (stdUserEmpower != null) {
                stdUserEmpower.setAmosUserId(publicAgencyUser.getAmosUserId());
                stdUserEmpower.setAmosOrgCode(lisk);
                userEmpowerMapper.updateById(stdUserEmpower);
            } else {
                stdUserEmpower = new StdUserEmpower();
                stdUserEmpower.setAmosUserId(publicAgencyUser.getAmosUserId());
                stdUserEmpower.setAmosOrgCode(lisk);
                stdUserEmpower.setPermissionType("HYGF");
                userEmpowerMapper.insert(stdUserEmpower);
            }


        } catch (Exception e) {

            log.error(e.getMessage(), e);
            throw new BadRequest(e.getMessage());
        }

    }


    @Transactional
    public void replace(String id) {
        try {

            //获取当前用户
            LambdaQueryWrapper<PublicAgencyUser> qud = new LambdaQueryWrapper<>();
            qud.eq(PublicAgencyUser::getSequenceNbr, id);
            PublicAgencyUser publicAgencyUse = publicAgencyUserMapper.selectOne(qud);

            LambdaQueryWrapper<PersonnelBusiness> qug = new LambdaQueryWrapper<>();
            qug.eq(PersonnelBusiness::getFoundationId, publicAgencyUse.getSequenceNbr());
            PersonnelBusiness personnelBusines = personnelBusinessMapper.selectOne(qug);
            personnelBusines.setUserType("2");
            personnelBusinessMapper.updateById(personnelBusines);

            //获取经销商管理员
            LambdaQueryWrapper<UnitInfo> qudg = new LambdaQueryWrapper<>();
            qudg.eq(UnitInfo::getAmosCompanySeq, personnelBusines.getAmosDealerId());
            UnitInfo unitInfo = unitInfoMapper.selectOne(qudg);

            LambdaQueryWrapper<PublicAgencyUser> qudx = new LambdaQueryWrapper<>();
            qudx.eq(PublicAgencyUser::getAmosUserId, unitInfo.getAdminUserId());
            PublicAgencyUser publicAgencyUsex = publicAgencyUserMapper.selectOne(qudx);

            LambdaQueryWrapper<PersonnelBusiness> qugf = new LambdaQueryWrapper<>();
            qugf.eq(PersonnelBusiness::getFoundationId, publicAgencyUsex.getSequenceNbr());
            PersonnelBusiness personnelBusinesx = personnelBusinessMapper.selectOne(qugf);
            personnelBusinesx.setUserType("1");
            personnelBusinessMapper.updateById(personnelBusinesx);

            unitInfo.setAdminLoginName(publicAgencyUse.getAmosUserName());
            unitInfo.setAdminPhone(publicAgencyUse.getEmergencyTelephone());
            unitInfo.setAdminUserId(publicAgencyUse.getAmosUserId());
            unitInfo.setAdminUserName(publicAgencyUse.getRealName());
            unitInfoMapper.updateById(unitInfo);

            //修改管理员
            List<Long> roidx = JSONArray.parseArray(publicAgencyUsex.getRole(), Long.class);


            //修改平台用户
            List<String> userId = new ArrayList<>();
            userId.add(publicAgencyUse.getAmosUserId());


            System.out.println("删除旧管理员===================================:" + publicAgencyUsex.getAmosUserId());
            List<String> userId1 = new ArrayList<>();
            if (roidx != null && !roidx.isEmpty() && roidx.size() == 1 && roidx.get(0).longValue() == userGroupId) {
                //新增空角色防止单位丢失

                userId1.add(publicAgencyUsex.getAmosUserId());
                Privilege.groupUserClient.create(userGroupempty, userId1);
            }

            //删除旧管理员
            Privilege.groupUserClient.deleteGroupUser(userGroupId, publicAgencyUsex.getAmosUserId());


            // 1 修改平台用户
            Privilege.groupUserClient.create(userGroupId, userId);


            System.out.println("新增角色用户===================================:" + userId);


            //修改权限
            if (roidx == null) {
                publicAgencyUsex.setRole(null);
            } else {
                roidx.remove(userGroupId);
                publicAgencyUsex.setRole(CollectionUtil.isEmpty(roidx) ? JSON.toJSONString(Arrays.asList(userGroupempty)) : JSON.toJSONString(roidx));
            }
            //修改当前用户角色权限
            List<Long> roid = JSONArray.parseArray(publicAgencyUse.getRole(), Long.class);
            if (roid == null) {
                roid = new ArrayList<>();
            }
            roid.add(userGroupId);
            if (roid.contains(userGroupempty)) {
                roid.remove(userGroupempty);
               // Privilege.groupUserClient.deleteGroupUser(userGroupempty, publicAgencyUsex.getAmosUserId());
                 personnelBusinessMapper.deleteRoleByUserId(publicAgencyUse.getAmosUserId(),userGroupempty);
                personnelBusinessMapper.deleteOrgRoleByUserId(publicAgencyUse.getAmosUserId(),userGroupempty);

            }
            publicAgencyUse.setRole(JSON.toJSONString(roid));

            publicAgencyUserMapper.updateById(publicAgencyUsex);
            publicAgencyUserMapper.updateById(publicAgencyUse);


            //旧管理员去除
            List<String> li = null;
            LambdaQueryWrapper<StdUserEmpower> uo = new LambdaQueryWrapper();
            uo.eq(StdUserEmpower::getAmosUserId, publicAgencyUsex.getAmosUserId());
            StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(uo);
            li = stdUserEmpower.getAmosOrgCode();

            if (stdUserEmpower != null) {
                stdUserEmpower.setAmosOrgCode(null);
                userEmpowerMapper.updateById(stdUserEmpower);

            } else {
                stdUserEmpower = new StdUserEmpower();
                stdUserEmpower.setAmosOrgCode(null);
                stdUserEmpower.setPermissionType("HYGF");
                stdUserEmpower.setAmosUserId(publicAgencyUsex.getAmosUserId());
                userEmpowerMapper.insert(stdUserEmpower);
            }


            //新管理员新增
            LambdaQueryWrapper<StdUserEmpower> uo1 = new LambdaQueryWrapper();
            uo1.eq(StdUserEmpower::getAmosUserId, publicAgencyUse.getAmosUserId());
            StdUserEmpower stdUserEmpower1 = userEmpowerMapper.selectOne(uo1);


            if (stdUserEmpower1 != null) {
                stdUserEmpower1.setAmosOrgCode(li);
                userEmpowerMapper.updateById(stdUserEmpower1);

            } else {
                stdUserEmpower1 = new StdUserEmpower();
                stdUserEmpower1.setAmosOrgCode(li);
                stdUserEmpower1.setPermissionType("HYGF");
                stdUserEmpower1.setAmosUserId(publicAgencyUse.getAmosUserId());
                userEmpowerMapper.insert(stdUserEmpower1);
            }

            List<String> userIds=new ArrayList<>();
            userIds.add(publicAgencyUse.getAmosUserId());
            UserMessage userMessage = new UserMessage(TaskTypeStationEnum.设置管理员.getCode(), personnelBusines.getSequenceNbr(), userIds.toString(), new Date(), "您已成为单位管理员。", personnelBusines.getAmosUnitOrgCode());

            userMessageMapper.insert(userMessage);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("设置失败！");
        }
    }


    @Override
    public UserDataDto getPersonnelBusinessById(String id) {

        LambdaQueryWrapper<PublicAgencyUser> qud = new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getSequenceNbr, id);
        PublicAgencyUser publicAgencyUse = publicAgencyUserMapper.selectOne(qud);

        LambdaQueryWrapper<PersonnelBusiness> qug = new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId, publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines = personnelBusinessMapper.selectOne(qug);

        UserDataZHDto userDataZHDto = new UserDataZHDto();
        UserDataJBDto userDataJBDto = new UserDataJBDto();
        UserDataZZDto userDataZZDto = new UserDataZZDto();

        userDataZZDto.setCertificate(personnelBusines.getCertificate() != null ? JSONArray.parseArray(personnelBusines.getCertificate(), JSONObject.class) : null);
        userDataZHDto.setRole(JSONArray.parseArray(publicAgencyUse.getRole(), long.class));
        userDataZHDto.setUserName(publicAgencyUse.getAmosUserName());

        BeanUtils.copyProperties(publicAgencyUse, userDataJBDto);
        userDataJBDto.setPosition(JSONArray.parseArray(publicAgencyUse.getPosition(), String.class));
        userDataJBDto.setRegionalCompaniesSeq(personnelBusines.getRegionalCompaniesSeq() != null ? personnelBusines.getRegionalCompaniesSeq().toString() : null);
        userDataJBDto.setAmosUnitId(personnelBusines.getAmosUnitId());

        Boolean hasOperationRecords = hasOperationRecords(id);
        userDataZHDto.setHasOperationRecords(hasOperationRecords);
        userDataJBDto.setHasOperationRecords(hasOperationRecords);
        userDataJBDto.setPageType("look");
        if (publicAgencyUse.getRole().contains(userGroupempty + "")) {
            // 如果是空角色，区域公司和角色可以修改
            userDataZHDto.setUnallowModify("allow");
            userDataJBDto.setUnallowModify("allow");
        } else {
            // 有业务参与不可以编辑
            userDataZHDto.setUnallowModify(hasOperationRecords ? "unallow" : "allow");
            userDataJBDto.setUnallowModify(hasOperationRecords ? "unallow" : "allow");
        }

        return new UserDataDto(userDataZHDto, userDataJBDto, userDataZZDto);
    }

    /**
     * 用户是否有业务操作
     *
     * @param id id
     * @return {@link  Boolean}
     * @throws
     * @author yangyang
     * @date 2024/7/3 16:24
     */
    public Boolean hasOperationRecords(String id) {
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        Boolean operateRecord = false;
        String userId = personnelBusinessMapper.selectUserInfo(Long.parseLong(id));
        //添加校验，如果业务表里面有相关的用户id不能删除
        List<String> tableName = personnelBusinessMapper.selectHygfTableName();
        if (CollectionUtil.isNotEmpty(tableName)) {
            for (String table : tableName) {
                // 排除人员业务信息表, 经销商人员信息, 人员消息
                if ("hygf_personnel_business".equals(table) || "hygf_unit_info".equals(table) || "hygf_user_message".equals(table)) {
                    continue;
                }
                int count = personnelBusinessMapper.countByUserId(table, userId);
                if (count > 0) {
                    operateRecord = true;
                    break;
                }
            }
        }
        return operateRecord;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteAllBySequenceNbr(Long sequenceNbr) {
        //        根据sequenceNbr查询用户userId
        String userId = personnelBusinessMapper.selectUserInfo(sequenceNbr);
        //添加校验，如果业务表里面有相关的用户id不能删除
        List<String> tableName = personnelBusinessMapper.selectHygfTableName();
        if (CollectionUtil.isNotEmpty(tableName)) {
            for (String table : tableName) {
                int count = personnelBusinessMapper.countByUserId(table, userId);
                if (count > 0) {
                    throw new BadRequest("该用户有操作记录无法删除！");
                }
            }
        }
        try {

//            删除平台表账号
            Privilege.agencyUserClient.multDeleteUser(userId);


//        删除privilege_agency_user表中数据
//            personnelBusinessMapper.deletePauByUserId(userId);
//        删除privilege_group_user表中数据
//            personnelBusinessMapper.deletePguByUserId(userId);
//        删除auth_login_info表中数据
//            personnelBusinessMapper.deleteAliByUserId(userId);
//        删除std_user_biz表中数据

            personnelBusinessMapper.deleteSubByUserId(userId);
//        删除hygf_personnel_business表中数据
            personnelBusinessMapper.deleteHpbByFoundationId(sequenceNbr);
//        删除std_user_empower表中数据
            personnelBusinessMapper.deleteSueByUserId(userId);


            return null;
        } catch (Exception e) {
            throw new BadRequest("删除失败！");
        }


    }

    @Override
    public Boolean deleteBySequenceNbrs(String sequenceNbrs) {
        //根据sequenceNbr查询用户userId
        if (StringUtils.isEmpty(sequenceNbrs)) {
            throw new BadRequest("入参：sequenceNbrs为空");
        }
        List<String> sequenceNbrList = new ArrayList<>();
        String[] sequenceNbrArray = sequenceNbrs.split(",");
        for (String sequenceNbr : sequenceNbrArray) {
            String userId = personnelBusinessMapper.selectUserInfo(Long.valueOf(sequenceNbr));
            //添加校验，如果业务表里面有相关的用户id不能删除
            List<String> tableName = personnelBusinessMapper.selectHygfTableName();
            if (CollectionUtil.isNotEmpty(tableName)) {
                for (String table : tableName) {
                    int count = personnelBusinessMapper.countByUserId(table, userId);
                    if (count > 0) {
                        logger.error("sequenceNbr：{}对应的用户：{},对应的表：{}有操作记录无法删除", sequenceNbr, userId, table);
                        sequenceNbrList.add(sequenceNbr);
                        return false;
                    }
                }
            }
            try {
                //删除平台表账号
                Privilege.agencyUserClient.multDeleteUser(userId);
                personnelBusinessMapper.deleteSubByUserId(userId);
                //删除hygf_personnel_business表中数据
                personnelBusinessMapper.deleteHpbByFoundationId(Long.valueOf(sequenceNbr));
                //删除std_user_empower表中数据
                personnelBusinessMapper.deleteSueByUserId(userId);
                return null;
            } catch (Exception e) {
                logger.error("sequenceNbr：{}对应删除失败", sequenceNbr);
                sequenceNbrList.add(sequenceNbr);
            }
        }
        return true;

    }

}