package com.cusc.nirvana.user.rnr.fp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.common.RnrResultEnum;
import com.cusc.nirvana.user.rnr.fp.common.cloud.CloudMethod;
import com.cusc.nirvana.user.rnr.fp.common.cloud.CloudService;
import com.cusc.nirvana.user.rnr.fp.common.util.DateUtil;
import com.cusc.nirvana.user.rnr.fp.constants.RedisConstant;
import com.cusc.nirvana.user.rnr.fp.constants.ResultCodeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.AttachmentDTO;
import com.cusc.nirvana.user.rnr.fp.dto.AttachmentRespDTO;
import com.cusc.nirvana.user.rnr.fp.dto.EnterpriseChangeRnrPersonDTO;
import com.cusc.nirvana.user.rnr.fp.dto.EnterpriseH5CallBackRequestDTO;
import com.cusc.nirvana.user.rnr.fp.dto.EnterpriseRnrPersonNameReqDTO;
import com.cusc.nirvana.user.rnr.fp.dto.EnterpriseRnrPersonNameResponseDTO;
import com.cusc.nirvana.user.rnr.fp.dto.RnrRequestDTO;
import com.cusc.nirvana.user.rnr.fp.dto.RnrResponseDTO;
import com.cusc.nirvana.user.rnr.fp.service.IEnterpriseRnrService;
import com.cusc.nirvana.user.rnr.fp.service.IFileService;
import com.cusc.nirvana.user.rnr.fp.service.IRnrService;
import com.cusc.nirvana.user.rnr.fp.service.ShortMessageCheckService;
import com.cusc.nirvana.user.rnr.mg.client.ChangeOrUnbindIccidsClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCompanyInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrFileClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrRelationClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrUnboundClient;
import com.cusc.nirvana.user.rnr.mg.client.MgVehicleCompanyClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.constants.CertFileRnrFileTypeRelation;
import com.cusc.nirvana.user.rnr.mg.constants.CertTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.CommonYesOrNoEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrBizzTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrFileType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderAuditTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderSourceEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCompanyInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrFileDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgVehicleCompanyDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrUnbindDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EnterpriseRnrServiceImpl implements IEnterpriseRnrService {

    @Resource
    private MgRnrRelationClient mgRnrRelationClient;

    @Resource
    private MgRnrCardInfoClient mgRnrCardInfoClient;

    @Autowired
    private MgRnrUnboundClient unboundClient;

    @Autowired
    private IRnrService rnrService;

    @Resource
    private MgRnrInfoClient rnrInfoClient;

    @Resource
    private MgRnrCompanyInfoClient companyInfoClient;

    @Resource
    private ShortMessageCheckService shortMessageCheckService;

    @Resource
    private MgVehicleCompanyClient vehicleCompanyClient;

    @Resource
	private RnrOrderClient orderClient;

    @Resource
	private IFileService fileService;

    @Resource
	private MgRnrFileClient fileClient;



	@Autowired
    private CloudService cloudService;

	@Resource
	private ChangeOrUnbindIccidsClient changeOrUnbindIccidsClient;


    @Resource
    private CacheFactory cacheFactory;

    /**
     * 企业实名
     *
     * @param dto
     * @return
     */
    @Override
    public Response enterpriseRnr(RnrRelationDTO dto, String requestId) {
        //卡实名状态校验
        rnrService.iccidListCheck(dto);
        //校验人卡实名状态  iccid和实名状态去查
        List<MgRnrCardInfoDTO> iccidList = dto.getCardList();
        if (CollectionUtils.isEmpty(iccidList)) {
            return Response.createError("iccid不能为空");
        }
        for (MgRnrCardInfoDTO iccid : iccidList) {
            MgRnrCardInfoDTO mgRnrCardInfoDTO = new MgRnrCardInfoDTO();
            mgRnrCardInfoDTO.setIccid(iccid.getIccid());
            Response<Boolean> cardInfoClientResponse = mgRnrCardInfoClient.checkStatus(mgRnrCardInfoDTO);
            if (!cardInfoClientResponse.isSuccess() || cardInfoClientResponse.getData() == null) {
                return Response.createError(cardInfoClientResponse.getMsg(), cardInfoClientResponse.getCode());
            }
            log.info("卡实名状态:{}", JSON.toJSONString(cardInfoClientResponse));
            if (cardInfoClientResponse.getData()) {
                return Response.createError("卡【" + iccid.getIccid() + "】已实名");
            }
        }
        //企业实名
        RnrRequestDTO rnrRequestDTO = rnrService.rnrPersonRelationDto2RnrRequestDTO(dto);
        rnrRequestDTO.setSerialNumber(dto.getOrder().getUuid());
        rnrRequestDTO.setRequestId(requestId);
//        log.info("RnrRequestDTO1111111: {}", JSON.toJSONString(rnrRequestDTO));

        RnrResponseDTO rnrResponseDTO = rnrService.doPersonRnr(rnrRequestDTO, null);
        log.info("企业实名", rnrResponseDTO);
        //添加活体图片1
        MgRnrFileDTO livenessPic1 = new MgRnrFileDTO();
        livenessPic1.setUuid(CuscStringUtils.generateUuid());
        livenessPic1.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
        livenessPic1.setRnrId(dto.getInfo().getUuid());
        livenessPic1.setIsCompany(CommonYesOrNoEnum.YES.getCode());
        livenessPic1.setRnrCompanyId(dto.getCompanyInfo().getUuid());
        livenessPic1.setFileSystemId(rnrResponseDTO.getLivenessPic1());
        livenessPic1.setFileType(RnrFileType.LIVENESS_SCREEN_FIRST.getCode());
        livenessPic1.setTenantNo(dto.getTenantNo());
        livenessPic1.setRoutingKey(dto.getInfo().getRoutingKey());
        livenessPic1.setCreator(dto.getInfo().getCreator());
        livenessPic1.setFileName("活体视频1.png");
        livenessPic1.setLiaisonId("0");
        dto.getRnrFileList().add(livenessPic1);
        //添加活体图片1
        MgRnrFileDTO livenessPic2 = new MgRnrFileDTO();
        livenessPic2.setUuid(CuscStringUtils.generateUuid());
        livenessPic2.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
        livenessPic2.setRnrId(dto.getInfo().getUuid());
        livenessPic2.setIsCompany(CommonYesOrNoEnum.YES.getCode());
        livenessPic2.setRnrCompanyId(dto.getCompanyInfo().getUuid());
        livenessPic2.setFileSystemId(rnrResponseDTO.getLivenessPic2());
        livenessPic2.setFileType(RnrFileType.LIVENESS_SCREEN_TWO.getCode());
        livenessPic2.setCreator(dto.getInfo().getCreator());
        livenessPic2.setFileName("活体视频2.png");
        livenessPic2.setTenantNo(dto.getTenantNo());
        livenessPic2.setRoutingKey(dto.getInfo().getRoutingKey());
        livenessPic2.setLiaisonId("0");
        dto.getRnrFileList().add(livenessPic2);



        //创建手工工单 调用工单接口 client
        log.info("数据信息", dto);
        Response response = mgRnrRelationClient.saveRnrRelation(dto);
        if (!response.isSuccess()) {
            return response;
        }
        return Response.createSuccess(1);
    }

    @Override
    public Response enterpriseRnrFollowUp(RnrRelationDTO dto) {
        log.info("enterpriseRnrFollowUp param : {}", JSON.toJSONString(dto));
        //校验人卡实名状态  iccid和实名状态去查
        List<MgRnrCardInfoDTO> iccidList = dto.getCardList();
        if (CollectionUtils.isEmpty(iccidList)) {
            return Response.createError("iccid不能为空");
        }
        for (MgRnrCardInfoDTO iccid : iccidList) {
            MgRnrCardInfoDTO mgRnrCardInfoDTO = new MgRnrCardInfoDTO();
            mgRnrCardInfoDTO.setIccid(iccid.getIccid());
            Response<Boolean> cardInfoClientResponse = mgRnrCardInfoClient.checkStatus(mgRnrCardInfoDTO);
            if (!cardInfoClientResponse.isSuccess() || cardInfoClientResponse.getData() == null) {
                return Response.createError(cardInfoClientResponse.getMsg(), cardInfoClientResponse.getCode());
            }
            log.info("卡实名状态:{}", JSON.toJSONString(cardInfoClientResponse));
            if (cardInfoClientResponse.getData()) {
                return Response.createError("卡【" + iccid.getIccid() + "】已实名");
            }
        }
        //创建手工工单 调用工单接口 client
        Response response = mgRnrRelationClient.saveRnrRelation(dto);
        if (!response.isSuccess()) {
            return response;
        }
        return Response.createSuccess(1);
    }

    @Override
    public Response uploadSecondaryEnterprise(RnrRelationDTO dto) {
        //解绑卡
        Response response = unboundCards(dto);
        if (!response.isSuccess()) {
            return Response.createSuccess(false);
        }
        //调用新车绑定方法
        //return uploadEnterpriseInfo(dto);
        return null;

    }

    @Override
    public List<EnterpriseRnrPersonNameResponseDTO> queryEnterpriseRnrPersonName(EnterpriseRnrPersonNameReqDTO dto) {
        MgRnrCompanyInfoDTO companyQueryDto = new MgRnrCompanyInfoDTO();
        companyQueryDto.setTenantNo(dto.getTenantNo());
        companyQueryDto.setCompanyName(dto.getCompanyName());
        if (!dto.getVehicleCompany()) {
            companyQueryDto.setIsVehicleCompany(0);
        }
        Response<List<MgRnrCompanyInfoDTO>> companyResponse = companyInfoClient.queryByList(companyQueryDto);
        if (!companyResponse.getSuccess()) {
            throw new CuscUserException(companyResponse.getCode(), companyResponse.getException());
        }
        List<MgRnrCompanyInfoDTO> companyInfoDTOList = companyResponse.getData();
        if (CollectionUtils.isEmpty(companyInfoDTOList)) {
            //throw new CuscUserException("","该公司未查询到实名信息");
            return Collections.emptyList();
        }


        Map<String, String> companyMap = companyInfoDTOList.stream().collect(Collectors.toMap(MgRnrCompanyInfoDTO::getRnrId, MgRnrCompanyInfoDTO::getCompanyName, (k, v) -> v));

        List<String> rnrIdList = companyInfoDTOList.stream().map(MgRnrCompanyInfoDTO::getRnrId).collect(Collectors.toList());


        MgRnrInfoDTO rnrQuery = new MgRnrInfoDTO();
        rnrQuery.setUuidList(rnrIdList);
        rnrQuery.setRnrStatus(RnrStatus.RNR.getCode());
        Response<List<MgRnrInfoDTO>> rnrInfoResponse = rnrInfoClient.queryByList(rnrQuery);
        if (!rnrInfoResponse.getSuccess()) {
            throw new CuscUserException(rnrInfoResponse.getCode(), rnrInfoResponse.getException());
        }

        List<MgRnrInfoDTO> rnrInfoDTOList = rnrInfoResponse.getData();

        //按照人分组
        Map<String, List<MgRnrInfoDTO>> personMap = rnrInfoDTOList.stream().collect(Collectors.groupingBy(MgRnrInfoDTO::getFullName));

        List<EnterpriseRnrPersonNameResponseDTO> reponseList = new ArrayList<>();

        for (Map.Entry<String, List<MgRnrInfoDTO>> entry : personMap.entrySet()) {
            List<MgRnrInfoDTO> rnrInfoList = entry.getValue();
            for (MgRnrInfoDTO mgRnrInfoDTO : rnrInfoList) {
                MgRnrCardInfoDTO cardQuery = new MgRnrCardInfoDTO();
                cardQuery.setRnrId(mgRnrInfoDTO.getUuid());
                cardQuery.setRnrStatus(RnrStatus.RNR.getCode());
                Response<List<MgRnrCardInfoDTO>> response = mgRnrCardInfoClient.queryByList(cardQuery);
                if (response != null && !CollectionUtils.isEmpty(response.getData())) {
                    //这个责任人下 有实名通过的卡' 处理下一个人
                    EnterpriseRnrPersonNameResponseDTO responseDTO = new EnterpriseRnrPersonNameResponseDTO();
                    responseDTO.setFullName(mgRnrInfoDTO.getFullName());
                    responseDTO.setCompanyName(companyMap.get(mgRnrInfoDTO.getUuid()));
                    reponseList.add(responseDTO);
                    break;
                }
            }
        }
        return reponseList;

    }


    /**
     * 解绑卡
     *
     * @param dto
     */
    private Response unboundCards(RnrRelationDTO dto) {
        List<String> iccidList = dto.getCardList().stream().map(MgRnrCardInfoDTO::getIccid).collect(Collectors.toList());
        MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
        query.setIccidList(iccidList);
        Response<List<MgRnrCardInfoDTO>> response = mgRnrCardInfoClient.queryByList(query);
        if (null == response || !response.getSuccess()) {
            return Response.createError("查询卡信息失败");
        }

        //获取汽车过户证明
        /*MgRnrFileDTO mgRnrFileDTO = dto.getRnrFileList().stream()
                .filter(f -> f.getFileType() == RnrFileType.CAR_TRANSFER_CERTIFICATE.getCode())
                .findFirst().get();
        if(mgRnrFileDTO == null) {
            return Response.createError("汽车过户证明缺失");
        }*/

        if (!CollectionUtils.isEmpty(response.getData())) {
            List<MgRnrCardInfoDTO> bindCards = new ArrayList<>();
            for (MgRnrCardInfoDTO cardDto : response.getData()) {
                //还在审核中的卡不能实名
                if (cardDto.getRnrStatus() == RnrStatus.INIT.getCode()) {
                    return Response.createError("卡[" + cardDto.getIccid() + "]正在实名中");
                }
                //实名成功的卡需要解绑
                if (cardDto.getRnrStatus() == RnrStatus.RNR.getCode()) {
                    bindCards.add(cardDto);
                }
            }

            //依次解绑
            if (!bindCards.isEmpty()) {
                RnrUnbindDTO unbindDTO;
                for (MgRnrCardInfoDTO bindCard : bindCards) {
                    //获取实名主体信息
                    MgRnrInfoDTO mgRnrInfoDTO = new MgRnrInfoDTO();
                    mgRnrInfoDTO.setUuid(bindCard.getRnrId());
                    Response<MgRnrInfoDTO> byUuid = rnrInfoClient.getByUuid(mgRnrInfoDTO);
                    if (byUuid == null || !byUuid.isSuccess()) {
                        return byUuid;
                    }
                    MgRnrInfoDTO rnrInfoDTO = byUuid.getData();

                    unbindDTO = new RnrUnbindDTO();
                    unbindDTO.setIccid(bindCard.getIccid());
                    unbindDTO.setVin(bindCard.getIotId());
                    unbindDTO.setCertNumber(rnrInfoDTO.getCertNumber());
                    unbindDTO.setCertType(rnrInfoDTO.getCertType());
                    unbindDTO.setFullName(rnrInfoDTO.getFullName());
                    unbindDTO.setPhone(rnrInfoDTO.getPhone());
                    unbindDTO.setReason(3);
                    unbindDTO.setManualUnbind(false);
                    //unbindDTO.setEvidence(mgRnrFileDTO.getFileSystemId());
                    response = unboundClient.rnrUnbound(unbindDTO);
                    if (null == response
                            || (!response.getSuccess() && response.getCode() != ResponseCode.ICCID_RNR_INFO_NOT_MATCHED.getCode())) {
                        return Response.createError("解绑卡[" + bindCard.getIccid() + "]失败");
                    }
                }
            }
        }
        return Response.createSuccess();
    }

	/**
	 * 提交企业责任人变更
	 * @param serialNumber
	 * @param requestId
	 * @param dto
	 */
	@Override
	public void changeEnterpriseRnrPerson(String serialNumber, String requestId, EnterpriseChangeRnrPersonDTO dto) {
		log.info("企业责任人变更,request = {}",JSONObject.toJSONString(dto));
    	//短信校验
		/*SmsRequestDTO smsDto = new SmsRequestDTO();
		smsDto.setTenantNo(dto.getTenantNo());
		smsDto.setBizType(BizTypeEnum.ENTERPRISE_CHANGE.getCode());
		smsDto.setCaptcha(dto.getCaptcha());
		smsDto.setPhone(dto.getCorporationPhone());
		Response response = shortMessageCheckService.checkSmsCaptcha(smsDto);
		if (!response.isSuccess()) {
			throw new CuscUserException(response.getCode(),response.getMsg());
		}*/
        changeEnterpriseRnrPersonNoSms(serialNumber, requestId, dto);
    }

    @Override
    public void changeEnterpriseRnrPersonNoSms(String serialNumber, String requestId, EnterpriseChangeRnrPersonDTO dto) {
        log.info("企业责任人变更,request = {}", JSONObject.toJSONString(dto));

        //查询出原来责任人对应的实名业务
        MgRnrInfoDTO rnrInfoQuery = new MgRnrInfoDTO();
        rnrInfoQuery.setTenantNo(dto.getTenantNo());
        rnrInfoQuery.setFullName(dto.getOrigCorporationName());
        rnrInfoQuery.setRnrStatus(RnrStatus.RNR.getCode());
        rnrInfoQuery.setCompanyName(dto.getCompanyName());
        List<MgRnrInfoDTO> orginRnrInfoList = rnrInfoClient.queryByList(rnrInfoQuery).getData();
        if (CollectionUtils.isEmpty(orginRnrInfoList)) {
            throw new CuscUserException("", "未查询到" + dto.getOrigCorporationName() + "有实名通过的业务");
        }
        log.info("企业责任人变更,原实名业务 = {}", orginRnrInfoList.stream().map(MgRnrInfoDTO::getUuid).collect(Collectors.toList()));

        //查询到实名业务 对应的 卡信息
        List<String> rnrIdList = orginRnrInfoList.stream().map(MgRnrInfoDTO::getUuid).collect(Collectors.toList());
        MgRnrCardInfoDTO cardQuery = new MgRnrCardInfoDTO();
        cardQuery.setRnrIdList(rnrIdList);
        cardQuery.setRnrStatus(RnrStatus.RNR.getCode());
        List<MgRnrCardInfoDTO> rnrCardList = mgRnrCardInfoClient.queryByList(cardQuery).getData();
        if (CollectionUtils.isEmpty(rnrCardList)) {
            throw new CuscUserException("", "未查询到" + dto.getOrigCorporationName() + "有实名通过的卡信息");
        }

        log.info("企业责任人变更,原卡信息 = {}", rnrCardList.stream().map(MgRnrCardInfoDTO::getUuid).collect(Collectors.toList()));

        //构建新的RnrRelationDto
        RnrRelationDTO rnrRelationDTO = enterpriseChangeDto2RnrRelation(dto, rnrCardList, serialNumber,orginRnrInfoList.get(0));

        RnrRequestDTO rnrRequestDTO = rnrService.rnrPersonRelationDto2RnrRequestDTO(rnrRelationDTO);
        rnrRequestDTO.setSerialNumber(rnrRelationDTO.getOrder().getUuid());
        rnrRequestDTO.setBizUuid(rnrRelationDTO.getInfo().getUuid());
        rnrRequestDTO.setRequestId(requestId);
		RnrResponseDTO rnrResponseDTO = rnrService.doPersonRnr(rnrRequestDTO, null);


		//添加活体图片1
		MgRnrFileDTO livenessPic1 = new MgRnrFileDTO();
		livenessPic1.setUuid(CuscStringUtils.generateUuid());
		livenessPic1.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
		livenessPic1.setRnrId(rnrRelationDTO.getInfo().getUuid());
		livenessPic1.setIsCompany(CommonYesOrNoEnum.YES.getCode());
		livenessPic1.setRnrCompanyId(rnrRelationDTO.getCompanyInfo().getUuid());
		livenessPic1.setFileSystemId(rnrResponseDTO.getLivenessPic1());
		livenessPic1.setFileType(RnrFileType.LIVENESS_SCREEN_FIRST.getCode());
		livenessPic1.setTenantNo(dto.getTenantNo());
		livenessPic1.setRoutingKey(rnrRelationDTO.getInfo().getRoutingKey());
		livenessPic1.setCreator(rnrRelationDTO.getInfo().getCreator());
		livenessPic1.setFileName("活体视频1.png");
		livenessPic1.setLiaisonId("0");
		rnrRelationDTO.getRnrFileList().add(livenessPic1);

		//添加活体图片1
		MgRnrFileDTO livenessPic2 = new MgRnrFileDTO();
		livenessPic2.setUuid(CuscStringUtils.generateUuid());
		livenessPic2.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
		livenessPic2.setRnrId(rnrRelationDTO.getInfo().getUuid());
		livenessPic2.setIsCompany(CommonYesOrNoEnum.YES.getCode());
		livenessPic2.setRnrCompanyId(rnrRelationDTO.getCompanyInfo().getUuid());
		livenessPic2.setFileSystemId(rnrResponseDTO.getLivenessPic2());
		livenessPic2.setFileType(RnrFileType.LIVENESS_SCREEN_TWO.getCode());
		livenessPic2.setCreator(rnrRelationDTO.getInfo().getCreator());
		livenessPic2.setFileName("活体视频2.png");
		livenessPic2.setTenantNo(rnrRelationDTO.getTenantNo());
		livenessPic2.setRoutingKey(rnrRelationDTO.getInfo().getRoutingKey());
		livenessPic2.setLiaisonId("0");
		rnrRelationDTO.getRnrFileList().add(livenessPic2);




		log.info("企业责任人变更,构建RnrRelation = {}", JSONObject.toJSONString(rnrRelationDTO));
        mgRnrRelationClient.saveRnrRelation(rnrRelationDTO);

		//将实名结果回传给智网
        rnrService.notifyResult(rnrRelationDTO.getCardList(),RnrBizzTypeEnum.INFO_CHANGE.getCode().toString(),serialNumber,null, ResultCodeEnum.PASS.getCode());
	}

	private RnrRelationDTO enterpriseChangeDto2RnrRelation(EnterpriseChangeRnrPersonDTO dto, List<MgRnrCardInfoDTO> rnrCardList, String serialNumber,MgRnrInfoDTO mgRnrInfoDTO) {
        RnrRelationDTO rnrRelationDTO = new RnrRelationDTO();
        rnrRelationDTO.setIsTrust(0);
        rnrRelationDTO.setTenantNo(dto.getTenantNo());

        //实名信息
        MgRnrInfoDTO rnrInfo = new MgRnrInfoDTO();
		BeanUtils.copyProperties(mgRnrInfoDTO,rnrInfo);
        rnrInfo.setRnrBizzType(RnrBizzTypeEnum.INFO_CHANGE.getCode());
        rnrInfo.setTenantNo(dto.getTenantNo());
        rnrInfo.setUuid(CuscStringUtils.generateUuid());
        rnrInfo.setFullName(dto.getCorporationName());
        rnrInfo.setCertType(dto.getCorporationCertType());
        rnrInfo.setCertNumber(dto.getCorporationCertNumber());
        rnrInfo.setCertAddress(dto.getCorporationCertAddress());
        rnrInfo.setGender(Integer.parseInt(dto.getCorporationGender()));
		rnrInfo.setEffectiveDate(DateUtil.parseDate(dto.getCorporationCertEffectiveDate(),DateUtil.YYMM_DD_MM));
        rnrInfo.setExpiredDate(dto.getCorporationCertExpirationDate());
        rnrInfo.setContactAddress(dto.getCorporationContactAddress());
        rnrInfo.setPhone(dto.getCorporationPhone());
        rnrInfo.setCreator(dto.getCreator());
        rnrInfo.setOperator(dto.getCreator());
        rnrInfo.setIsCompany(1);
        rnrRelationDTO.setInfo(rnrInfo);

        //订单信息
        RnrOrderDTO orderDTO = new RnrOrderDTO();
        orderDTO.setTenantNo(dto.getTenantNo());
        orderDTO.setRnrBizzType(RnrBizzTypeEnum.INFO_CHANGE.getCode());
        orderDTO.setRnrId(rnrInfo.getUuid());
        orderDTO.setUuid(CuscStringUtils.generateUuid());
        orderDTO.setOrderType(RnrOrderType.COMPANY_CORPORATION_CHANGE.getCode());
        orderDTO.setAuditType(RnrOrderAuditTypeEnum.MANUAL.getCode());
        orderDTO.setOrderStatus(RnrOrderStatusEnum.ASSIGNMENT.getCode());
        orderDTO.setOrderSource(RnrOrderSourceEnum.PORTAL.getCode());
        orderDTO.setSerialNumber(serialNumber);
        orderDTO.setIsBatchOrder(0);
        orderDTO.setCreator(dto.getCreator());
        orderDTO.setOperator(dto.getCreator());
        orderDTO.setSendWorkOrder(true);
		orderDTO.setOrgId(mgRnrInfoDTO.getOrgId());
        rnrRelationDTO.setOrder(orderDTO);


		MgRnrCompanyInfoDTO companyQueryDto = new MgRnrCompanyInfoDTO();
		companyQueryDto.setTenantNo(dto.getTenantNo());
		companyQueryDto.setCompanyName(dto.getCompanyName());
		Response<List<MgRnrCompanyInfoDTO>> companyResponse = companyInfoClient.queryByList(companyQueryDto);

        //公司信息
        MgRnrCompanyInfoDTO companyInfoDTO = new MgRnrCompanyInfoDTO();
        if (null != companyResponse && companyResponse.isSuccess() && !CollectionUtils.isEmpty(companyResponse.getData())) {
			MgRnrCompanyInfoDTO orginalCompanyInfo = companyResponse.getData().get(0);
			BeanUtils.copyProperties(orginalCompanyInfo,companyInfoDTO);
		}

        companyInfoDTO.setTenantNo(dto.getTenantNo());
        companyInfoDTO.setUuid(CuscStringUtils.generateUuid());
        companyInfoDTO.setRnrBizzType(RnrBizzTypeEnum.INFO_CHANGE.getCode());
        companyInfoDTO.setRnrId(rnrInfo.getUuid());
        companyInfoDTO.setCompanyName(dto.getCompanyName());
        companyInfoDTO.setCreator(dto.getCreator());
        companyInfoDTO.setOperator(dto.getCreator());
        MgVehicleCompanyDTO vehicleQuery = new MgVehicleCompanyDTO();
        vehicleQuery.setTenantNo(dto.getTenantNo());
        vehicleQuery.setCompanyName(dto.getCompanyName());
        Response<List<MgVehicleCompanyDTO>> vcListResp = vehicleCompanyClient.queryByList(vehicleQuery);
		MgVehicleCompanyDTO vehicleCompanyDTO = null;
        if (vcListResp != null && vcListResp.isSuccess() && !CollectionUtils.isEmpty(vcListResp.getData())) {
            companyInfoDTO.setIsVehicleCompany(1);
			vehicleCompanyDTO = vcListResp.getData().get(0);
        }
        rnrRelationDTO.setCompanyInfo(companyInfoDTO);


        //文件信息
        List<MgRnrFileDTO> fileDTOList = new ArrayList<>();
        //视频
        MgRnrFileDTO videoFile = new MgRnrFileDTO();
        videoFile.setTenantNo(dto.getTenantNo());
        videoFile.setUuid(CuscStringUtils.generateUuid());
        videoFile.setFileType(RnrFileType.LIVENESS_VIDEO.getCode());
        videoFile.setRnrId(rnrInfo.getUuid());
        videoFile.setLiaisonId("0");
        videoFile.setIsCompany(1);
        videoFile.setRnrCompanyId(companyInfoDTO.getUuid());
        videoFile.setFileSystemId(dto.getCorporationVideo());
        videoFile.setCreator(dto.getCreator());
        videoFile.setOperator(dto.getCreator());
        fileDTOList.add(videoFile);

        //责任人证件信息
        List<MgRnrFileDTO> certFileList = getCorporationCertFile(dto, rnrInfo.getUuid(), companyInfoDTO.getUuid());
        fileDTOList.addAll(certFileList);

        //企业实名认证授权书
        for (String syetemFileId : dto.getAuthorizationLetterPic()) {
            MgRnrFileDTO authFile = new MgRnrFileDTO();
            authFile.setTenantNo(dto.getTenantNo());
            authFile.setUuid(CuscStringUtils.generateUuid());
            authFile.setFileType(RnrFileType.ENTERPRISE_AUTH_FILE.getCode());
            authFile.setRnrId(rnrInfo.getUuid());
            authFile.setLiaisonId("0");
            authFile.setIsCompany(1);
            authFile.setRnrCompanyId(companyInfoDTO.getUuid());
            authFile.setFileSystemId(syetemFileId);
            authFile.setCreator(dto.getCreator());
            authFile.setOperator(dto.getCreator());

            fileDTOList.add(authFile);
        }

		if (null != vehicleCompanyDTO) {
			MgRnrFileDTO fileQuery = new MgRnrFileDTO();
			fileQuery.setRnrId(vehicleCompanyDTO.getFirstRnrId());
			fileQuery.setTenantNo(orderDTO.getTenantNo());
			List<MgRnrFileDTO> fileList = fileClient.getByRnrid(fileQuery).getData();

			for (MgRnrFileDTO fileDTO : fileList) {
				//新提交的个人信息 和 企业实名认证授权书 不需要复制过来
				if (notChangeNewSubmitFile(fileDTO.getFileType())){
					MgRnrFileDTO copyFile = new MgRnrFileDTO();
					BeanUtils.copyProperties(fileDTO,copyFile);
					copyFile.setUuid(CuscStringUtils.generateUuid());
					copyFile.setRnrId(rnrInfo.getUuid());
					copyFile.setRnrCompanyId(companyInfoDTO.getUuid());

					fileDTOList.add(copyFile);
				}
			}


		}


        rnrRelationDTO.setRnrFileList(fileDTOList);

        //卡信息
        List<MgRnrCardInfoDTO> newCardIdList = rnrCardList.stream().map(origCard -> {
            MgRnrCardInfoDTO newCard = new MgRnrCardInfoDTO();
            newCard.setUuid(CuscStringUtils.generateUuid());
            newCard.setRnrId(rnrInfo.getUuid());
            newCard.setOrderId(orderDTO.getUuid());
            newCard.setIotId(origCard.getIotId());
            newCard.setOldCardId(origCard.getUuid());
            newCard.setIccid(origCard.getIccid());
            newCard.setRnrStatus(RnrStatus.INIT.getCode());
            newCard.setTenantNo(dto.getTenantNo());
            newCard.setRoutingKey(origCard.getRoutingKey());
            newCard.setCreator(dto.getCreator());
            newCard.setOperator(dto.getCreator());
            newCard.setRnrBizzType(RnrBizzTypeEnum.INFO_CHANGE.getCode());
            return newCard;
        }).collect(Collectors.toList());
        rnrRelationDTO.setCardList(newCardIdList);

        return rnrRelationDTO;
    }


	private boolean notChangeNewSubmitFile(Integer fileType) {
		List<Integer> list = Arrays.asList(RnrFileType.IDENTITY_CARD_BACK.getCode(), RnrFileType.IDENTITY_CARD_FRONT.getCode(),
				RnrFileType.OFFICIAL_CARD_FRONT.getCode(), RnrFileType.OFFICIAL_CARD_BACK.getCode(),
				RnrFileType.POLICE_CARD_FRONT.getCode(), RnrFileType.POLICE_CARD_BACK.getCode(),
				RnrFileType.HK_MACAO_PASSPORT_FRONT.getCode(), RnrFileType.HK_MACAO_PASSPORT_BACK.getCode(),
				RnrFileType.TAIWAN_CARD_FRONT.getCode(), RnrFileType.TAIWAN_CARD_BACK.getCode(),
				RnrFileType.FOREIGN_NATIONAL_PASSPORT_FRONT.getCode(), RnrFileType.FOREIGN_NATIONAL_PASSPORT_BACK.getCode(),
				RnrFileType.HK_MACAO_RESIDENCE_PERMIT_FRONT.getCode(), RnrFileType.HK_MACAO_RESIDENCE_PERMIT_BACK.getCode(),
				RnrFileType.TAIWAN_RESIDENCE_PERMIT_FRONT.getCode(), RnrFileType.TAIWAN_RESIDENCE_PERMIT_BACK.getCode(),
				RnrFileType.RESIDENCE_BOOKLET_FRONT.getCode(), RnrFileType.RESIDENCE_BOOKLET_BACK.getCode(), RnrFileType.ENTERPRISE_AUTH_FILE.getCode());
		return !list.contains(fileType);
	}

    private List<MgRnrFileDTO> getCorporationCertFile(EnterpriseChangeRnrPersonDTO dto, String rnrId, String companyId) {
        String corporationCertType = dto.getCorporationCertType();
        CertTypeEnum certTypeEnum = CertTypeEnum.getEnumByCode(corporationCertType);
        if (null == certTypeEnum) {
            return Collections.emptyList();
        }

        List<MgRnrFileDTO> fileDTOS = new ArrayList<>();

        List<RnrFileType> rnrFileList = CertFileRnrFileTypeRelation.getRnrFileList(certTypeEnum);
        List<String> corporationCertPic = dto.getCorporationCertPic();

        for (int index = 0; index < corporationCertPic.size(); index++) {
            int rnrFileType;
            if (index >= rnrFileList.size()) {
                rnrFileType = rnrFileList.get(rnrFileList.size() - 1).getCode();
            } else {
                rnrFileType = rnrFileList.get(index).getCode();
            }
            MgRnrFileDTO fileDTO = new MgRnrFileDTO();
            fileDTO.setTenantNo(dto.getTenantNo());
            fileDTO.setUuid(CuscStringUtils.generateUuid());
            fileDTO.setFileType(rnrFileType);
            fileDTO.setRnrId(rnrId);
            fileDTO.setLiaisonId("0");
            fileDTO.setIsCompany(1);
            fileDTO.setRnrCompanyId(companyId);
            fileDTO.setFileSystemId(corporationCertPic.get(index));
            fileDTO.setCreator(dto.getCreator());
            fileDTO.setOperator(dto.getCreator());

            fileDTOS.add(fileDTO);
        }
        return fileDTOS;
    }


	@Override
	public void submitH5(RnrRelationDTO rnrRelationDTO) {

		rnrRelationDTO.getInfo().setRnrStatus(RnrStatus.INIT.getCode());
		rnrRelationDTO.getInfo().setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
		rnrRelationDTO.getOrder().setOrderStatus(RnrOrderStatusEnum.COMMIT.getCode());
		rnrRelationDTO.getOrder().setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
		rnrRelationDTO.getOrder().setSendWorkOrder(false);
		rnrRelationDTO.getCardList().forEach(card->card.setRnrStatus(RnrStatus.INIT.getCode()));
		Response response = mgRnrRelationClient.saveRnrRelation(rnrRelationDTO);

		if (response.isSuccess()) {
			RnrOrderDTO message = new RnrOrderDTO();
			message.setUuid(rnrRelationDTO.getOrder().getUuid());
			changeOrUnbindIccidsClient.sendMSMToMQ(message);
		}
	}

	@Override
	public Integer personH5CallBack(EnterpriseH5CallBackRequestDTO dto) {
		if (null == dto.getLivenessPicFileId() || dto.getLivenessPicFileId().length != 2) {
			throw new CuscUserException("","活体照片不是2张");
		}
		//订单号
		String orderNo = dto.getOrderNo();
        //根据订单号加锁
        try {
            boolean lockStatus = cacheFactory.getLockService().lock(RedisConstant.RNR_H5_CALLBACK_LOCK + orderNo,
                    RedisConstant.RNR_H5_CALLBACK_LOCK_EXPIRE);
            if(!lockStatus){
                throw new CuscUserException("", "当前有正在处理的实名请求，请勿重复提交");
            }
        } catch (CacheException e) {
            log.error("personH5CallBack 加锁失败 ", e);
        }
		RnrOrderDTO orderQuery = new RnrOrderDTO();
		orderQuery.setUuid(orderNo);
		Response<RnrOrderDTO> orderResponse = orderClient.getByUuid(orderQuery);
		if (!orderResponse.isSuccess() || null == orderResponse.getData()) {
			throw new CuscUserException("","未查询到订单信息");
		}
		RnrOrderDTO orderDTO = orderResponse.getData();

        //判断工单是否作废
        if (orderDTO.getOrderStatus() != null
                && RnrOrderStatusEnum.CANCEL.getCode().intValue() == orderDTO.getOrderStatus().intValue()) {
            throw new CuscUserException("", "实名工单已超时作废，请重新实名");
        }
        if (orderDTO.getOrderStatus() != null
                && RnrOrderStatusEnum.NOT_PASS.getCode().intValue() == orderDTO.getOrderStatus().intValue()) {
            throw new CuscUserException("", "实名工单审核不通过，请重新实名");
        }
        if (orderDTO.getOrderStatus() != null
                && RnrOrderStatusEnum.ASSIGNMENT.getCode().intValue() == orderDTO.getOrderStatus().intValue()) {
            throw new CuscUserException("", "已有工单在审核中,请等待");
        }

        //实名通过
        if (orderDTO.getOrderStatus() != null && RnrOrderStatusEnum.PASS.getCode() == orderDTO.getOrderStatus()) {
            return RnrResultEnum.PASS.getCode();
        }

		String rnrId = orderDTO.getRnrId();
		MgRnrInfoDTO rnrInfoQuery = new MgRnrInfoDTO();
		rnrInfoQuery.setUuid(rnrId);
		Response<MgRnrInfoDTO> rnrInfoResponse = rnrInfoClient.getByUuid(rnrInfoQuery);
		if (!rnrInfoResponse.isSuccess() || null == rnrInfoResponse.getData()) {
			throw new CuscUserException("","未查询到实名信息");
		}
		MgRnrInfoDTO rnrInfo = rnrInfoResponse.getData();

        if (orderDTO.getOrderStatus() != null
                && RnrOrderStatusEnum.ASSIGNMENT.getCode().intValue() == orderDTO.getOrderStatus().intValue()) {
            throw new CuscUserException("", "已有工单在审核中,请等待");
        }

		String[] bestBaseLiveness64 = new String[2];
        String[] bestBaseLiveness64ForFile = new String[2];

        AttachmentDTO attachmentDTO = new AttachmentDTO();
        attachmentDTO.setSerialNumber(CuscStringUtils.generateUuid());
        attachmentDTO.setFileId(dto.getLivenessPicFileId()[0]);
        Response<AttachmentRespDTO> response1 = cloudService.postForResponse(CloudMethod.ATTACHMENT_DOWNLOAD,
                attachmentDTO, AttachmentRespDTO.class);
		if (response1.isSuccess()) {
			AttachmentRespDTO attachmentRespDTO = response1.getData();
			bestBaseLiveness64[0] = attachmentRespDTO.getBase64();
			bestBaseLiveness64[1] = attachmentRespDTO.getBase64();
			bestBaseLiveness64ForFile[0]=attachmentRespDTO.getBase64();
		} else {
			throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"下载活体截图失败");
		}

        AttachmentDTO attachmentDTOForVideo = new AttachmentDTO();
        attachmentDTOForVideo.setSerialNumber(CuscStringUtils.generateUuid());
        attachmentDTOForVideo.setFileId(dto.getVideFileId());
        Response<AttachmentRespDTO> response3 = cloudService.postForResponse(CloudMethod.ATTACHMENT_DOWNLOAD,
                attachmentDTOForVideo, AttachmentRespDTO.class);
        if(response3.isSuccess()){
            AttachmentRespDTO attachmentRespDTO = response3.getData();
            bestBaseLiveness64ForFile[1]=attachmentRespDTO.getBase64();
        }else {
			log.info("活体视频下载失败,orderNo = {}",dto.getOrderNo());
		}



		RnrRequestDTO rnrRequestDTO = rnrService.h5InfoToRnrRequest(false,orderDTO, rnrId, rnrInfo);
		RnrResponseDTO rnrResponseDTO = rnrService.doPersonRnr(rnrRequestDTO, bestBaseLiveness64);

		//文件上传
		String best64Img = bestBaseLiveness64ForFile[0];
		String best64ImgFileKey = "";
		if (StringUtils.isNotBlank(best64Img)){
			best64ImgFileKey = fileService.upLoadImgBase64(best64Img,"png");
		}

		String video = bestBaseLiveness64ForFile[1];
		String videoFileKey = "";
		if (StringUtils.isNotBlank(video)){
			videoFileKey = fileService.upLoadFileBase64(video,"mp4");
		}

		//视屏文件存储
		MgRnrFileDTO videoFile = new MgRnrFileDTO();
		videoFile.setUuid(CuscStringUtils.generateUuid());
		videoFile.setRnrId(rnrId);
		videoFile.setFileType(RnrFileType.LIVENESS_VIDEO.getCode());
		videoFile.setFileSystemId(videoFileKey);
		videoFile.setTenantNo(orderDTO.getTenantNo());
		videoFile.setRoutingKey(orderDTO.getRoutingKey());
		videoFile.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
        videoFile.setIsCompany(1);
        fileClient.add(videoFile);

		//活体截图1
		MgRnrFileDTO faceFile = new MgRnrFileDTO();
		faceFile.setUuid(CuscStringUtils.generateUuid());
		faceFile.setRnrId(rnrId);
		faceFile.setFileType(RnrFileType.LIVENESS_SCREEN_FIRST.getCode());
		faceFile.setFileSystemId(best64ImgFileKey);
		faceFile.setTenantNo(orderDTO.getTenantNo());
		faceFile.setRoutingKey(orderDTO.getRoutingKey());
		faceFile.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
        faceFile.setIsCompany(1);
        fileClient.add(faceFile);

		//活体截图1
		MgRnrFileDTO nationFile = new MgRnrFileDTO();
		nationFile.setUuid(CuscStringUtils.generateUuid());
		nationFile.setRnrId(rnrId);
		nationFile.setFileType(RnrFileType.LIVENESS_SCREEN_TWO.getCode());
		nationFile.setFileSystemId(best64ImgFileKey);
		nationFile.setTenantNo(orderDTO.getTenantNo());
		nationFile.setRoutingKey(orderDTO.getRoutingKey());
		nationFile.setRnrBizzType(RnrBizzTypeEnum.Bind.getCode());
        nationFile.setIsCompany(1);
        fileClient.add(nationFile);




		RnrOrderDTO orderUpdate = new RnrOrderDTO();
		orderUpdate.setUuid(orderDTO.getUuid());
		orderUpdate.setOrderStatus(RnrOrderStatusEnum.ASSIGNMENT.getCode());
		orderClient.update(orderUpdate);

		try {
			//发起一个工单'
			RnrOrderDTO workOrder = new RnrOrderDTO();
			workOrder.setUuid(orderDTO.getUuid());
			orderClient.startWorkOrder(workOrder);
		} catch (Exception e) {
			log.error("企业H5回调发起工单流程失败:info = {}",JSONObject.toJSONString(dto),e);
		}

        try {
            //解锁
            cacheFactory.getLockService().unLock(RedisConstant.RNR_H5_CALLBACK_LOCK + orderNo);
        } catch (CacheException e) {
            log.error("personH5CallBack 解锁失败 ", e);
        }

		return RnrResultEnum.REVIEW.getCode();
	}

}
