package com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.QRCodeUtil;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.dto.DynamicFormColumnDto;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonFormDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormColumnServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.tzs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.tzs.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.PersonEducationDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.PersonQualityDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.UnitPersonInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.PersonEducation;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.PersonQuality;
import com.yeejoin.amos.boot.module.tzs.flc.api.mapper.UnitPersonMapper;
import com.yeejoin.amos.boot.module.tzs.flc.api.service.IUnitPersonService;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
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.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业人员服务实现类
 */
@Service
public class UnitPersonServiceImpl  implements IUnitPersonService {


    private final Logger logger = LogManager.getLogger(UnitPersonServiceImpl.class);

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Autowired
    PersonQualityServiceImpl flcPersonQualityServiceImpl;


    @Autowired
    PersonEducationServiceImpl personEducationServiceImpl;


    @Autowired
    ISourceFileService iSourceFileService;


    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;

    @Autowired
    SourceFileServiceImpl sourceFileService;

    @Autowired
    DynamicFormColumnServiceImpl alertFormServiceImpl;

    @Resource
    UnitPersonMapper unitPersonMapper;

    @Transactional
    @Override
    public UnitPersonInfoDto saveUser(UnitPersonInfoDto unitPersonInfoDto) {
        unitPersonInfoDto.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        OrgPersonDto orgPersonVo = new OrgPersonDto();
        if(StringUtils.isNotBlank(unitPersonInfoDto.getOrgExpandAttr2())) {
            String pwd = DesUtil.encode(unitPersonInfoDto.getOrgExpandAttr2(), "qaz");
            unitPersonInfoDto.setOrgExpandAttr2(pwd);
        }
        // 只有parentId 需要手动填充name
        OrgUsr parent =  iOrgUsrService.getById(Long.parseLong(unitPersonInfoDto.getParentId()));
        unitPersonInfoDto.setParentName(parent.getBizOrgName());
        BeanUtils.copyProperties(unitPersonInfoDto,orgPersonVo);

        try {
            OrgUsrDto result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
            PersonQualityDto personQualityDto = unitPersonInfoDto.getPersonQualityDto();
            PersonEducationDto personEducationDto = unitPersonInfoDto.getPersonEducationDto();


            // 处理图片信息 -- 证照和图片
            Map<String, List<AttachmentDto>> userAttach = new HashMap<>();
            userAttach.put(TzsCommonParam.LICENCE_PIC,unitPersonInfoDto.getLicencePic());
            userAttach.put(TzsCommonParam.HEAD_SHOT,unitPersonInfoDto.getHeadshot());
            iSourceFileService.saveAttachments(result.getSequenceNbr(),userAttach);

            if(personQualityDto != null) {
                if(StringUtils.isNotEmpty(personQualityDto.getLicenceTypeCode())) {
                    String[] licenceTypeCode = personQualityDto.getLicenceTypeCode().split(",");
                    List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).in(DataDictionary::getCode,licenceTypeCode));
                    String licenceType = "";
                    for(DataDictionary temp : list) {
                        licenceType += "," + temp.getName();
                    }
                    if(licenceType.length() > 0) {
                        licenceType = licenceType.substring(1);
                        personQualityDto.setLicenceType(licenceType);
                    }
                }


                // 创建人员资质信息
                personQualityDto.setPsersonId(result.getSequenceNbr());
                personQualityDto = flcPersonQualityServiceImpl.createWithModel(personQualityDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.LICENCE_INFO,personQualityDto.getLicenceInfo());
                iSourceFileService.saveAttachments(personQualityDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonQualityDto(personQualityDto);
            }

            if(personEducationDto != null) {
                // 创建人员教育信息
                personEducationDto.setPsersonId(result.getSequenceNbr());
                personEducationDto = personEducationServiceImpl.createWithModel(personEducationDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.ATTACHMENT,personEducationDto.getAttachment());
                iSourceFileService.saveAttachments(personEducationDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonEducationDto(personEducationDto);

            }




            // 创建账号信息
            if(StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr1()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr2())
            && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr3()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr4())
            && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr5() )) {

                String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                String orgId = unitPersonInfoDto.getOrgExpandAttr3();// 拿到的是 org_user的id 需要转换成amosid
                OrgUsr temp =  iOrgUsrService.getById(Long.parseLong(orgId));
                Long companyId = Long.parseLong(temp.getAmosOrgId());


                String appcode = unitPersonInfoDto.getOrgExpandAttr4();

                // 创建人员账户信息
                FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                AgencyUserModel agencyUserModel = new AgencyUserModel();
                agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                agencyUserModel.setLockStatus("UNLOCK");
                agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                agencyUserModel.setAgencyCode("tzs");
                // agencyUserModel.setMobile(adminTel); 不存储电话信息
                // 所属组织
                Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                List<Long> roleIds = new ArrayList<>();
                List<RoleModel> allRoleList = roleListResult.getResult();
                List<RoleModel> userRoleList = new ArrayList<>();
                allRoleList.stream().forEach(t -> {
                    if(t.getRoleName().equals(roleName)) {
                        userRoleList.add(t);
                    }
                });
                userRoleList.stream().forEach(r -> {
                    roleIds.add(r.getSequenceNbr());
                });

                roleSeqsMap.put(companyId,roleIds);
                List<String> appCodes = new ArrayList<>();
                appCodes.add(appcode);
                agencyUserModel.setAppCodes(appCodes);
                Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                orgRoles.put(companyId,userRoleList);
                agencyUserModel.setOrgRoles(orgRoles);
                agencyUserModel.setOrgRoleSeqs(roleSeqsMap);

                FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(agencyUserModel);
                agencyUserModel = userResult.getResult();
                orgPersonVo.setSequenceNbr(result.getSequenceNbr());
                orgPersonVo.setAmosOrgId(agencyUserModel.getUserId() + "");
                result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
                BeanUtils.copyProperties(result,unitPersonInfoDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitPersonInfoDto;
    }

    @Override
    @Transactional
    public UnitPersonInfoDto getPersonById(Long sequenceNbr) {
        // 首先获取orguer信息
        UnitPersonInfoDto temp = new UnitPersonInfoDto();
        try {
            OrgPersonFormDto orgPerson = iOrgUsrService.selectPersonById(sequenceNbr);
            temp = new UnitPersonInfoDto();
            BeanUtils.copyProperties(orgPerson,temp);
            // 查询附件
            Map<String, List<AttachmentDto>> attachmentMap = sourceFileService.getAttachments(sequenceNbr);
            // 获取企业二维码
            if(attachmentMap != null) {
                // 判断是否有二维码信息 没有则添加
                if(attachmentMap.get(TzsCommonParam.QR_CODE) != null) {
                    temp.setQrcode(attachmentMap.get(TzsCommonParam.QR_CODE));
                } else {
                    this.saveQrCode(orgPerson);
                    attachmentMap = sourceFileService.getAttachments(sequenceNbr);
                    temp.setQrcode(attachmentMap.get(TzsCommonParam.QR_CODE));
                }
                if(attachmentMap.get(TzsCommonParam.LICENCE_PIC) != null) {
                    temp.setLicencePic(attachmentMap.get(TzsCommonParam.LICENCE_PIC));
                }
                if(attachmentMap.get(TzsCommonParam.HEAD_SHOT) != null) {
                    temp.setHeadshot(attachmentMap.get(TzsCommonParam.HEAD_SHOT));
                }

            }
            PersonQuality quality = flcPersonQualityServiceImpl.getOne(new LambdaQueryWrapper<PersonQuality>().eq(PersonQuality::getIsDelete,false).eq(PersonQuality::getPsersonId,sequenceNbr));
            PersonQualityDto qualityDto = new PersonQualityDto();
            attachmentMap = sourceFileService.getAttachments(quality.getSequenceNbr());
            if(attachmentMap != null) {
                if(attachmentMap.get(TzsCommonParam.LICENCE_INFO) != null) {
                    qualityDto.setLicenceInfo(attachmentMap.get(TzsCommonParam.LICENCE_INFO));
                }
            }
            BeanUtils.copyProperties(quality,qualityDto);
            temp.setPersonQualityDto(qualityDto);
            PersonEducation personEducation = personEducationServiceImpl.getOne(new LambdaQueryWrapper<PersonEducation>().eq(PersonEducation::getIsDelete,false).eq(PersonEducation::getPsersonId,sequenceNbr));
            PersonEducationDto personEducationDto = new PersonEducationDto();
            attachmentMap = sourceFileService.getAttachments(personEducation.getSequenceNbr());
            if(attachmentMap != null) {
                if(attachmentMap.get(TzsCommonParam.ATTACHMENT) != null) {
                    personEducationDto.setAttachment(attachmentMap.get(TzsCommonParam.ATTACHMENT));
                }
            }
            BeanUtils.copyProperties(personEducation,personEducationDto);
            temp.setPersonEducationDto(personEducationDto);

        } catch (Exception e) {
            e.printStackTrace();
        }
        String organizationId = temp.getOrgExpandAttr3(); // 所属组织
        if(StringUtils.isNotBlank(organizationId)) {
            FeignClientResult<CompanyModel> company = Privilege.companyClient.seleteOne(Long.parseLong(organizationId));
            if(company != null && company.getResult() != null) {
                CompanyModel tempModel =  company.getResult();
                temp.setOrganization(tempModel.getCompanyName());
            }
        }
        return temp;
    }

    @Override
    public IPage<Map<String, Object>> pagePerson(List<Long> parentId , String pageNum, String pageSize, Map<String, Object> req) {
        IPage<Map<String, Object>> pageBean = null;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("parentId", parentId);
        req.remove("pageSize");
        req.remove("pageNum");
        req.remove("parentId");
        // 处理动态字段
        List<String> sql = new ArrayList<>();
        List<DynamicFormColumnDto> dynamicList = alertFormServiceImpl.queryListByTypeCode("1106");
        dynamicList.stream().forEach(t -> {
            if(req.get(t.getFieldCode()) != null) { // 存在动态字段
                StringBuffer tempsql = new StringBuffer();
                tempsql.append("AND " + t.getFieldCode() );
                if("eq".equals(t.getQueryStrategy())) {
                    tempsql.append(" = '" + req.get(t.getFieldCode()) + "'");
                } else if("like".equals(t.getQueryStrategy())) {
                    tempsql.append(" like '%" + req.get(t.getFieldCode()) +"%'");
                }
                sql.add(tempsql.toString());
            }
        });
        if(req.get("birthdayStart") != null) {
            sql.add(" AND birthday  >=  '" + req.get("birthdayStart")+ "'");
        }
        if(req.get("birthdayEnd") != null) {
            sql.add(" AND birthday <= '" + req.get("birthdayEnd")+ "'");
        }
        if(req.get("hasLicence") != null) {
            sql.add(" AND hasLicence = '" + req.get("hasLicence")+ "'");
        }
        if(req.get("account") != null) {
            sql.add(" AND org_expand_attr1 like '%" + req.get("account")+ "%'");
        }
        if(req.get("role") != null) {
            sql.add(" AND org_expand_attr5 like '%" + req.get("role")+ "%'");
        }
        if(req.get("bizOrgCode") != null) {
            sql.add(" AND biz_org_code like '%" + req.get("bizOrgCode")+ "%'");
        }
        if(req.get("bizOrgName") != null) {
            sql.add(" AND biz_org_name like '%" + req.get("bizOrgName")+ "%'");
        }
        if(req.get("ages") != null) { // 0: 60以上 1: 50-59 2: 40-49 3: 30-39 4: 20-29 5:20 以下
            map.put("ages", req.get("ages"));
        }
        if(req.get("address") != null) { // address 模糊搜索
            sql.add(" AND fulladdress like '%" + req.get("address")+ "%'");
        }
        map.put("sql", sql);
        pageBean.setTotal(unitPersonMapper.selectPersonListCount(map));
        map.put("pageNum", (pageBean.getCurrent() - 1) * pageBean.getSize());
        map.put("pageSize", pageBean.getSize());
        List<Map<String, Object>> list = unitPersonMapper.selectPersonList(map);
        pageBean.setRecords(list);
        return pageBean;
    }

    @Transactional
    @Override
    public Boolean removeById(Long sequenceNbr) {
        // 删除 人员基本信息 逻辑删除
        OrgUsr user = iOrgUsrService.getById(sequenceNbr);
        iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", sequenceNbr).set("is_delete",
                CommonConstant.IS_DELETE_01));
        // 删除 人员相关表信息
        flcPersonQualityServiceImpl.update(new LambdaUpdateWrapper<PersonQuality>().eq(PersonQuality::getPsersonId, sequenceNbr).set(PersonQuality::getIsDelete,true));
        personEducationServiceImpl.update(new LambdaUpdateWrapper<PersonEducation>().eq(PersonEducation::getPsersonId, sequenceNbr).set(PersonEducation::getIsDelete,true));
        // 删除 人员账号信息
        Boolean flag = false;
        try {
            Privilege.agencyUserClient.multDeleteUser(user.getAmosOrgId());
            flag = true;
        } catch (InnerInvokException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Transactional
    @Override
    public Boolean batchDelete(List<Long> sequenceNbrList) {
        for(Long sequenceNbr : sequenceNbrList) {
            if(!removeById(sequenceNbr)) {
                throw new BadRequest("删除" + sequenceNbr +"用户失败");
            }
        }
        return true;
    }

    @Override
    public UnitPersonInfoDto saveSupUser(UnitPersonInfoDto unitPersonInfoDto) {
        unitPersonInfoDto.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        OrgPersonDto orgPersonVo = new OrgPersonDto();
        if(StringUtils.isNotBlank(unitPersonInfoDto.getOrgExpandAttr2())) {
            String pwd = DesUtil.encode(unitPersonInfoDto.getOrgExpandAttr2(), "qaz");
            unitPersonInfoDto.setOrgExpandAttr2(pwd);
        }
        // 只有parentId 需要手动填充name
        FeignClientResult<CompanyModel> company = Privilege.companyClient.seleteOne(Long.parseLong(unitPersonInfoDto.getParentId()));
        if(company == null || company.getResult() == null) {
            throw new BadRequest("所在单位选择有误");
        }
        unitPersonInfoDto.setParentName(company.getResult().getCompanyName());

        BeanUtils.copyProperties(unitPersonInfoDto,orgPersonVo);

        try {
            OrgUsrDto result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
            PersonQualityDto personQualityDto = unitPersonInfoDto.getPersonQualityDto();
            PersonEducationDto personEducationDto = unitPersonInfoDto.getPersonEducationDto();


            // 处理图片信息 -- 证照和图片
            Map<String, List<AttachmentDto>> userAttach = new HashMap<>();
            userAttach.put(TzsCommonParam.LICENCE_PIC,unitPersonInfoDto.getLicencePic());
            userAttach.put(TzsCommonParam.HEAD_SHOT,unitPersonInfoDto.getHeadshot());
            iSourceFileService.saveAttachments(result.getSequenceNbr(),userAttach);

            if(personQualityDto != null) {

                if(StringUtils.isNotEmpty(personQualityDto.getLicenceTypeCode())) {
                    String[] licenceTypeCode = personQualityDto.getLicenceTypeCode().split(",");
                    List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).in(DataDictionary::getCode,licenceTypeCode));
                    String licenceType = "";
                    for(DataDictionary temp : list) {
                        licenceType += "," + temp.getName();
                    }
                    if(licenceType.length() > 0) {
                        licenceType = licenceType.substring(1);
                        personQualityDto.setLicenceType(licenceType);
                    }
                }

                // 创建人员资质信息
                personQualityDto.setPsersonId(result.getSequenceNbr());
                personQualityDto = flcPersonQualityServiceImpl.createWithModel(personQualityDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.LICENCE_INFO,personQualityDto.getLicenceInfo());
                iSourceFileService.saveAttachments(personQualityDto.getSequenceNbr(),userAttach);
            }

            if(personEducationDto != null) {
                // 创建人员教育信息
                personEducationDto.setPsersonId(result.getSequenceNbr());
                personEducationDto = personEducationServiceImpl.createWithModel(personEducationDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.ATTACHMENT,personEducationDto.getAttachment());
                iSourceFileService.saveAttachments(personEducationDto.getSequenceNbr(),userAttach);

            }
            // 创建账号信息
            if(StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr1()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr2())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr3()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr4())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr5() )) {

                String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                Long companyId = Long.parseLong(unitPersonInfoDto.getOrgExpandAttr3());


                String appcode = unitPersonInfoDto.getOrgExpandAttr4();

                // 创建人员账户信息
                FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                AgencyUserModel agencyUserModel = new AgencyUserModel();
                agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                agencyUserModel.setLockStatus("UNLOCK");
                agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                agencyUserModel.setAgencyCode("tzs");
                // agencyUserModel.setMobile(adminTel); 不存储电话信息
                // 所属组织
                Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                List<Long> roleIds = new ArrayList<>();
                List<RoleModel> allRoleList = roleListResult.getResult();
                List<RoleModel> userRoleList = new ArrayList<>();
                allRoleList.stream().forEach(t -> {
                    if(t.getRoleName().equals(roleName)) {
                        userRoleList.add(t);
                    }
                });
                userRoleList.stream().forEach(r -> {
                    roleIds.add(r.getSequenceNbr());
                });

                roleSeqsMap.put(companyId,roleIds);
                List<String> appCodes = new ArrayList<>();
                appCodes.add(appcode);
                agencyUserModel.setAppCodes(appCodes);
                Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                orgRoles.put(companyId,userRoleList);
                agencyUserModel.setOrgRoles(orgRoles);
                agencyUserModel.setOrgRoleSeqs(roleSeqsMap);

                FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(agencyUserModel);
                agencyUserModel = userResult.getResult();
                orgPersonVo.setSequenceNbr(result.getSequenceNbr());
                orgPersonVo.setAmosOrgId(agencyUserModel.getUserId() + "");
                result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
                BeanUtils.copyProperties(result,unitPersonInfoDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitPersonInfoDto;
    }

    @Transactional
    @Override
    public UnitPersonInfoDto updateSupUser(UnitPersonInfoDto unitPersonInfoDto) {
        unitPersonInfoDto.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        OrgPersonDto orgPersonVo = new OrgPersonDto();
        if(StringUtils.isNotBlank(unitPersonInfoDto.getOrgExpandAttr2())) {
            String pwd = DesUtil.encode(unitPersonInfoDto.getOrgExpandAttr2(), "qaz");
            unitPersonInfoDto.setOrgExpandAttr2(pwd);
        }
        // 只有parentId 需要手动填充name
        FeignClientResult<CompanyModel> company = Privilege.companyClient.seleteOne(Long.parseLong(unitPersonInfoDto.getParentId()));
        if(company == null || company.getResult() == null) {
            throw new BadRequest("所在单位选择有误");
        }
        OrgUsr oldInfo =  iOrgUsrService.getById(unitPersonInfoDto.getSequenceNbr());
        String originalPassword = oldInfo.getOrgExpandAttr2();
        String amosId = oldInfo.getAmosOrgId();
        unitPersonInfoDto.setParentName(company.getResult().getCompanyName());
        BeanUtils.copyProperties(unitPersonInfoDto,orgPersonVo);

        try {
            iOrgUsrService.updateByIdOrgPersonFlc(orgPersonVo,unitPersonInfoDto.getSequenceNbr());
            PersonQualityDto personQualityDto = unitPersonInfoDto.getPersonQualityDto();
            PersonEducationDto personEducationDto = unitPersonInfoDto.getPersonEducationDto();


            // 处理图片信息 -- 证照和图片
            Map<String, List<AttachmentDto>> userAttach = new HashMap<>();
            userAttach.put(TzsCommonParam.LICENCE_PIC,unitPersonInfoDto.getLicencePic());
            userAttach.put(TzsCommonParam.HEAD_SHOT,unitPersonInfoDto.getHeadshot());
            iSourceFileService.saveAttachments(unitPersonInfoDto.getSequenceNbr(),userAttach);

            if(personQualityDto != null) {

                if(StringUtils.isNotEmpty(personQualityDto.getLicenceTypeCode())) {
                    String[] licenceTypeCode = personQualityDto.getLicenceTypeCode().split(",");
                    List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).in(DataDictionary::getCode,licenceTypeCode));
                    String licenceType = "";
                    for(DataDictionary temp : list) {
                        licenceType += "," + temp.getName();
                    }
                    if(licenceType.length() > 0) {
                        licenceType = licenceType.substring(1);
                        personQualityDto.setLicenceType(licenceType);
                    }
                }


                // 更新人员资质信息
                personQualityDto.setPsersonId(unitPersonInfoDto.getSequenceNbr());
                if(personQualityDto.getSequenceNbr() != null) {
                    // 已经存在更新 否则新增
                    personQualityDto = flcPersonQualityServiceImpl.updateWithModel(personQualityDto);
                } else {
                    personQualityDto = flcPersonQualityServiceImpl.createWithModel(personQualityDto);
                }
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.LICENCE_INFO,personQualityDto.getLicenceInfo());
                iSourceFileService.saveAttachments(personQualityDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonQualityDto(personQualityDto);
            }

            if(personEducationDto != null) {
                // 更新人员教育信息
                personEducationDto.setPsersonId(unitPersonInfoDto.getSequenceNbr());
                if(personEducationDto.getSequenceNbr() != null) {
                    // 已经存在更新 否则新增
                    personEducationDto = personEducationServiceImpl.updateWithModel(personEducationDto);
                } else {
                    personEducationDto = personEducationServiceImpl.createWithModel(personEducationDto);
                }
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.ATTACHMENT,personEducationDto.getAttachment());
                iSourceFileService.saveAttachments(personEducationDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonEducationDto(personEducationDto);

            }




            // 更新账号信息
            if(StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr1()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr2())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr3()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr4())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr5() )) {

                // 首先判断是否存在 用户信息， 如果不存在走新增方法
                if(StringUtils.isNotEmpty(amosId)) {
                    String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                    Long companyId = Long.parseLong(unitPersonInfoDto.getOrgExpandAttr3());
                    String appcode = unitPersonInfoDto.getOrgExpandAttr4();
                    // 创建人员账户信息
                    FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);


                    AgencyUserModel agencyUserModel = Privilege.agencyUserClient.queryByUserId(orgPersonVo.getAmosOrgId()).getResult();
                    agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                    agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                    agencyUserModel.setLockStatus("UNLOCK");
                    agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setOriginalPassword(originalPassword);
                    agencyUserModel.setAgencyCode("tzs");
                    // agencyUserModel.setMobile(adminTel); 不存储电话信息
                    // 所属组织
                    Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                    List<Long> roleIds = new ArrayList<>();
                    List<RoleModel> allRoleList = roleListResult.getResult();
                    List<RoleModel> userRoleList = new ArrayList<>();
                    allRoleList.stream().forEach(t -> {
                        if(t.getRoleName().equals(roleName)) {
                            userRoleList.add(t);
                        }
                    });
                    userRoleList.stream().forEach(r -> {
                        roleIds.add(r.getSequenceNbr());
                    });

                    roleSeqsMap.put(companyId,roleIds);
                    List<String> appCodes = new ArrayList<>();
                    appCodes.add(appcode);
                    agencyUserModel.setAppCodes(appCodes);
                    Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                    orgRoles.put(companyId,userRoleList);
                    agencyUserModel.setOrgRoles(orgRoles);
                    agencyUserModel.setOrgRoleSeqs(roleSeqsMap);
                    Privilege.agencyUserClient.update(agencyUserModel,orgPersonVo.getAmosOrgId());
                    // 密码另外更新
                    Privilege.agencyUserClient.modifyPassword(orgPersonVo.getAmosOrgId(),agencyUserModel);
                } else {

                    String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                    Long companyId = Long.parseLong(unitPersonInfoDto.getOrgExpandAttr3());


                    String appcode = unitPersonInfoDto.getOrgExpandAttr4();

                    // 创建人员账户信息
                    FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                    AgencyUserModel agencyUserModel = new AgencyUserModel();
                    agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                    agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                    agencyUserModel.setLockStatus("UNLOCK");
                    agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setAgencyCode("tzs");
                    // agencyUserModel.setMobile(adminTel); 不存储电话信息
                    // 所属组织
                    Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                    List<Long> roleIds = new ArrayList<>();
                    List<RoleModel> allRoleList = roleListResult.getResult();
                    List<RoleModel> userRoleList = new ArrayList<>();
                    allRoleList.stream().forEach(t -> {
                        if(t.getRoleName().equals(roleName)) {
                            userRoleList.add(t);
                        }
                    });
                    userRoleList.stream().forEach(r -> {
                        roleIds.add(r.getSequenceNbr());
                    });

                    roleSeqsMap.put(companyId,roleIds);
                    List<String> appCodes = new ArrayList<>();
                    appCodes.add(appcode);
                    agencyUserModel.setAppCodes(appCodes);
                    Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                    orgRoles.put(companyId,userRoleList);
                    agencyUserModel.setOrgRoles(orgRoles);
                    agencyUserModel.setOrgRoleSeqs(roleSeqsMap);

                    FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(agencyUserModel);
                    agencyUserModel = userResult.getResult();
                    unitPersonInfoDto.setAmosOrgId(agencyUserModel.getUserId() + "");
                    orgPersonVo.setAmosOrgId(agencyUserModel.getUserId() + "");
                    iOrgUsrService.updateByIdOrgPersonFlc(orgPersonVo,unitPersonInfoDto.getSequenceNbr());




                }




            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitPersonInfoDto;
    }



    @Transactional
    @Override
    public UnitPersonInfoDto updateUser(UnitPersonInfoDto unitPersonInfoDto) {
        unitPersonInfoDto.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        OrgPersonDto orgPersonVo = new OrgPersonDto();
        if(StringUtils.isNotBlank(unitPersonInfoDto.getOrgExpandAttr2())) {
            String pwd = DesUtil.encode(unitPersonInfoDto.getOrgExpandAttr2(), "qaz");
            unitPersonInfoDto.setOrgExpandAttr2(pwd);
        }
        // 只有parentId 需要手动填充name
        OrgUsr parent =  iOrgUsrService.getById(Long.parseLong(unitPersonInfoDto.getParentId()));
        OrgUsr oldInfo =  iOrgUsrService.getById(unitPersonInfoDto.getSequenceNbr());
        String originalPassword = oldInfo.getOrgExpandAttr2();
        String amosId = oldInfo.getAmosOrgId();
        unitPersonInfoDto.setParentName(parent.getBizOrgName());
        BeanUtils.copyProperties(unitPersonInfoDto,orgPersonVo);

        try {
            iOrgUsrService.updateByIdOrgPersonFlc(orgPersonVo,unitPersonInfoDto.getSequenceNbr());
            PersonQualityDto personQualityDto = unitPersonInfoDto.getPersonQualityDto();
            PersonEducationDto personEducationDto = unitPersonInfoDto.getPersonEducationDto();


            // 处理图片信息 -- 证照和图片
            Map<String, List<AttachmentDto>> userAttach = new HashMap<>();
            userAttach.put(TzsCommonParam.LICENCE_PIC,unitPersonInfoDto.getLicencePic());
            userAttach.put(TzsCommonParam.HEAD_SHOT,unitPersonInfoDto.getHeadshot());
            iSourceFileService.saveAttachments(unitPersonInfoDto.getSequenceNbr(),userAttach);

            if(personQualityDto != null) {
                if(StringUtils.isNotEmpty(personQualityDto.getLicenceTypeCode())) {
                    String[] licenceTypeCode = personQualityDto.getLicenceTypeCode().split(",");
                    List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).in(DataDictionary::getCode,licenceTypeCode));
                    String licenceType = "";
                    for(DataDictionary temp : list) {
                        licenceType += "," + temp.getName();
                    }
                    if(licenceType.length() > 0) {
                        licenceType = licenceType.substring(1);
                        personQualityDto.setLicenceType(licenceType);
                    }
                }

                // 更新人员资质信息
                personQualityDto.setPsersonId(unitPersonInfoDto.getSequenceNbr());
                if(personQualityDto.getSequenceNbr() != null) {
                    // 已经存在更新 否则新增
                    personQualityDto = flcPersonQualityServiceImpl.updateWithModel(personQualityDto);
                } else {
                    personQualityDto = flcPersonQualityServiceImpl.createWithModel(personQualityDto);
                }
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.LICENCE_INFO,personQualityDto.getLicenceInfo());
                iSourceFileService.saveAttachments(personQualityDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonQualityDto(personQualityDto);
            }

            if(personEducationDto != null) {
                // 更新人员教育信息
                personEducationDto.setPsersonId(unitPersonInfoDto.getSequenceNbr());

                if(personEducationDto.getSequenceNbr() != null) {
                    // 已经存在更新 否则新增
                    personEducationDto = personEducationServiceImpl.updateWithModel(personEducationDto);
                } else {
                    personEducationDto = personEducationServiceImpl.createWithModel(personEducationDto);
                }

                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.ATTACHMENT,personEducationDto.getAttachment());
                iSourceFileService.saveAttachments(personEducationDto.getSequenceNbr(),userAttach);
                unitPersonInfoDto.setPersonEducationDto(personEducationDto);

            }




            // 更新账号信息
            if(StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr1()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr2())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr3()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr4())
                    && StringUtils.isNotEmpty(unitPersonInfoDto.getOrgExpandAttr5() )) {

                // 首先判断是否存在 用户信息， 如果不存在走新增方法
                if(StringUtils.isNotEmpty(amosId)) {
                    String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                    String orgId = unitPersonInfoDto.getOrgExpandAttr3();// 拿到的是 org_user的id 需要转换成amosid
                    OrgUsr temp =  iOrgUsrService.getById(Long.parseLong(orgId));
                    Long companyId = Long.parseLong(temp.getAmosOrgId());
                    String appcode = unitPersonInfoDto.getOrgExpandAttr4();
                    // 创建人员账户信息
                    FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                    AgencyUserModel agencyUserModel = Privilege.agencyUserClient.queryByUserId(orgPersonVo.getAmosOrgId()).getResult();
                    agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                    agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                    agencyUserModel.setLockStatus("UNLOCK");
                    agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setOriginalPassword(originalPassword);
                    agencyUserModel.setAgencyCode("tzs");
                    // agencyUserModel.setMobile(adminTel); 不存储电话信息
                    // 所属组织
                    Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                    List<Long> roleIds = new ArrayList<>();
                    List<RoleModel> allRoleList = roleListResult.getResult();
                    List<RoleModel> userRoleList = new ArrayList<>();
                    allRoleList.stream().forEach(t -> {
                        if(t.getRoleName().equals(roleName)) {
                            userRoleList.add(t);
                        }
                    });
                    userRoleList.stream().forEach(r -> {
                        roleIds.add(r.getSequenceNbr());
                    });

                    roleSeqsMap.put(companyId,roleIds);
                    List<String> appCodes = new ArrayList<>();
                    appCodes.add(appcode);
                    agencyUserModel.setAppCodes(appCodes);
                    Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                    orgRoles.put(companyId,userRoleList);
                    agencyUserModel.setOrgRoles(orgRoles);
                    agencyUserModel.setOrgRoleSeqs(roleSeqsMap);
                    Privilege.agencyUserClient.update(agencyUserModel,orgPersonVo.getAmosOrgId());
                    // 密码另外更新
                    Privilege.agencyUserClient.modifyPassword(orgPersonVo.getAmosOrgId(),agencyUserModel);
                } else {
                    String roleName = unitPersonInfoDto.getOrgExpandAttr5();
                    String orgId = unitPersonInfoDto.getOrgExpandAttr3();// 拿到的是 org_user的id 需要转换成amosid
                    OrgUsr temp =  iOrgUsrService.getById(Long.parseLong(orgId));
                    Long companyId = Long.parseLong(temp.getAmosOrgId());


                    String appcode = unitPersonInfoDto.getOrgExpandAttr4();

                    // 创建人员账户信息
                    FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                    AgencyUserModel agencyUserModel = new AgencyUserModel();
                    agencyUserModel.setUserName(unitPersonInfoDto.getOrgExpandAttr1());
                    agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                    agencyUserModel.setLockStatus("UNLOCK");
                    agencyUserModel.setPassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setRePassword(unitPersonInfoDto.getOrgExpandAttr2());
                    agencyUserModel.setAgencyCode("tzs");
                    // agencyUserModel.setMobile(adminTel); 不存储电话信息
                    // 所属组织
                    Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                    List<Long> roleIds = new ArrayList<>();
                    List<RoleModel> allRoleList = roleListResult.getResult();
                    List<RoleModel> userRoleList = new ArrayList<>();
                    allRoleList.stream().forEach(t -> {
                        if(t.getRoleName().equals(roleName)) {
                            userRoleList.add(t);
                        }
                    });
                    userRoleList.stream().forEach(r -> {
                        roleIds.add(r.getSequenceNbr());
                    });

                    roleSeqsMap.put(companyId,roleIds);
                    List<String> appCodes = new ArrayList<>();
                    appCodes.add(appcode);
                    agencyUserModel.setAppCodes(appCodes);
                    Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                    orgRoles.put(companyId,userRoleList);
                    agencyUserModel.setOrgRoles(orgRoles);
                    agencyUserModel.setOrgRoleSeqs(roleSeqsMap);

                    FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(agencyUserModel);
                    agencyUserModel = userResult.getResult();
                    unitPersonInfoDto.setAmosOrgId(agencyUserModel.getUserId() + "");
                    orgPersonVo.setAmosOrgId(agencyUserModel.getUserId() + "");
                    iOrgUsrService.updateByIdOrgPersonFlc(orgPersonVo,unitPersonInfoDto.getSequenceNbr());
                }



            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitPersonInfoDto;
    }


    public String saveQrCode(OrgPersonFormDto orgPerson) {
        // 二维码生成规则  人员类型  企业编码 人员编号
        List<FormValue> dynamicFormAlert = orgPerson.getDynamicFormAlert();
        String personType = "";
        for(FormValue t : dynamicFormAlert) {
            if("person_type".equals(t.getKey())) {
                personType = t.getValueName();
                break;
            }
        }
        String qrString = "人员类型: " +personType +"\n\r";
        OrgUsr company = iOrgUsrService.getById(orgPerson.getParentId());
        // 如果company 为空 说明是 监管端 需要获取组织机构树
        if(company == null) {
            FeignClientResult<CompanyModel> amosCompany = Privilege.companyClient.seleteOne(Long.parseLong(orgPerson.getParentId()));
            if(amosCompany == null || amosCompany.getResult() == null) {
                throw new BadRequest("所在单位有误");
            }
            qrString += "企业编码: " +amosCompany.getResult().getOrgCode()+"\n\r";
            qrString += "人员编号: " +orgPerson.getBizOrgCode() +"\n\r";
        } else {
            qrString += "企业编码: " +company.getBizOrgCode() +"\n\r";
            qrString += "人员编号: " +orgPerson.getBizOrgCode() +"\n\r";
        }


        byte[] bytes = QRCodeUtil.generateQRCodeImageByteData(qrString, 480);
        MultipartFile file = new MockMultipartFile("person_" + orgPerson.getSequenceNbr() + ".png","person_" + orgPerson.getSequenceNbr() + ".png","application/octet-stream" ,bytes);
        FeignClientResult<Map<String, String>> result =  Systemctl.fileStorageClient.updateCommonFile(file);
        Map<String, String> map = result.getResult();
        if(map.isEmpty()) {
            logger.error("未生成二维码文件");
            throw new BadRequest("未生成二维码文件");
        }
        String filePath = "";
        for(Map.Entry<String,String> fileResult : map.entrySet()) {
            filePath = fileResult.getKey();
        }
        // 保存qrCode
        List<AttachmentDto> qrCode = new ArrayList<>();
        AttachmentDto temp = new AttachmentDto();
        temp.setName("person_" + orgPerson.getSequenceNbr() + ".png");
        temp.setType("image");
        temp.setUrl(filePath);
        qrCode.add(temp);
        Map<String, List<AttachmentDto>> attachmentMap = sourceFileService.getAttachments(orgPerson.getSequenceNbr());
        attachmentMap.put(TzsCommonParam.QR_CODE,qrCode);
        sourceFileService.saveAttachments(orgPerson.getSequenceNbr(),attachmentMap);
        return filePath;
    }
}