package jnpf.certificate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.seata.spring.annotation.GlobalTransactional;
import jnpf.certificate.mapper.CertificateBusinessLicenseExtMapper;
import jnpf.certificate.mapper.CertificateHygieneLicenseExtMapper;
import jnpf.certificate.mapper.CertificateInstanceItemMapper;
import jnpf.certificate.mapper.CertificateInstanceMapper;
import jnpf.certificate.service.CertificateManageApiService;
import jnpf.model.certificate.po.CertificateBusinessLicenseExtEntity;
import jnpf.model.certificate.po.CertificateHygieneLicenseExtEntity;
import jnpf.model.certificate.po.CertificateInstanceEntity;
import jnpf.model.certificate.po.CertificateInstanceItemEntity;
import jnpf.model.certificate.vo.CertificateOrganizeBusinessLicenseVO;
import jnpf.model.warningnotice.enums.CertificateTypeEnum;
import jnpf.util.FtbUtil;
import jnpf.util.ServiceException;
import jnpf.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织营业执照开放接口服务实现。
 */
@Slf4j
@Service
public class CertificateManageApiServiceImpl implements CertificateManageApiService {

    private static final int STATUS_MISSING = 1;
    private static final int STATUS_EXPIRED = 2;
    private static final int STATUS_NEAR_EXPIRE = 3;
    private static final int STATUS_NORMAL = 4;
    private static final int SUBJECT_TYPE_ORGANIZE = 2;
    private static final int SUBJECT_TYPE_STORE = 3;
    private static final int IS_LONG_TERM_NO = 0;
    private static final int NEAR_EXPIRE_DAYS = 30;

    @Autowired
    private CertificateInstanceMapper certificateInstanceMapper;
    @Autowired
    private CertificateBusinessLicenseExtMapper certificateBusinessLicenseExtMapper;
    @Autowired
    private CertificateHygieneLicenseExtMapper certificateHygieneLicenseExtMapper;
    @Autowired
    private CertificateInstanceItemMapper certificateInstanceItemMapper;

    /**
     * 根据组织ID查询营业执照信息。
     */
    @Override
    public CertificateOrganizeBusinessLicenseVO queryBusinessLicense(String organizeId) {
        ServiceException.isTrue(StrUtil.isNotBlank(organizeId), "组织ID不能为空");
        return buildOrganizeBusinessLicenseVO(StrUtil.trim(organizeId));
    }

    /**
     * 根据组织ID列表批量查询营业执照信息。
     */
    @Override
    public List<CertificateOrganizeBusinessLicenseVO> queryBusinessLicenseBatch(Collection<String> organizeIds) {
        if (CollUtil.isEmpty(organizeIds)) {
            return Collections.emptyList();
        }
        List<String> targetIds = organizeIds.stream()
                .filter(StrUtil::isNotBlank)
                .map(StrUtil::trim)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(targetIds)) {
            return Collections.emptyList();
        }

        Map<String, CertificateInstanceEntity> instanceMap = queryBusinessInstanceMap(targetIds);
        Map<String, CertificateBusinessLicenseExtEntity> extMap = queryBusinessExtMap(instanceMap.values());

        List<CertificateOrganizeBusinessLicenseVO> result = new ArrayList<>(targetIds.size());
        for (String organizeId : targetIds) {
            CertificateInstanceEntity instance = instanceMap.get(organizeId);
            CertificateBusinessLicenseExtEntity ext = instance == null ? null : extMap.get(instance.getId());
            result.add(convertToVO(organizeId, instance, ext));
        }
        return result;
    }

    /**
     * 保存组织营业执照信息。
     */
    @Override
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void saveBusinessLicense(CertificateOrganizeBusinessLicenseVO req) {
        ServiceException.notNull(req, "请求参数不能为空");
        String organizeId = StrUtil.trim(req.getOrganizeId());
        ServiceException.isTrue(StrUtil.isNotBlank(organizeId), "组织ID不能为空");

        Date establishDate = parseDate(req.getEstablishDate(), "成立时间");
        Date issueDate = parseDate(req.getIssueDate(), "发证日期");
        Date expireDate = parseDate(req.getExpireDate(), "到期日期");
        Integer isLongTerm = req.getIsLongTerm() == null ? 0 : req.getIsLongTerm();
        if (Integer.valueOf(1).equals(isLongTerm)) {
            expireDate = null;
        }

        String certificateType = CertificateTypeEnum.BUSINESS_LICENSE.getType();
        String certificateImage = trimToNull(req.getCertificateImage());
        int status = calculateStatus(isLongTerm, expireDate);

        String instanceId = upsertBusinessInstance(
                organizeId,
                certificateType,
                certificateImage,
                issueDate,
                expireDate,
                isLongTerm,
                status
        );
        if(Objects.isNull(instanceId)){
            return;
        }
        upsertBusinessExt(instanceId, req, establishDate);
    }

    /**
     * 初始化门店默认缺失证照（营业执照、食品经营许可证）。
     */
    @Override
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void initStoreDefaultCertificates(String storeId) {
        String targetStoreId = StrUtil.trim(storeId);
        ServiceException.isTrue(StrUtil.isNotBlank(targetStoreId), "门店ID不能为空");

        List<String> defaultTypes = Arrays.asList(
                CertificateTypeEnum.BUSINESS_LICENSE.getType(),
                CertificateTypeEnum.HYGIENE_LICENSE.getType()
        );
        for (String certificateType : defaultTypes) {
            initStoreDefaultCertificate(targetStoreId, certificateType);
        }
    }

    /**
     * 根据组织ID删除该主体下全部证照信息。
     */
    @Override
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void deleteBusinessLicense(String organizeId, String loginUserId) {
        String targetOrganizeId = StrUtil.trim(organizeId);
        ServiceException.isTrue(StrUtil.isNotBlank(targetOrganizeId), "组织ID不能为空");

        Date now = new Date();
        LambdaUpdateWrapper<CertificateInstanceEntity> instanceUpdateWrapper = Wrappers.lambdaUpdate();
        instanceUpdateWrapper.eq(CertificateInstanceEntity::getEnabledMark, 0);
        instanceUpdateWrapper.eq(CertificateInstanceEntity::getSubjectId, targetOrganizeId);
        instanceUpdateWrapper.set(CertificateInstanceEntity::getEnabledMark, 1);
        instanceUpdateWrapper.set(CertificateInstanceEntity::getLastModifyTime, now);
        if(StringUtil.isNotBlank(loginUserId)){
            instanceUpdateWrapper.set(CertificateInstanceEntity::getLastModifyUserId, loginUserId);
        }
        certificateInstanceMapper.update(null, instanceUpdateWrapper);

        LambdaQueryWrapper<CertificateInstanceEntity> instanceQueryWrapper = Wrappers.lambdaQuery();
        instanceQueryWrapper.eq(CertificateInstanceEntity::getSubjectType, SUBJECT_TYPE_ORGANIZE);
        instanceQueryWrapper.eq(CertificateInstanceEntity::getSubjectId, targetOrganizeId);
        List<CertificateInstanceEntity> allBusinessInstances = certificateInstanceMapper.selectList(instanceQueryWrapper);
        if (CollUtil.isEmpty(allBusinessInstances)) {
            return;
        }

        List<String> instanceIds = allBusinessInstances.stream()
                .map(CertificateInstanceEntity::getId)
                .filter(StrUtil::isNotBlank)
                .map(StrUtil::trim)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(instanceIds)) {
            return;
        }

        LambdaUpdateWrapper<CertificateBusinessLicenseExtEntity> extUpdateWrapper = Wrappers.lambdaUpdate();
        extUpdateWrapper.eq(CertificateBusinessLicenseExtEntity::getEnabledMark, 0);
        extUpdateWrapper.in(CertificateBusinessLicenseExtEntity::getInstanceId, instanceIds);
        extUpdateWrapper.set(CertificateBusinessLicenseExtEntity::getEnabledMark, 1);
        extUpdateWrapper.set(CertificateBusinessLicenseExtEntity::getLastModifyTime, now);
        extUpdateWrapper.set(CertificateBusinessLicenseExtEntity::getLastModifyUserId, loginUserId);
        certificateBusinessLicenseExtMapper.update(null, extUpdateWrapper);

        LambdaUpdateWrapper<CertificateHygieneLicenseExtEntity> hygieneExtUpdateWrapper = Wrappers.lambdaUpdate();
        hygieneExtUpdateWrapper.eq(CertificateHygieneLicenseExtEntity::getEnabledMark, 0);
        hygieneExtUpdateWrapper.in(CertificateHygieneLicenseExtEntity::getInstanceId, instanceIds);
        hygieneExtUpdateWrapper.set(CertificateHygieneLicenseExtEntity::getEnabledMark, 1);
        hygieneExtUpdateWrapper.set(CertificateHygieneLicenseExtEntity::getLastModifyTime, now);
        hygieneExtUpdateWrapper.set(CertificateHygieneLicenseExtEntity::getLastModifyUserId, loginUserId);
        certificateHygieneLicenseExtMapper.update(null, hygieneExtUpdateWrapper);

        LambdaUpdateWrapper<CertificateInstanceItemEntity> itemUpdateWrapper = Wrappers.lambdaUpdate();
        itemUpdateWrapper.eq(CertificateInstanceItemEntity::getEnabledMark, 0);
        itemUpdateWrapper.in(CertificateInstanceItemEntity::getInstanceId, instanceIds);
        itemUpdateWrapper.set(CertificateInstanceItemEntity::getEnabledMark, 1);
        itemUpdateWrapper.set(CertificateInstanceItemEntity::getLastModifyTime, now);
        itemUpdateWrapper.set(CertificateInstanceItemEntity::getLastModifyUserId, loginUserId);
        certificateInstanceItemMapper.update(null, itemUpdateWrapper);
    }

    /**
     * 查询并组装组织营业执照返回对象。
     */
    private CertificateOrganizeBusinessLicenseVO buildOrganizeBusinessLicenseVO(String organizeId) {
        CertificateInstanceEntity instance = queryLatestBusinessInstance(organizeId);
        CertificateBusinessLicenseExtEntity ext = instance == null ? null : queryLatestBusinessExt(instance.getId());
        return convertToVO(organizeId, instance, ext);
    }

    /**
     * 批量查询营业执照主表数据映射。
     */
    private Map<String, CertificateInstanceEntity> queryBusinessInstanceMap(List<String> organizeIds) {
        LambdaQueryWrapper<CertificateInstanceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CertificateInstanceEntity::getEnabledMark, 0);
        wrapper.eq(CertificateInstanceEntity::getSubjectType, SUBJECT_TYPE_ORGANIZE);
        wrapper.eq(CertificateInstanceEntity::getCertificateType, CertificateTypeEnum.BUSINESS_LICENSE.getType());
        wrapper.in(CertificateInstanceEntity::getSubjectId, organizeIds);
        wrapper.orderByDesc(CertificateInstanceEntity::getLastModifyTime);
        wrapper.orderByDesc(CertificateInstanceEntity::getCreatorTime);
        List<CertificateInstanceEntity> instanceList = certificateInstanceMapper.selectList(wrapper);
        if (CollUtil.isEmpty(instanceList)) {
            return Collections.emptyMap();
        }
        Map<String, CertificateInstanceEntity> result = new LinkedHashMap<>();
        for (CertificateInstanceEntity entity : instanceList) {
            if (entity == null || StrUtil.isBlank(entity.getSubjectId())) {
                continue;
            }
            String subjectId = StrUtil.trim(entity.getSubjectId());
            result.putIfAbsent(subjectId, entity);
        }
        return result;
    }

    /**
     * 批量查询营业执照扩展表数据映射。
     */
    private Map<String, CertificateBusinessLicenseExtEntity> queryBusinessExtMap(Iterable<CertificateInstanceEntity> instances) {
        List<String> instanceIds = new ArrayList<>();
        for (CertificateInstanceEntity entity : instances) {
            if (entity != null && StrUtil.isNotBlank(entity.getId())) {
                instanceIds.add(StrUtil.trim(entity.getId()));
            }
        }
        if (CollUtil.isEmpty(instanceIds)) {
            return Collections.emptyMap();
        }
        LambdaQueryWrapper<CertificateBusinessLicenseExtEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CertificateBusinessLicenseExtEntity::getEnabledMark, 0);
        wrapper.in(CertificateBusinessLicenseExtEntity::getInstanceId, instanceIds);
        wrapper.orderByDesc(CertificateBusinessLicenseExtEntity::getLastModifyTime);
        wrapper.orderByDesc(CertificateBusinessLicenseExtEntity::getCreatorTime);
        List<CertificateBusinessLicenseExtEntity> extList = certificateBusinessLicenseExtMapper.selectList(wrapper);
        if (CollUtil.isEmpty(extList)) {
            return Collections.emptyMap();
        }
        Map<String, CertificateBusinessLicenseExtEntity> result = new LinkedHashMap<>();
        for (CertificateBusinessLicenseExtEntity ext : extList) {
            if (ext == null || StrUtil.isBlank(ext.getInstanceId())) {
                continue;
            }
            result.putIfAbsent(StrUtil.trim(ext.getInstanceId()), ext);
        }
        return result;
    }

    /**
     * 查询组织最新营业执照主表记录。
     */
    private CertificateInstanceEntity queryLatestBusinessInstance(String organizeId) {
        LambdaQueryWrapper<CertificateInstanceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CertificateInstanceEntity::getEnabledMark, 0);
        wrapper.eq(CertificateInstanceEntity::getSubjectType, SUBJECT_TYPE_ORGANIZE);
        wrapper.eq(CertificateInstanceEntity::getSubjectId, organizeId);
        wrapper.eq(CertificateInstanceEntity::getCertificateType, CertificateTypeEnum.BUSINESS_LICENSE.getType());
        wrapper.orderByDesc(CertificateInstanceEntity::getLastModifyTime);
        wrapper.orderByDesc(CertificateInstanceEntity::getCreatorTime);
        List<CertificateInstanceEntity> list = certificateInstanceMapper.selectList(wrapper);
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }

    /**
     * 查询实例最新营业执照扩展记录。
     */
    private CertificateBusinessLicenseExtEntity queryLatestBusinessExt(String instanceId) {
        LambdaQueryWrapper<CertificateBusinessLicenseExtEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CertificateBusinessLicenseExtEntity::getEnabledMark, 0);
        wrapper.eq(CertificateBusinessLicenseExtEntity::getInstanceId, instanceId);
        wrapper.orderByDesc(CertificateBusinessLicenseExtEntity::getLastModifyTime);
        wrapper.orderByDesc(CertificateBusinessLicenseExtEntity::getCreatorTime);
        List<CertificateBusinessLicenseExtEntity> list = certificateBusinessLicenseExtMapper.selectList(wrapper);
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }

    /**
     * 保存或更新营业执照主表信息。
     */
    private String upsertBusinessInstance(String organizeId,
                                          String certificateType,
                                          String certificateImage,
                                          Date issueDate,
                                          Date expireDate,
                                          Integer isLongTerm,
                                          Integer status) {
        LambdaUpdateWrapper<CertificateInstanceEntity> updateWrapper = buildBusinessInstanceUpdateWrapper(
                organizeId, certificateType, certificateImage, issueDate, expireDate, isLongTerm, status
        );
        int updateRows = certificateInstanceMapper.update(null, updateWrapper);
        if (updateRows > 0) {
            CertificateInstanceEntity latest = queryLatestBusinessInstance(organizeId);
            ServiceException.notNull(latest, "营业执照实例更新成功但未查询到数据");
            return latest.getId();
        }

        CertificateInstanceEntity insertEntity = new CertificateInstanceEntity();
        insertEntity.setId(FtbUtil.getId());
        insertEntity.setCertificateType(certificateType);
        insertEntity.setSubjectType(SUBJECT_TYPE_ORGANIZE);
        insertEntity.setSubjectId(organizeId);
        insertEntity.setCertificateImage(certificateImage);
        insertEntity.setIssueDate(issueDate);
        insertEntity.setExpireDate(expireDate);
        if(Objects.nonNull(expireDate)){
            insertEntity.setExpireTimestamp(expireDate.getTime());
        }
        insertEntity.setIsLongTerm(isLongTerm);
        insertEntity.setStatus(status);
        insertEntity.setEnabledMark(0);
        try {
            certificateInstanceMapper.insert(insertEntity);
            return insertEntity.getId();
        } catch (DuplicateKeyException e) {
            log.warn("营业执照实例插入出现重复键，执行重试更新。organizeId={}, certificateType={}", organizeId, certificateType, e);
            LambdaUpdateWrapper<CertificateInstanceEntity> retryWrapper = buildBusinessInstanceUpdateWrapper(
                    organizeId, certificateType, certificateImage, issueDate, expireDate, isLongTerm, status
            );
            int retryRows = certificateInstanceMapper.update(null, retryWrapper);
            if(retryRows <= 0){
                log.error("upsertBusinessInstance fail.insertEntity:{}",insertEntity);
                return null;
            }
            CertificateInstanceEntity latest = queryLatestBusinessInstance(organizeId);
            ServiceException.notNull(latest, "营业执照实例重试更新成功但未查询到数据");
            return latest.getId();
        }
    }

    /**
     * 初始化单个门店默认证照记录。
     */
    private void initStoreDefaultCertificate(String storeId, String certificateType) {
        LambdaQueryWrapper<CertificateInstanceEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CertificateInstanceEntity::getEnabledMark, 0);
        queryWrapper.eq(CertificateInstanceEntity::getSubjectType, SUBJECT_TYPE_STORE);
        queryWrapper.eq(CertificateInstanceEntity::getSubjectId, storeId);
        queryWrapper.eq(CertificateInstanceEntity::getCertificateType, certificateType);
        queryWrapper.last("limit 1");
        CertificateInstanceEntity existed = certificateInstanceMapper.selectOne(queryWrapper);
        if (existed != null) {
            return;
        }

        CertificateInstanceEntity insertEntity = new CertificateInstanceEntity();
        insertEntity.setId(FtbUtil.getId());
        insertEntity.setCertificateType(certificateType);
        insertEntity.setSubjectType(SUBJECT_TYPE_STORE);
        insertEntity.setSubjectId(storeId);
        insertEntity.setIsLongTerm(IS_LONG_TERM_NO);
        insertEntity.setStatus(STATUS_MISSING);
        insertEntity.setEnabledMark(0);
        try {
            certificateInstanceMapper.insert(insertEntity);
        } catch (DuplicateKeyException e) {
            log.warn("初始化门店默认证照出现重复键，忽略。storeId={}, certificateType={}", storeId, certificateType, e);
        }
    }

    /**
     * 保存或更新营业执照扩展表信息。
     */
    private void upsertBusinessExt(String instanceId, CertificateOrganizeBusinessLicenseVO req, Date establishDate) {
        String companyName = trimToNull(req.getCompanyName());
        String companyAddress = trimToNull(req.getCompanyAddress());
        String legalRepresentative = trimToNull(req.getLegalRepresentative());

        LambdaUpdateWrapper<CertificateBusinessLicenseExtEntity> updateWrapper = buildBusinessExtUpdateWrapper(
                instanceId, companyName, companyAddress, legalRepresentative, establishDate
        );
        int updateRows = certificateBusinessLicenseExtMapper.update(null, updateWrapper);
        if (updateRows > 0) {
            return;
        }

        CertificateBusinessLicenseExtEntity insertEntity = new CertificateBusinessLicenseExtEntity();
        insertEntity.setId(FtbUtil.getId());
        insertEntity.setInstanceId(instanceId);
        insertEntity.setCompanyName(companyName);
        insertEntity.setCompanyAddress(companyAddress);
        insertEntity.setLegalRepresentative(legalRepresentative);
        insertEntity.setEstablishDate(establishDate);
        insertEntity.setEnabledMark(0);
        try {
            certificateBusinessLicenseExtMapper.insert(insertEntity);
        } catch (DuplicateKeyException e) {
            log.warn("营业执照扩展插入出现重复键，执行重试更新。instanceId={}", instanceId, e);
            LambdaUpdateWrapper<CertificateBusinessLicenseExtEntity> retryWrapper = buildBusinessExtUpdateWrapper(
                    instanceId, companyName, companyAddress, legalRepresentative, establishDate
            );
            int retryRows = certificateBusinessLicenseExtMapper.update(null, retryWrapper);
            ServiceException.isTrue(retryRows > 0, "营业执照扩展保存失败，请稍后重试");
        }
    }

    /**
     * 组装营业执照返回对象。
     */
    private CertificateOrganizeBusinessLicenseVO convertToVO(String organizeId,
                                                             CertificateInstanceEntity instance,
                                                             CertificateBusinessLicenseExtEntity ext) {
        CertificateOrganizeBusinessLicenseVO vo = new CertificateOrganizeBusinessLicenseVO();
        vo.setOrganizeId(organizeId);
        vo.setIsLongTerm(instance == null || instance.getIsLongTerm() == null ? 0 : instance.getIsLongTerm());
        if (instance != null) {
            vo.setCertificateImage(instance.getCertificateImage());
            vo.setIssueDate(formatDate(instance.getIssueDate()));
            vo.setExpireDate(formatDate(instance.getExpireDate()));
            vo.setBusinessTerm(buildBusinessTerm(instance.getIssueDate(), instance.getExpireDate(), vo.getIsLongTerm()));
        } else {
            vo.setBusinessTerm("[]");
        }
        if (ext != null) {
            vo.setCompanyName(ext.getCompanyName());
            vo.setLegalRepresentative(ext.getLegalRepresentative());
            vo.setCompanyAddress(ext.getCompanyAddress());
            vo.setEstablishDate(formatDate(ext.getEstablishDate()));
        }
        return vo;
    }

    /**
     * 计算证照状态。
     */
    private Integer calculateStatus(Integer isLongTerm, Date expireDate) {
        if (Integer.valueOf(1).equals(isLongTerm)) {
            return STATUS_NORMAL;
        }
        if (expireDate == null) {
            return STATUS_MISSING;
        }
        Date today = DateUtil.beginOfDay(DateUtil.date());
        Date target = DateUtil.beginOfDay(expireDate);
        if (target.before(today)) {
            return STATUS_EXPIRED;
        }
        long daysDiff = DateUtil.betweenDay(today, target, false);
        if (daysDiff <= NEAR_EXPIRE_DAYS) {
            return STATUS_NEAR_EXPIRE;
        }
        return STATUS_NORMAL;
    }

    /**
     * 解析日期字符串。
     */
    private Date parseDate(String dateText, String fieldName) {
        if (StrUtil.isBlank(dateText)) {
            return null;
        }
        int strLen = dateText.length();
        if(StringUtil.isNumeric(dateText) && (strLen == 10 || strLen == 13)){
            long date = Long.parseLong(dateText);
            if(dateText.length() == 10){
                date = date * 1000;
            }
            return new Date(date);
        }
        try {
            return DateUtil.parseDate(StrUtil.trim(dateText));
        } catch (Exception e) {
            throw new ServiceException(fieldName + "格式不正确，正确格式为yyyy-MM-dd");
        }
    }

    /**
     * 格式化日期。
     */
    private String formatDate(Date date) {
        return date == null ? null : DateUtil.formatDate(date);
    }

    /**
     * 组装营业期限展示文案。
     */
    private String buildBusinessTerm(Date issueDate, Date expireDate, Integer isLongTerm) {
        if (Integer.valueOf(1).equals(isLongTerm)) {
            return "[]";
        }
        if (expireDate == null) {
            return "[]";
        }
        String issueText = issueDate == null ? "" : DateUtil.formatDate(issueDate);
        return "[\""+issueText + "\",\"" + DateUtil.formatDate(expireDate)+"\"]";
    }

    /**
     * 构建营业执照主表更新条件。
     */
    private LambdaUpdateWrapper<CertificateInstanceEntity> buildBusinessInstanceUpdateWrapper(String organizeId,
                                                                                               String certificateType,
                                                                                               String certificateImage,
                                                                                               Date issueDate,
                                                                                               Date expireDate,
                                                                                               Integer isLongTerm,
                                                                                               Integer status) {
        LambdaUpdateWrapper<CertificateInstanceEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(CertificateInstanceEntity::getSubjectId, organizeId);
        updateWrapper.eq(CertificateInstanceEntity::getCertificateType, certificateType);
        updateWrapper.set(CertificateInstanceEntity::getSubjectType, SUBJECT_TYPE_ORGANIZE);
        updateWrapper.set(CertificateInstanceEntity::getEnabledMark, 0);
        updateWrapper.set(CertificateInstanceEntity::getCertificateImage, certificateImage);
        updateWrapper.set(CertificateInstanceEntity::getIssueDate, issueDate);
        updateWrapper.set(CertificateInstanceEntity::getExpireDate, expireDate);
        if(Objects.nonNull(expireDate)){
            updateWrapper.set(CertificateInstanceEntity::getExpireTimestamp, expireDate.getTime());
        }
        updateWrapper.set(CertificateInstanceEntity::getIsLongTerm, isLongTerm);
        updateWrapper.set(CertificateInstanceEntity::getStatus, status);
        return updateWrapper;
    }

    /**
     * 构建营业执照扩展表更新条件。
     */
    private LambdaUpdateWrapper<CertificateBusinessLicenseExtEntity> buildBusinessExtUpdateWrapper(String instanceId,
                                                                                                    String companyName,
                                                                                                    String companyAddress,
                                                                                                    String legalRepresentative,
                                                                                                    Date establishDate) {
        LambdaUpdateWrapper<CertificateBusinessLicenseExtEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(CertificateBusinessLicenseExtEntity::getEnabledMark, 0);
        updateWrapper.eq(CertificateBusinessLicenseExtEntity::getInstanceId, instanceId);
        updateWrapper.set(CertificateBusinessLicenseExtEntity::getCompanyName, companyName);
        updateWrapper.set(CertificateBusinessLicenseExtEntity::getCompanyAddress, companyAddress);
        updateWrapper.set(CertificateBusinessLicenseExtEntity::getLegalRepresentative, legalRepresentative);
        updateWrapper.set(CertificateBusinessLicenseExtEntity::getEstablishDate, establishDate);
        return updateWrapper;
    }

    /**
     * 去首尾空格，空串返回 null。
     */
    private String trimToNull(String text) {
        String value = StrUtil.trim(text);
        return StrUtil.isBlank(value) ? null : value;
    }
}
