/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.rechargerecord.service.impl;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.api.SaBaseLoginUserApi;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.core.utils.WxUtil;
import vip.xiaonuo.biz.modular.rechargeplanconfig.entity.BizRechargePlanConfig;
import vip.xiaonuo.biz.modular.rechargeplanconfig.mapper.BizRechargePlanConfigMapper;
import vip.xiaonuo.biz.modular.rechargerecord.param.*;
import vip.xiaonuo.biz.modular.recommendrecord.service.BizRecommendRecordService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.rechargerecord.entity.BizRechargeRecord;
import vip.xiaonuo.biz.modular.rechargerecord.mapper.BizRechargeRecordMapper;
import vip.xiaonuo.biz.modular.rechargerecord.service.BizRechargeRecordService;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.CommonWxUtil;
import vip.xiaonuo.common.wx.WxPayConfig;
import vip.xiaonuo.dev.api.DevConfigApi;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 充值记录表Service接口实现类
 *
 * @author wulei
 * @date 2025/02/06 17:41
 **/
@Service
@Slf4j
public class BizRechargeRecordServiceImpl extends ServiceImpl<BizRechargeRecordMapper, BizRechargeRecord> implements BizRechargeRecordService {

    @Resource
    private CommonWxUtil commonWxUtil;
    @Resource
    private WxPayConfig wxPayConfig;
    @Resource
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;
    @Resource
    private BizRechargePlanConfigMapper bizRechargePlanConfigMapper;
    @Resource
    private BizUserMapper bizUserMapper;
    @Resource
    private BizRecommendRecordService bizRecommendRecordService;
    @Resource(name = "loginUserApi")
    private SaBaseLoginUserApi loginUserApi;
    @Resource
    private DevConfigApi devConfigApi;



    @Override
    public Page<BizRechargeRecord> page(BizRechargeRecordPageParam bizRechargeRecordPageParam) {
        QueryWrapper<BizRechargeRecord> queryWrapper = new QueryWrapper<BizRechargeRecord>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getSearchKey())) {
            queryWrapper.and(s -> s.like("u.ACCOUNT", bizRechargeRecordPageParam.getSearchKey())
                    .or().like("u.NAME", bizRechargeRecordPageParam.getSearchKey()));
        }
        if (ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getStartRechargeTime()) && ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getEndRechargeTime())) {
            queryWrapper.between("t.recharge_time", bizRechargeRecordPageParam.getStartRechargeTime(), bizRechargeRecordPageParam.getEndRechargeTime());
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isEmpty(loginUserDataScope)) {
            queryWrapper.in("t.user_id", StpLoginUserUtil.getLoginUser().getId());
        }
        queryWrapper.orderByDesc("t.recharge_time");
        queryWrapper.eq("t.delete_flag", CommonDeleteFlagEnum.NOT_DELETE);
        Page<BizRechargeRecord> pageList = baseMapper.pageList(CommonPageRequest.defaultPage(), queryWrapper);
        pageList.getRecords().forEach(bizRechargeRecord -> {
            if (ObjectUtil.isNotEmpty(bizRechargeRecord.getPhone())) {
                bizRechargeRecord.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(bizRechargeRecord.getPhone()));
            }
        });
        return pageList;
    }

    @Override
    public Page<BizRechargeRecord> userPage(BizRechargeRecordPageParam bizRechargeRecordPageParam) {
        QueryWrapper<BizRechargeRecord> queryWrapper = new QueryWrapper<BizRechargeRecord>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getStartRechargeTime()) && ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getEndRechargeTime())) {
            queryWrapper.lambda().between(BizRechargeRecord::getRechargeTime, bizRechargeRecordPageParam.getStartRechargeTime(), bizRechargeRecordPageParam.getEndRechargeTime());
        }
        if (ObjectUtil.isNotEmpty(bizRechargeRecordPageParam.getIsPay())){
            queryWrapper.lambda().eq(BizRechargeRecord::getIsPay,bizRechargeRecordPageParam.getIsPay());
        }
        queryWrapper.lambda().eq(BizRechargeRecord::getUserId, StpLoginUserUtil.getLoginUser().getId());
        queryWrapper.lambda().orderByDesc(BizRechargeRecord::getRechargeTime);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized Map<String, Object> add(BizRechargeRecordAddParam bizRechargeRecordAddParam) {
        Map<String, Object> resultMap = new HashMap<>(5);
        BizRechargeRecord bizRechargeRecord = new BizRechargeRecord();
        //充值金额不能为0
        if (bizRechargeRecordAddParam.getRechargeAmount().compareTo(BigDecimal.ZERO) == 0) {
            throw new CommonException("充值金额不能为0");
        }
        // 查询用户信息
        BizUser bizUser = bizUserMapper.selectById(StpLoginUserUtil.getLoginUser().getId());
        if (ObjectUtil.isNull(bizUser)) {
            throw new CommonException("未查询到该用户信息");
        }
        if (StringUtils.equals(bizUser.getUserStatus(),"DISABLED")){
            throw new CommonException("用户账号冻结，不可充值！");
        }
        if (ObjectUtil.isNotEmpty(bizRechargeRecordAddParam.getRechargePlanId())) {
            // 校验充值方案
            BizRechargePlanConfig bizRechargePlanConfig = bizRechargePlanConfigMapper.selectById(bizRechargeRecordAddParam.getRechargePlanId());
            if (ObjectUtil.isNull(bizRechargePlanConfig)) {
                throw new CommonException("未查询到该充值方案");
            }
            if (bizRechargeRecordAddParam.getRechargeAmount().compareTo(bizRechargePlanConfig.getRechargeAmount()) < 0) {
                throw new CommonException("当前充值金额不符合该优惠方案");
            }
            //拼接方案内容
            StringBuffer content = new StringBuffer();
            content.append("充值方案：").append(bizRechargePlanConfig.getRechargeAmount()).append("元及以上，");
            if (bizRechargePlanConfig.getCouponAmount().compareTo(BigDecimal.ZERO) != 0) {
                content.append("赠送"+bizRechargePlanConfig.getCouponAmount()+"寸蛋糕券 ")
                        .append(" x ").append(bizRechargePlanConfig.getCouponNum())
                        .append("（线下核销领蛋糕）");
            }
            if(StringUtils.equals(bizRechargePlanConfig.getIsAccount(),"1")){
                content.append("，账户余额到账").append(bizRechargePlanConfig.getAccountBalance())
                        .append("元，返利").append(bizRechargePlanConfig.getRebateRatio())
                        .append("%到推荐人代金券");
            }else{
                content.append("，账户余额到账").append(bizRechargePlanConfig.getAccountBalance())
                        .append("元(待激活)，返利").append(bizRechargePlanConfig.getRebateRatio())
                        .append("%到推荐人代金券");
            }

            bizRechargeRecord.setRechargePlanDescribe(content.toString());
            bizRechargeRecord.setRechargePlanId(bizRechargeRecordAddParam.getRechargePlanId());
            bizRechargeRecord.setPlanAccountBalance(bizRechargePlanConfig.getAccountBalance());
            bizRechargeRecord.setCouponAmount(bizRechargePlanConfig.getCouponAmount());
            bizRechargeRecord.setCouponNum(bizRechargePlanConfig.getCouponNum());

            //计算返点金额
            bizRechargeRecord = getBizRechargeRecord(bizUser,bizRechargeRecord,bizRechargeRecordAddParam);
        }else{
            //计算返点金额
            bizRechargeRecord = getBizRechargeRecord(bizUser,bizRechargeRecord,bizRechargeRecordAddParam);
        }
        String openId = commonWxUtil.getOpenId(bizRechargeRecordAddParam.getCode(), wxPayConfig.getGetOpenIdUrl(), wxPayConfig.getAppId(), wxPayConfig.getAppSecret());
        if (ObjectUtil.isEmpty(openId)) {
            throw new CommonException("openId获取异常，请联系管理员");
        }
        log.info("================ 生成基础充值记录内容 =============");
        bizRechargeRecord.setRechargeAmount(bizRechargeRecordAddParam.getRechargeAmount());
        // 本系统订单号
        String orderNumber = "BBT" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN) + RandomUtil.randomNumbers(3);
        bizRechargeRecord.setOrderNo(orderNumber);
        bizRechargeRecord.setRechargeTime(DateUtil.date());
        bizRechargeRecord.setUserId(bizUser.getId());
        this.save(bizRechargeRecord);
        //转换金额为分
        Integer totalFee = bizRechargeRecordAddParam.getRechargeAmount().multiply(new BigDecimal("100")).intValue();

        //请求微信支付相关配置
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(rsaAutoCertificateConfig)
                        .signType("RSA") // 不填默认为RSA
                        .build();
        PrepayWithRequestPaymentResponse response;
        try {
            PrepayRequest request = new PrepayRequest();
            request.setAppid(wxPayConfig.getAppId());
            request.setMchid(wxPayConfig.getMerchantId());
            request.setDescription("爸爸糖手工吐司会员账户充值");
            request.setOutTradeNo(orderNumber);
            request.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
            Amount amount = new Amount();
            amount.setTotal(totalFee);
            request.setAmount(amount);
            Payer payer = new Payer();
            payer.setOpenid(openId);
            request.setPayer(payer);
            log.info("请求生成订单，请求参数：{}", JSONObject.toJSONString(request));
            // 调用预下单接口
            response = service.prepayWithRequestPayment(request);
            resultMap.put("package", response.getPackageVal());
            resultMap.put("nonceStr", response.getNonceStr());
            resultMap.put("signType", response.getSignType());
            resultMap.put("timeStamp", response.getTimeStamp());
            resultMap.put("paySign", response.getPaySign());
            resultMap.put("dataId", bizRechargeRecord.getId());
            log.info("订单【{}】生成订单成功，返回信息：{}", orderNumber, response);
        } catch (HttpException e) {
            // 发送HTTP请求失败
            log.error("微信下单发送HTTP请求失败，错误信息：{}", e.getMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        } catch (ServiceException e) {
            // 服务返回状态小于200或大于等于300，例如500
            log.error("微信下单服务状态错误，错误信息：{}", e.getErrorMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        } catch (MalformedMessageException e) {
            // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        }
        //3. 返回微信订单参数，方便小程序唤起支付
        return resultMap;
    }

    public BizRechargeRecord getBizRechargeRecord(BizUser bizUser,BizRechargeRecord bizRechargeRecord,BizRechargeRecordAddParam bizRechargeRecordAddParam){
        if (ObjectUtil.isNotEmpty(bizUser.getReferralUser())) {
            //查询推荐人信息
            List<cn.hutool.json.JSONObject> roleList = loginUserApi.getRoleListByUserId(bizUser.getReferralUser());
            List<String> roleCodeList = roleList.stream().map(jsonObject -> jsonObject.getStr("code")).collect(Collectors.toList());
            log.info("推荐人角色编码集合:"+roleCodeList);
            if(ObjectUtil.isNotEmpty(roleCodeList)){
                if(StringUtils.equals(roleCodeList.get(0),"YK8PsRXAdf")){
                    //店员角色
                    //查询当日推荐人推荐人数
                    BigDecimal rebate = new BigDecimal(devConfigApi.getValueByKey("SNOWY_REBATE_RATIO")).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                    BigDecimal rebateAmount = bizRechargeRecordAddParam.getRechargeAmount().multiply(rebate);
                    bizRechargeRecord.setRebateAmount(rebateAmount);
                    bizRechargeRecord.setRebateRatio(new BigDecimal(devConfigApi.getValueByKey("SNOWY_REBATE_RATIO")));
                }else if(StringUtils.equals(roleCodeList.get(0),"vVA3owyWwx")){
                    //用户角色
                    BigDecimal rebate = new BigDecimal(devConfigApi.getValueByKey("SNOWY_USER_REBATE_RATIO")).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                    BigDecimal rebateAmount = bizRechargeRecordAddParam.getRechargeAmount().multiply(rebate);
                    bizRechargeRecord.setRebateAmount(rebateAmount);
                    bizRechargeRecord.setRebateRatio(new BigDecimal(devConfigApi.getValueByKey("SNOWY_USER_REBATE_RATIO")));
                }else{
                    BigDecimal rebate = new BigDecimal(devConfigApi.getValueByKey("SNOWY_REBATE_RATIO")).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                    BigDecimal rebateAmount = bizRechargeRecordAddParam.getRechargeAmount().multiply(rebate);
                    bizRechargeRecord.setRebateAmount(rebateAmount);
                    bizRechargeRecord.setRebateRatio(new BigDecimal(devConfigApi.getValueByKey("SNOWY_REBATE_RATIO")));
                }
            }
        }
        return bizRechargeRecord;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> retryPayment(BizRechargePay bizRechargePay) {
        Map<String, Object> resultMap = new HashMap<>(5);
        //转换金额为分
        Integer totalFee = bizRechargePay.getRechargeAmount().multiply(new BigDecimal("100")).intValue();

        BizRechargeRecord rechargeRecord = this.getById(bizRechargePay.getRechargeId());
        // 本系统订单号
        String orderNumber = "BBT" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN) + RandomUtil.randomNumbers(3);
        rechargeRecord.setOrderNo(orderNumber);
        this.updateById(rechargeRecord);

        BizUser bizUser = bizUserMapper.selectById(StpLoginUserUtil.getLoginUser().getId());
        String openId = bizUser.getOpenId();

        //请求微信支付相关配置
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(rsaAutoCertificateConfig)
                        .signType("RSA") // 不填默认为RSA
                        .build();
        PrepayWithRequestPaymentResponse response;
        try {
            PrepayRequest request = new PrepayRequest();
            request.setAppid(wxPayConfig.getAppId());
            request.setMchid(wxPayConfig.getMerchantId());
            request.setDescription("爸爸糖手工吐司会员账户充值");
            request.setOutTradeNo(orderNumber);
            request.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
            Amount amount = new Amount();
            amount.setTotal(totalFee);
            request.setAmount(amount);
            Payer payer = new Payer();
            payer.setOpenid(openId);
            request.setPayer(payer);
            log.info("请求生成订单，请求参数：{}", JSONObject.toJSONString(request));
            // 调用预下单接口
            response = service.prepayWithRequestPayment(request);
            resultMap.put("package", response.getPackageVal());
            resultMap.put("nonceStr", response.getNonceStr());
            resultMap.put("signType", response.getSignType());
            resultMap.put("timeStamp", response.getTimeStamp());
            resultMap.put("paySign", response.getPaySign());
            resultMap.put("dataId", rechargeRecord.getId());
            log.info("订单【{}】生成订单成功，返回信息：{}", orderNumber, response);
        } catch (HttpException e) {
            // 发送HTTP请求失败
            log.error("微信下单发送HTTP请求失败，错误信息：{}", e.getMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        } catch (ServiceException e) {
            // 服务返回状态小于200或大于等于300，例如500
            log.error("微信下单服务状态错误，错误信息：{}", e.getErrorMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        } catch (MalformedMessageException e) {
            // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
            throw new CommonException("微信下单失败，请联系管理员");
        }
        //3. 返回微信订单参数，方便小程序唤起支付
        return resultMap;
    }

//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void edit(BizRechargeRecordEditParam bizRechargeRecordEditParam) {
//        BizRechargeRecord bizRechargeRecord = this.queryEntity(bizRechargeRecordEditParam.getId());
//        BeanUtil.copyProperties(bizRechargeRecordEditParam, bizRechargeRecord);
//        this.updateById(bizRechargeRecord);
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizRechargeRecordIdParam> bizRechargeRecordIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizRechargeRecordIdParamList, BizRechargeRecordIdParam::getId));
    }

    @Override
    public BizRechargeRecord detail(BizRechargeRecordIdParam bizRechargeRecordIdParam) {
        return this.queryEntity(bizRechargeRecordIdParam.getId());
    }

    @Override
    public BizRechargeRecord queryEntity(String id) {
        BizRechargeRecord bizRechargeRecord = this.getById(id);
        if (ObjectUtil.isEmpty(bizRechargeRecord)) {
            throw new CommonException("充值记录表不存在，id值为：{}", id);
        }
        return bizRechargeRecord;
    }

    //取消订单
    @Override
    public void cancelOrder(BizRechargeRecordIdParam bizRechargeRecordIdParam) {
        BizRechargeRecord bizRechargeRecord = this.queryEntity(bizRechargeRecordIdParam.getId());
        bizRechargeRecord.setIsPay("2");
        this.updateById(bizRechargeRecord);
    }

    public String returnBase(){
        CommonWxUtil util = new CommonWxUtil();
        try {
            String accessToken = util.getAccessToken();
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            JSONObject paramJson = new JSONObject();
            paramJson.put("page", "pages/register/index");
            paramJson.put("scene", "8JFFG95PD0");
            paramJson.put("check_path", false);
            paramJson.put("env_version","trial");
            paramJson.put("width", 280);

            try {
                File localFile = new File("D:/defaultUploadFolder/recommend");
                if(!localFile.exists()) {
                    localFile.mkdir();
                }

                String localPath = "D:/defaultUploadFolder/recommend/" + 1 + ".png";
                InputStream inputStream = WxUtil.postInputStream(url, paramJson);
                int index;
                byte[] bytes = new byte[1024];
                FileOutputStream downloadFile = new FileOutputStream(localPath);
                while ((index = inputStream.read(bytes)) != -1) {
                    downloadFile.write(bytes, 0, index);
                    downloadFile.flush();
                }
                File file = new File(localPath);
                String base = "data:image/png;base64,"+Base64.encode(file);
                System.out.printf("base:"+base);
                downloadFile.close();
                inputStream.close();
                return base;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static void main(String[] args) {
        CommonWxUtil util = new CommonWxUtil();
        try {
            String accessToken = util.getAccessToken();
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            JSONObject paramJson = new JSONObject();
            paramJson.put("page", "pages/register/index");
            paramJson.put("scene", "8JFFG95PD0");
            paramJson.put("check_path", false);
            paramJson.put("env_version","trial");
            paramJson.put("width", 280);

            try {
                File localFile = new File("D:/defaultUploadFolder/recommend");
                if(!localFile.exists()) {
                    localFile.mkdir();
                }

                String localPath = "D:/defaultUploadFolder/recommend/" + 1 + ".png";
                InputStream inputStream = WxUtil.postInputStream(url, paramJson);
                int index;
                byte[] bytes = new byte[1024];
                FileOutputStream downloadFile = new FileOutputStream(localPath);
                while ((index = inputStream.read(bytes)) != -1) {
                    downloadFile.write(bytes, 0, index);
                    downloadFile.flush();
                }
                File file = new File(localPath);
                String base = "data:image/png;base64,"+Base64.encode(file);
                System.out.printf("base:"+base);
                downloadFile.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveImageToFile(byte[] imageData, String filePath) throws IOException {
        Files.write(Paths.get(filePath), imageData);
        System.out.println("图片已保存至: " + filePath);
    }
}
