package com.ruoyi.web.modules.industrypolicy.support;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industrypolicy.domain.BizSubsidyGrantRecord;

/**
 * 补贴发放记录敏感字段脱敏。
 */
public final class SubsidyGrantRecordMasking
{
    private SubsidyGrantRecordMasking()
    {
    }

    /** 是否为脱敏占位值（含 * / 全角＊ 等），不可直接用于保存校验 */
    public static boolean isMaskedValue(String value)
    {
        if (StringUtils.isEmpty(value))
        {
            return false;
        }
        for (int i = 0; i < value.length(); i++)
        {
            char c = value.charAt(i);
            if (c == '*' || c == '＊' || c == '●' || c == '•')
            {
                return true;
            }
        }
        return false;
    }

    /** 提交值是否与库内明文脱敏后一致（编辑未改敏感字段） */
    public static boolean equalsMasked(String plain, String incoming)
    {
        if (StringUtils.isEmpty(plain) || StringUtils.isEmpty(incoming))
        {
            return false;
        }
        return plain.equals(incoming) || maskIdCard(plain).equals(incoming);
    }

    public static String maskIdCard(String idCard)
    {
        if (StringUtils.isEmpty(idCard) || idCard.length() < 8)
        {
            return idCard;
        }
        int len = idCard.length();
        StringBuilder sb = new StringBuilder(len);
        sb.append(idCard, 0, 4);
        for (int i = 4; i < len - 4; i++)
        {
            sb.append('*');
        }
        sb.append(idCard.substring(len - 4));
        return sb.toString();
    }

    public static String maskPhone(String phone)
    {
        if (StringUtils.isEmpty(phone) || phone.length() < 7)
        {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
    }

    public static String maskBankAccount(String bankAccount)
    {
        if (StringUtils.isEmpty(bankAccount) || bankAccount.length() < 4)
        {
            return bankAccount;
        }
        int len = bankAccount.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len - 4; i++)
        {
            sb.append('*');
        }
        sb.append(bankAccount.substring(len - 4));
        return sb.toString();
    }

    public static BizSubsidyGrantRecord applySensitiveMask(BizSubsidyGrantRecord row, boolean showFull)
    {
        if (row == null || showFull)
        {
            return row;
        }
        row.setIdCard(maskIdCard(row.getIdCard()));
        row.setContactPhone(maskPhone(row.getContactPhone()));
        row.setBankAccount(maskBankAccount(row.getBankAccount()));
        return row;
    }
}
