
package com.tmerclub.cloud.multishop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.payment.allinpay.member.resp.UpdateCompanyInfoResp;
import com.tmerclub.cloud.api.payment.dto.UpdateCompanyInfoDTO;
import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.common.constant.*;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.common.util.PrincipalUtil;
import com.tmerclub.cloud.multishop.constant.AuditStatus;
import com.tmerclub.cloud.multishop.dto.ShopAuditingDTO;
import com.tmerclub.cloud.multishop.dto.ShopCompanyAuditingDTO;
import com.tmerclub.cloud.multishop.dto.ShopCompanyDTO;
import com.tmerclub.cloud.multishop.mapper.CompanyAuditingMapper;
import com.tmerclub.cloud.multishop.mapper.ShopDetailMapper;
import com.tmerclub.cloud.multishop.model.ShopCompany;
import com.tmerclub.cloud.multishop.model.ShopCompanyAuditing;
import com.tmerclub.cloud.multishop.service.*;
import com.tmerclub.cloud.multishop.vo.ShopAuditingVO;
import com.tmerclub.cloud.multishop.vo.ShopCompanyAuditingVO;
import com.tmerclub.cloud.multishop.vo.ShopCompanyVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author chiley
 */
@Service
public class CompanyAuditingServiceImpl implements CompanyAuditingService {

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

    @Autowired
    private CompanyAuditingMapper companyAuditingMapper;
    @Autowired
    private ShopCompanyService shopCompanyService;
    @Autowired
    private ShopAllinpayService shopAllinpayService;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;
    @Autowired
    private ShopDetailMapper shopDetailMapper;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ShopBankCardService shopBankCardService;
    @Autowired
    private ShopAuditingService shopAuditingService;

    @Override
    public void updateRemark(ShopCompanyAuditingDTO shopCompanyAuditingDTO) {
        companyAuditingMapper.update(BeanUtil.map(shopCompanyAuditingDTO, ShopCompanyAuditing.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyChangeCompanyInfo(ShopCompanyDTO shopCompanyDTO) {
        ShopDetailVO shopDetailVO = shopDetailMapper.getByShopId(shopCompanyDTO.getShopId());
        ShopCompanyVO shopCompanyVO = new ShopCompanyVO();
        if (shopAllinpayService.getIsAllinpay()) {
            if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                logger.info("获取影印件还未通过的商家{}工商信息，状态为待审核", shopCompanyDTO.getShopId());
                shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopCompanyDTO.getShopId(), AuditStatus.WAITAUDIT.value());
            } else {
                logger.info("获取影印件已经通过的商家{}工商信息，状态为审核成功", shopCompanyDTO.getShopId());
                shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopCompanyDTO.getShopId(), AuditStatus.SUCCESSAUDIT.value());
            }
        }
        if (StrUtil.isNotBlank(shopCompanyDTO.getLegalPhone())) {
            if (!PrincipalUtil.isDbPhone(shopCompanyDTO.getLegalPhone(), shopCompanyVO.getLegalPhone(), true)) {
                throw new LuckException("请输入正确的手机号");
            }
            if (shopCompanyDTO.getLegalPhone().contains(Constant.ASTERISK)) {
                shopCompanyDTO.setLegalPhone(shopCompanyVO.getLegalPhone());
            }
        }
        // 把之前审核不通过的工商信息删除
        shopCompanyService.deleteByShopIdAndStatus(shopCompanyDTO.getShopId(), AuditStatus.FAILAUDIT.value());
        // 保存变更工商信息
        ShopCompany shopCompany = BeanUtil.map(shopCompanyDTO, ShopCompany.class);
        shopCompany.setStatus(AuditStatus.WAITAUDIT.value());
        shopCompanyService.save(shopCompany, false);
        // 生成审核信息
        Long companyAuditingId = generateAuditInformation(shopCompany);
        if (shopAllinpayService.getIsAllinpay()) {
            if (Objects.equals(shopDetailVO.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.SUCCESS.value())) {
                logger.info("商家{}工商信息已经通过审核，更新工商信息内容和状态和后续处理", shopCompanyDTO.getShopId());
                // 审核成功的要进行更改的
                updateCompany(shopCompanyDTO, companyAuditingId, shopCompanyVO, shopDetailVO);
            }
        }
    }

    private void updateCompany(ShopCompanyDTO shopCompanyDTO, Long companyAuditingId, ShopCompanyVO shopCompanyVO, ShopDetailVO shopDetailVO) {
        Long shopId = shopCompanyDTO.getShopId();
        ServerResponseEntity<Integer> idCardStatus = allinpayFeignClient.getIdCardStatus(AllinpayConstant.SHOP + shopId);
        if (!idCardStatus.isSuccess()) {
            throw new LuckException(idCardStatus.getMsg());
        }
        if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), idCardStatus.getData())) {
            logger.info("商家{}影印件信息状态{}和通联影印件信息状态{}不一致，处理影印件状态", shopCompanyDTO.getShopId(),
                    shopDetailVO.getIdCardCollectProcessStatus(), idCardStatus.getData());
            // 不一致先更新
            shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus.getData());
        }
        // 改了基本信息
        boolean isChangeInfo = getIsChangeInfo(shopCompanyDTO, shopCompanyVO);
        // 改了关键信息
        boolean isChangeKeyInfo = getIsChangeKeyInfo(shopCompanyDTO, shopCompanyVO);
        // 改了影印件
        boolean isChangeIdCard = getIsChangeIdCard(shopCompanyDTO, shopCompanyVO);
        if (!isChangeInfo && !isChangeKeyInfo && !isChangeIdCard) {
            // 没有改通联有关信息直接审核成功
            logger.info("没有修改通联有关信息，店铺{}工商信息审核通过", shopId);
            audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
            return;
        }

        if (isChangeInfo || isChangeKeyInfo) {
            logger.info("商家修改了基本信息{}或关键信息{}，交给通联审核", isChangeInfo, isChangeKeyInfo);
            // 对于信息修改操作，上送所有需修改信息均认证成功才操作修改，否则信息均不修改；
            UpdateCompanyInfoDTO updateCompanyInfoDTO = new UpdateCompanyInfoDTO(AllinpayConstant.SHOP + shopId);
            updateCompanyInfoDTO.setCompanyName(shopCompanyDTO.getFirmName());
            updateCompanyInfoDTO.setCompanyAddress(shopCompanyDTO.getResidence());
            updateCompanyInfoDTO.setLegalPhone(shopCompanyDTO.getLegalPhone());
            updateCompanyInfoDTO.setLegalIds(shopCompanyDTO.getLegalIds());
            updateCompanyInfoDTO.setLegalName(shopCompanyDTO.getRepresentative());
            // 通联审核
            ServerResponseEntity<UpdateCompanyInfoResp> response = allinpayFeignClient.updateCompanyInfo(updateCompanyInfoDTO);
            if (!response.isSuccess()) {
                logger.info("通联审核店铺{}修改的工商信息失败，拒绝更新，原因为{}", shopId, response.getMsg());
                // 审核失败不会更新影印件审核，只需要拒绝更新就可以了
                audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.FAILAUDIT.value(), response.getMsg()));
                return;
            }
            UpdateCompanyInfoResp updateCompanyInfoResp = response.getData();
            if (Objects.equals(updateCompanyInfoResp.getResult(), com.tmerclub.cloud.api.payment.constant.AuditStatus.SUCCESS.getCode())) {
                logger.info("通联审核店铺{}修改的工商信息成功", shopId);
                if (isChangeKeyInfo) {
                    logger.info("店铺{}修改了关键信息，并且审核通过，更新店铺为通联上线待审核，等待影印件重新审核通过", shopId);
                    // 修改了会触发ocr的
                    //审核成功 通联更新了企业信息 更新会触发ocr，店铺需要下线等待影印件审核通过
                    audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
                    // 更新店铺为通联上线待审核，影印件审核通过即可营业
                    shopDetailMapper.updateShopToWaitAudit(shopCompanyDTO.getShopId());
                } else if (!isChangeIdCard) {
                    logger.info("店铺{}没有修改了关键信息，也没有影印件要上传，直接审核成功", shopId);
                    // 没有修改关键信息,没有上传影印件可以直接成功
                    audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
                    if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                        logger.info("店铺{}影印件状态异常，更新影印件", shopId);
                        shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus.getData());
                    }
                    return;
                }
            } else if (Objects.equals(updateCompanyInfoResp.getResult(), com.tmerclub.cloud.api.payment.constant.AuditStatus.FAIL.getCode())) {
                logger.info("通联审核店铺{}修改的工商信息失败，拒绝更新", shopId);
                // 审核失败不会更新影印件审核，只需要拒绝更新就可以了
                audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.FAILAUDIT.value(), updateCompanyInfoResp.getFailReason()));
                return;
            }
        }

        // 如果有改变影印件，没有改变别的信息，在这里影印件需要重新上传，上传失败拒绝更新
        onlyChangeIdCard(shopCompanyDTO, companyAuditingId, shopDetailVO, shopId, idCardStatus, isChangeInfo, isChangeKeyInfo);
    }

    private void onlyChangeIdCard(ShopCompanyDTO shopCompanyDTO, Long companyAuditingId, ShopDetailVO shopDetailVO, Long shopId, ServerResponseEntity<Integer> idCardStatus, boolean isChangeInfo, boolean isChangeKeyInfo) {
        if (!isChangeInfo && !isChangeKeyInfo) {
            logger.info("店铺{}只修改影印件，影印件上传", shopId);
            if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), idCardStatus.getData()) && Objects.equals(idCardStatus.getData(), IdCardCollectProcessStatus.ALL.value())) {
                logger.info("店铺{}影印件已经通过审核，但是店铺影印件状态没更新，更新状态并且拒绝影印件上传审核", shopId);
                // 如果影印件上传成功但是这里没有更新的话要更新一下
                audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件已经审核通过，无需更新"));
                shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus.getData());
                return;
            } else if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), idCardStatus.getData())) {
                logger.info("店铺{}影印件状态没更新，更新状态", shopId);
                shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus.getData());
            } else if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                logger.info("店铺{}影印件已经通过审核，拒绝影印件上传审核", shopId);
                audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件已经审核通过，无需更新"));
                return;
            }
            String result = shopCompanyService.idCardCollect(BeanUtil.map(shopCompanyDTO, ShopCompanyVO.class), shopId);
            if (!Objects.equals(result, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                logger.info("店铺{}影印件上传失败，拒绝影印件更新", shopId);
                audit(new ShopCompanyAuditingDTO(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件上传失败，请重新上传"));
                return;
            }
            // 更新店铺为通联上线待审核，影印件审核通过即可营业
            shopDetailMapper.updateShopToWaitAudit(shopCompanyDTO.getShopId());
            // 更新店铺影印件采集状态
            shopDetailMapper.updateAllinpayIdCardStatus(shopCompanyDTO.getShopId(), IdCardCollectProcessStatus.WAIT_AUDIT.value());
        }
    }

    private boolean getIsChangeIdCard(ShopCompanyDTO shopCompanyDTO, ShopCompanyVO shopCompany) {
        if (Objects.isNull(shopCompany)) {
            return true;
        }
        if (!Objects.equals(shopCompany.getIdentityCardFront(), shopCompanyDTO.getIdentityCardFront())) {
            return true;
        }
        if (!Objects.equals(shopCompany.getBusinessLicense(), shopCompanyDTO.getBusinessLicense())) {
            return true;
        }
        return !Objects.equals(shopCompany.getIdentityCardLater(), shopCompanyDTO.getIdentityCardLater());
    }

    private boolean getIsChangeInfo(ShopCompanyDTO shopCompanyDTO, ShopCompanyVO shopCompanyVO) {
        if (Objects.isNull(shopCompanyVO)) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getResidence(), shopCompanyVO.getResidence())) {
            return true;
        }
        return !Objects.equals(shopCompanyDTO.getLegalPhone(), shopCompanyVO.getLegalPhone());
    }

    private boolean getIsChangeKeyInfo(ShopCompanyDTO shopCompanyDTO, ShopCompanyVO shopCompanyVO) {
        if (Objects.isNull(shopCompanyVO)) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getRepresentative(), shopCompanyVO.getRepresentative())) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getFirmName(), shopCompanyVO.getFirmName())) {
            return true;
        }
        return !Objects.equals(shopCompanyDTO.getLegalIds(), shopCompanyVO.getLegalIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCompanyInfoResult(String bizUserId, Integer status, Integer result, String failReason) {
        Long shopId = Long.valueOf(bizUserId.substring(AllinpayConstant.SHOP_LENGTH));
        ShopCompanyVO waitAuditShopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        ShopCompanyVO successShopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.SUCCESSAUDIT.value());
        ShopCompanyAuditingVO shopCompanyAuditingVO = getLatestAuditingByShopId(shopId);
        // 更新失败
        if (Objects.equals(result, com.tmerclub.cloud.api.payment.constant.AuditStatus.FAIL.getCode())) {
            logger.info("通联回调审核店铺{}修改的工商信息失败，拒绝更新，原因为{}", shopId, failReason);
            audit(new ShopCompanyAuditingDTO(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), failReason));
        }
        // 更新成功
        else if (Objects.equals(result, com.tmerclub.cloud.api.payment.constant.AuditStatus.SUCCESS.getCode())) {
            // 如果有改变企业名称，法人名称，需要重新签约提现协议
            checkChangeName(waitAuditShopCompany, successShopCompany, shopId);
            if (getIsChangeIdCard(BeanUtil.map(waitAuditShopCompany, ShopCompanyDTO.class), successShopCompany)) {
                logger.info("通联回调审核店铺{}修改的工商信息成功，修改了影印件，重新上传影印件", shopId);
                // 修改了影印件
                String idCardCollectResult = shopCompanyService.idCardCollect(waitAuditShopCompany, shopId);
                if (!Objects.equals(idCardCollectResult, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                    logger.info("通联回调审核店铺{}修改的工商信息成功，影印件上传异常，拒绝申请", shopId);
                    audit(new ShopCompanyAuditingDTO(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), "影印件上传异常，请重试"));
                    return;
                }
                // 更新店铺为通联上线待审核，影印件审核通过即可营业
                shopDetailMapper.updateShopToWaitAudit(shopId);
                // 更新店铺影印件采集状态
                shopDetailMapper.updateAllinpayIdCardStatus(shopId, IdCardCollectProcessStatus.WAIT_AUDIT.value());
            } else {
                logger.info("通联回调审核店铺{}修改的工商信息成功，没有修改影印件", shopId);
                if (!Objects.equals(status, IdCardCollectProcessStatus.ALL.value())) {
                    logger.info("通联回调审核店铺{}修改的工商信息成功，没有修改影印件，影印件ocr失败", shopId);
                    // 影印件ocr失败了，对店铺进行状态更新
                    // 更新店铺为通联上线待审核，影印件审核通过即可营业
                    shopDetailMapper.updateShopToWaitAudit(shopId);
                    // 更新店铺影印件采集状态
                    shopDetailMapper.updateAllinpayIdCardStatus(shopId, status);
                    return;
                }
                // 审核成功,影印件也成功
                audit(new ShopCompanyAuditingDTO(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.SUCCESSAUDIT.value(), ""));
            }
        }
    }


    private void checkChangeName(ShopCompanyVO shopCompanyDTO, ShopCompanyVO shopCompany, Long shopId) {
        if (!Objects.equals(shopCompany.getFirmName(), shopCompanyDTO.getFirmName())) {
            logger.info("通联回调审核店铺{}修改的工商信息成功，修改了企业名称，需要重新签约对公提现协议", shopId);
            shopDetailMapper.updateAcctProtocolNoByType(shopId, SignAcctType.COMPANY.getValue(), null);
        }
        if (!Objects.equals(shopCompany.getRepresentative(), shopCompanyDTO.getRepresentative())) {
            logger.info("通联回调审核店铺{}修改的工商信息成功，修改了法人姓名，需要重新签约法人提现协议", shopId);
            shopDetailMapper.updateAcctProtocolNoByType(shopId, SignAcctType.LEGAL_PERSON.getValue(), null);
        }
    }

    @Override
    public ShopCompanyAuditingVO getLatestAuditingByShopId(Long shopId) {
        return companyAuditingMapper.getLatestAuditingByShopId(shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revoke(Long shopId) {
        if (shopAllinpayService.getIsAllinpay()) {
            throw new LuckException("当前无法撤销申请");
        }
        ShopCompanyAuditingVO shopCompanyAuditingVO = getLatestAuditingByShopId(shopId);
        if (Objects.isNull(shopCompanyAuditingVO) || !Objects.equals(shopCompanyAuditingVO.getStatus(), AuditStatus.WAITAUDIT.value())) {
            throw new LuckException("申请信息未能找到，请刷新页面");
        }
        // 删除申请变更的工商信息
        shopCompanyService.deleteByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        // 删除申请审核信息
        companyAuditingMapper.deleteById(shopCompanyAuditingVO.getCompanyAuditingId());
    }

    @Override
    public PageVO<ShopCompanyAuditingVO> page(PageDTO pageDTO, ShopCompanyAuditingDTO shopCompanyAuditingDTO) {
        return PageUtil.doPage(pageDTO, () -> companyAuditingMapper.list(shopCompanyAuditingDTO));
    }

    @Override
    public ShopCompanyAuditingVO getAuditInfo(Long shopId) {
        ShopCompanyAuditingVO shopCompanyAuditingVO = getLatestAuditingByShopId(shopId);
        if (Objects.isNull(shopCompanyAuditingVO)) {
            if (shopAllinpayService.getIsAllinpay()) {
                ShopCompanyVO shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
                ShopCompanyAuditingVO shopCompanyAuditing = new ShopCompanyAuditingVO();
                shopCompanyAuditing.setShopCompanyVO(shopCompanyVO);
                return shopCompanyAuditing;
            }
            return null;
        }
        ShopCompanyVO shopCompanyVO = shopCompanyService.getById(shopCompanyAuditingVO.getShopCompanyId());
        shopCompanyAuditingVO.setShopCompanyVO(shopCompanyVO);
        return shopCompanyAuditingVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(ShopCompanyAuditingDTO shopCompanyAuditingDTO) {
        boolean isAllinpay = shopAllinpayService.getIsAllinpay();
        ShopCompanyAuditing companyAuditing = companyAuditingMapper.getById(shopCompanyAuditingDTO.getCompanyAuditingId());
        if (Objects.isNull(companyAuditing) || !Objects.equals(companyAuditing.getStatus(), AuditStatus.WAITAUDIT.value())) {
            throw new LuckException("申请信息未能找到，请刷新页面");
        }
        companyAuditing.setAuditorId(isAllinpay ? null : AuthUserContext.get().getUserId());
        // 审核不通过
        if (Objects.equals(shopCompanyAuditingDTO.getStatus(), AuditStatus.FAILAUDIT.value())) {
            companyAuditing.setStatus(AuditStatus.FAILAUDIT.value());
            companyAuditing.setRemarks(shopCompanyAuditingDTO.getRemarks());
            companyAuditingMapper.update(companyAuditing);
            // 把对应的工商信息设置为审核未通过状态
            ShopCompany shopCompany = new ShopCompany();
            shopCompany.setShopCompanyId(companyAuditing.getShopCompanyId());
            shopCompany.setStatus(AuditStatus.FAILAUDIT.value());
            shopCompanyService.updateById(shopCompany);
            return;
        }
        // 审核通过(if不能省略，防止传入非法参数)
        if (Objects.equals(shopCompanyAuditingDTO.getStatus(), AuditStatus.SUCCESSAUDIT.value())) {
            companyAuditing.setStatus(AuditStatus.SUCCESSAUDIT.value());
            companyAuditingMapper.update(companyAuditing);

            shopCompanyService.batchUpdateStatus(companyAuditing.getShopId(), AuditStatus.FAILAUDIT.value(), null);
            // 把对应的工商信息设置为启用状态
            ShopCompany shopCompany = new ShopCompany();
            shopCompany.setShopCompanyId(companyAuditing.getShopCompanyId());
            shopCompany.setStatus(AuditStatus.SUCCESSAUDIT.value());
            shopCompanyService.updateById(shopCompany);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAllinpayShopStatus(String bizUserId, Integer status, String failReason, Integer isPassShop) {
        Long shopId = Long.valueOf(bizUserId.substring(AllinpayConstant.SHOP_LENGTH));
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        if (Objects.equals(status, com.tmerclub.cloud.api.payment.constant.AuditStatus.FAIL.getCode())) {
            logger.info("通联审核商家企业信息失败");
            if (Objects.equals(shopDetailVO.getAllinpayShopStatus(), AllinpayShopStatus.OFFLINE.value()) && Objects.equals(shopDetailVO.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.FAIL.value())) {
                logger.info("店铺{}状态已经处理过，无需下线处理", shopDetailVO.getShopName());
                return;
            }
            auditFail(bizUserId, failReason, shopId);
        } else if (Objects.equals(status, com.tmerclub.cloud.api.payment.constant.AuditStatus.SUCCESS.getCode())) {
            logger.info("通联审核商家企业信息成功");
            if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value()) && Objects.equals(shopDetailVO.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.SUCCESS.value())) {
                return;
            }
            ShopCompanyVO shopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
            // 审核成功 更新店铺状态
            shopBankCardService.updateShopAllinpayStatusToSuccess(shopId);
            if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                // 调用影印件上传接口
                String idCardResult = shopCompanyService.idCardCollect(shopCompany, shopId);
                if (!Objects.equals(idCardResult, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                    logger.error("店铺设置企业信息回调，影印件上传审核失败：{}", idCardResult);
                }
            }
        }
        shopDetailService.removeCacheByShopId(shopId);
    }

    private void auditFail(String bizUserId, String failReason, Long shopId) {
        ShopCompanyAuditingVO shopCompanyAuditingVO = getLatestAuditingByShopId(shopId);
        if (Objects.nonNull(shopCompanyAuditingVO) && Objects.equals(shopCompanyAuditingVO.getStatus(), AuditStatus.WAITAUDIT.value())) {
            logger.info("店铺Id{}已经开店，通联审核失败，拒绝店铺的工商申请", shopId);
            // 如果是已经开店来审核的话要把审核拒绝通过
            audit(new ShopCompanyAuditingDTO(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), failReason));
        } else {
            logger.info("店铺Id{}还未开店，通联审核失败，拒绝店铺的开店申请", shopId);
            // 还未开店，审核失败
            ShopAuditingVO shopAuditing = shopAuditingService.getByshopId(shopId);
            ShopAuditingDTO shopAuditingDTO = BeanUtil.map(shopAuditing, ShopAuditingDTO.class);
            shopAuditingDTO.setStatus(AuditStatus.FAILAUDIT.value());
            shopAuditingDTO.setRemarks(failReason);
            shopDetailService.audit(shopAuditingDTO);
        }
        // 更新审核失败——平台下线
        shopDetailMapper.updateShopAuditFail(shopId);
        logger.info("店铺id为{}通联审核失败原因：{}", bizUserId, failReason);
    }

    /**
     * 生成店铺申请记录
     *
     * @param shopCompany
     */
    private Long generateAuditInformation(ShopCompany shopCompany) {
        ShopCompanyAuditing shopCompanyAuditing = new ShopCompanyAuditing();
        shopCompanyAuditing.setShopId(shopCompany.getShopId());
        shopCompanyAuditing.setShopCompanyId(shopCompany.getShopCompanyId());
        shopCompanyAuditing.setUserId(AuthUserContext.get().getUserId());
        shopCompanyAuditing.setStatus(AuditStatus.WAITAUDIT.value());
        companyAuditingMapper.insert(shopCompanyAuditing);
        return shopCompanyAuditing.getCompanyAuditingId();
    }
}
