package com.m2pool.lease.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.redis.service.RedisService;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.lease.constant.Algorithm;
import com.m2pool.lease.constant.BlockInterval;
import com.m2pool.lease.constant.PowerUnit;
import com.m2pool.lease.redis.RedisCoinInfoKey;
import com.m2pool.lease.dto.*;
import com.m2pool.lease.entity.*;
import com.m2pool.lease.exception.ProductSoldOutException;
import com.m2pool.lease.mapper.*;
import com.m2pool.lease.service.LeaseProductMachinePriceService;
import com.m2pool.lease.service.LeaseProductService;
import com.m2pool.lease.service.LeaseShopConfigService;
import com.m2pool.lease.utils.PowerUnitUtils;
import com.m2pool.lease.utils.QrCodeUtils;
import com.m2pool.lease.utils.WalletRuleCheckUtils;
import com.m2pool.lease.vo.BaseVo;
import com.m2pool.lease.vo.ProductMachineVo;
import com.m2pool.lease.vo.ProductPageVo;
import com.m2pool.lease.vo.ProductURDVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author yyb
 * @since 2025-07-23
 */
@Service
public class LeaseProductServiceImpl extends ServiceImpl<LeaseProductMapper, LeaseProduct> implements LeaseProductService {


    @Resource
    private LeaseProductMachineMapper leaseProductMachineMapper;

    @Resource
    private LeaseProductMapper leaseProductMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private LeaseShopMapper leaseShopMapper;

    @Resource
    private LeaseShopConfigMapper leaseShopConfigMapper;

    @Resource
    private LeaseProductMachinePriceService leaseProductMachinePriceService;
    @Resource
    private LeaseShopConfigService leaseShopConfigService;

    @Resource
    private LeaseProductMachinePriceMapper leaseProductMachinePriceMapper;


    @Override
    public PageResult<ProductDto> getProductList(ProductPageVo productPageVo) {
        Long shopId = 0L;
        System.out.println("用户邮箱参数:"+productPageVo.getUserEmail());
        //1.用户邮箱参数不为空,则表示个人中心的商品列表。这个时候能看到下架的商品
        if (!StringUtils.isEmpty(productPageVo.getUserEmail())){
            LeaseShop leaseShop = leaseShopMapper.selectOne(new LambdaQueryWrapper<LeaseShop>()
                    .eq(LeaseShop::getUserEmail, productPageVo.getUserEmail()));
            if (leaseShop != null){
                shopId = leaseShop.getId();
            }else{
                return PageResult.fail(new ArrayList<>(), "不存在出售商品");
            }
        }
        PageHelper.startPage(productPageVo.getPageNum(), productPageVo.getPageSize());
        List<ProductDto> leaseProducts = leaseProductMapper.getProductListForShopAndUserCenter(productPageVo.getCoin(), productPageVo.getAlgorithm(), shopId);
        PageInfo<ProductDto> pageInfo = new PageInfo<>(leaseProducts);
        if(leaseProducts.isEmpty()){
            return PageResult.fail(new ArrayList<>(), "不存在出售商品");
        }
        //获取店铺对应的支付方式
        List<Long> shopIds = leaseProducts.stream().map(ProductDto::getShopId).distinct().collect(Collectors.toList());
        List<PayTypeDto> payType = leaseShopConfigMapper.getPayType(shopIds);
        Map<Long, List<PayTypeDto>> payTypeMap = payType.stream().collect(Collectors.groupingBy(PayTypeDto::getShopId));
        //配置支付列表
        for (ProductDto productDto : leaseProducts) {
            productDto.setPayTypes(payTypeMap.get(productDto.getShopId()));
        }

        PageResult<ProductDto> success = PageResult.success(leaseProducts);
        success.setTotal(pageInfo.getTotal());
        success.setTotalPage(pageInfo.getPages());
        PageHelper.clearPage();
        return success;
    }


    @Override
    public Result<ProductDto> getMachineInfoById(BaseVo baseVo) {
        LeaseProduct leaseProduct = leaseProductMapper.selectById(baseVo.getId());
        if (leaseProduct == null) {
            return Result.fail("商品不存在");
        }

       String priceRange = leaseProduct.getMinPrice().equals(leaseProduct.getMaxPrice()) ? leaseProduct.getMinPrice().toString(): leaseProduct.getMinPrice() +"-"+leaseProduct.getMaxPrice();
        ProductDto productDto = ProductDto.builder()
                .id(leaseProduct.getId())
                .shopId(leaseProduct.getShopId())
                .name(leaseProduct.getName())
                .image(leaseProduct.getImage())
                .type(leaseProduct.getType())
                .state(leaseProduct.getState())
                .priceRange(priceRange)
                .description(leaseProduct.getDescription())
                .coin(leaseProduct.getCoin())
                .algorithm(leaseProduct.getAlgorithm())
                .build();
        return Result.success(productDto);
    }

    @Override
    public PageResult<ProductMachineDto> getProductMachineInfo(ProductMachineVo productMachineVo) {
        Long productId = productMachineVo.getId();
        LeaseProduct product = getById(productId);
        List<PayConfigDto> shopWalletInfo = leaseShopMapper.getShopWalletInfo(product.getShopId());
        PageHelper.startPage(productMachineVo.getPageNum(), productMachineVo.getPageSize());
        productMachineVo =  buildQuery(productMachineVo,shopWalletInfo.get(0));
        List<ProductMachineDto> productMachineDtoList = leaseProductMachineMapper.getMachinesByPriceAndPowerAndDissipation(productMachineVo, product.getCoin());
        PageInfo<ProductMachineDto> pageInfo = new PageInfo<>(productMachineDtoList);

        if (productMachineDtoList.isEmpty()){
            return PageResult.fail(new ArrayList<>(),"不存在矿机");
        }
        //币价 单位usdt
        BigDecimal price = redisService.getCacheBigDecimal(RedisCoinInfoKey.getPiceKey(product.getCoin())) == null ? BigDecimal.ZERO : redisService.getCacheBigDecimal(RedisCoinInfoKey.getPiceKey(product.getCoin()));
        //报块奖励
        BigDecimal reward =redisService.getCacheBigDecimal(RedisCoinInfoKey.getRewardKey(product.getCoin())) == null ? BigDecimal.ZERO : redisService.getCacheBigDecimal(RedisCoinInfoKey.getRewardKey(product.getCoin())) ;
        //全网算力单位是MH/s
        BigDecimal mhs = redisService.getCacheBigDecimal(RedisCoinInfoKey.getMhsKey(product.getCoin())) == null ? BigDecimal.ZERO : redisService.getCacheBigDecimal(RedisCoinInfoKey.getMhsKey(product.getCoin()));

        List<ProductMachineDto> productMachines = productMachineDtoList.stream()
                .peek(productMachineDto -> {
                    //理论收益
                    BigDecimal singleTheoryMachineIncome = BigDecimal.ZERO;
                    productMachineDto.setAlgorithm(product.getAlgorithm());
                    // 矿机算力单位转换 + 计算单矿机平均算力(ComputingPower coin_real_power 24小时总算力)
                    BigDecimal computingPower  = PowerUnitUtils.getPower(productMachineDto.getUnit(), productMachineDto.getComputingPower()
                            .multiply(BigDecimal.valueOf(1000 * 1000)));
                    //全网算力单位转换
                    BigDecimal power = PowerUnitUtils.getPower(productMachineDto.getUnit(), mhs.multiply(BigDecimal.valueOf(1000 * 1000)));
                    //（理论收益 = 矿机算力/全网算力 * 24h /出块间隔秒数 * 单块奖励（redis中nexa:reward））
                    singleTheoryMachineIncome = computingPower.divide( power,6, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.valueOf(24 * 60 * 60)
                                    .divide(BlockInterval.getBlockCountByCoinName(product.getCoin()), 6, RoundingMode.HALF_UP))
                            .multiply(reward);
                    productMachineDto.setComputingPower(computingPower);
                    productMachineDto.setTheoryIncome(singleTheoryMachineIncome);
                    productMachineDto.setTheoryUsdtIncome(singleTheoryMachineIncome.multiply(price));

                })
                .collect(Collectors.toList());
        //分页内排序
        productMachines = sorted(productMachines,productMachineVo);
        PageResult<ProductMachineDto> success = PageResult.success(productMachines);
        success.setTotal(pageInfo.getTotal());
        success.setTotalPage(pageInfo.getPages());
        PageHelper.clearPage();
        return success;
    }

    /**
     * 构建查询条件
     * @param productMachineVo
     * @param payConfigDto
     * @return
     */
    public ProductMachineVo buildQuery(ProductMachineVo productMachineVo,PayConfigDto payConfigDto){
        if (StringUtils.isEmpty(productMachineVo.getChain()) && StringUtils.isEmpty(productMachineVo.getCoin())){
            productMachineVo.setChain(payConfigDto.getPayChain());
            productMachineVo.setCoin(payConfigDto.getPayCoin());
        }
        BigDecimal power = PowerUnit.getPower(productMachineVo.getUnit()).divide(BigDecimal.valueOf(1000 * 1000),2,RoundingMode.HALF_UP);
        productMachineVo.setMaxPower(productMachineVo.getMaxPower().multiply(power));
        productMachineVo.setMinPower(productMachineVo.getMinPower().multiply(power));
        //算力设置
        if (productMachineVo.getMaxPower().compareTo(productMachineVo.getMinPower()) < 0){
            productMachineVo.setMaxPower(productMachineVo.getMinPower());
            productMachineVo.setMinPower(productMachineVo.getMaxPower());
        }
        //功耗设置
        if (productMachineVo.getMaxPowerDissipation().compareTo(productMachineVo.getMinPowerDissipation()) < 0){
            productMachineVo.setMaxPowerDissipation(productMachineVo.getMinPowerDissipation());
            productMachineVo.setMinPowerDissipation(productMachineVo.getMaxPowerDissipation());
        }
        //价格设置
        if (productMachineVo.getMaxPrice().compareTo(productMachineVo.getMinPrice()) < 0){

            productMachineVo.setMaxPrice(productMachineVo.getMinPrice());
            productMachineVo.setMinPrice(productMachineVo.getMaxPrice());
        }
        System.out.println("请求参数"+ JSONUtil.toJsonPrettyStr(productMachineVo));
        return productMachineVo;
    }

    public List<ProductMachineDto> sorted(List<ProductMachineDto> productMachineDtoList,ProductMachineVo productMachineVo){

        if (productMachineVo.getPriceSort() != null) {
            Comparator<ProductMachineDto> priceComparator = productMachineVo.getPriceSort() ?
                    Comparator.comparing(ProductMachineDto::getPrice) :
                    Comparator.comparing(ProductMachineDto::getPrice).reversed();
          return  productMachineDtoList.stream()
                    .sorted(priceComparator)
                    .collect(Collectors.toList());
        } else if (productMachineVo.getPowerSort() != null) {
            Comparator<ProductMachineDto> powerComparator = productMachineVo.getPowerSort() ?
                    Comparator.comparing(ProductMachineDto::getComputingPower) :
                    Comparator.comparing(ProductMachineDto::getComputingPower).reversed();
            return productMachineDtoList.stream()
                    .sorted(powerComparator)
                    .collect(Collectors.toList());
        } else if (productMachineVo.getPowerDissipationSort() != null) {
            Comparator<ProductMachineDto> powerDissipationComparator = productMachineVo.getPowerDissipationSort() ?
                    Comparator.comparing(ProductMachineDto::getPowerDissipation) :
                    Comparator.comparing(ProductMachineDto::getPowerDissipation).reversed();
            return productMachineDtoList.stream()
                    .sorted(powerDissipationComparator)
                    .collect(Collectors.toList());
        } else {
            return productMachineDtoList;
        }
    }

    @Override
    public Result<List<PayConfigDto>> getPayTypes() {
        LeaseShop leaseShop = leaseShopMapper.selectOne(new LambdaQueryWrapper<LeaseShop>()
                .select(LeaseShop::getId)
                .eq(LeaseShop::getUserEmail, SecurityUtils.getUsername())
                .eq(LeaseShop::getDel, false));
        if (leaseShop == null){
            //店铺不存在
            return Result.success(null);
        }
        List<PayConfigDto> shopWalletInfo = leaseShopMapper.getShopWalletInfo(leaseShop.getId());
        return Result.success(shopWalletInfo);
    }

    ///**
    // * 计算每个价格分组中商品机器的功耗、理论算力、实际算力范围，并返回对应的范围信息对象
    // * @param productMachineDtoMap 按价格分组的商品机器列表
    // * @return 每个价格对应的商品机器范围信息
    // */
    //public static Map<BigDecimal, ProductMachineRangeGroupDto> calculateRanges(Map<BigDecimal, List<ProductMachineDto>> productMachineDtoMap) {
    //    // 使用 AtomicInteger 来实现 onlyKey 递增
    //    AtomicInteger onlyKey = new AtomicInteger(0);
    //    return productMachineDtoMap.entrySet().stream()
    //            .collect(Collectors.toMap(
    //                    Map.Entry::getKey,
    //                    entry -> {
    //                        List<ProductMachineDto> productMachines = entry.getValue();
    //                        int number = productMachines.size();
    //                        BigDecimal price = entry.getKey();
    //
    //                        // 计算功耗范围
    //                        BigDecimal minPower = productMachines.stream()
    //                                .map(ProductMachineDto::getPowerDissipation)
    //                                .min(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        BigDecimal maxPower = productMachines.stream()
    //                                .map(ProductMachineDto::getPowerDissipation)
    //                                .max(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        String powerRange = minPower.equals(maxPower) ? String.valueOf(minPower) : minPower + " - " + maxPower;
    //
    //                        // 计算理论算力范围
    //                        BigDecimal minTheoryPower = productMachines.stream()
    //                                .map(ProductMachineDto::getTheoryPower)
    //                                .min(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        BigDecimal maxTheoryPower = productMachines.stream()
    //                                .map(ProductMachineDto::getTheoryPower)
    //                                .max(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        String theoryPowerRange = minTheoryPower.equals(maxTheoryPower) ? String.valueOf(minTheoryPower) : minTheoryPower + " - " + maxTheoryPower;
    //
    //                        // 计算实际算力范围
    //                        BigDecimal minComputingPower = productMachines.stream()
    //                                .map(ProductMachineDto::getComputingPower)
    //                                .min(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        BigDecimal maxComputingPower = productMachines.stream()
    //                                .map(ProductMachineDto::getComputingPower)
    //                                .max(BigDecimal::compareTo)
    //                                .orElse(BigDecimal.ZERO);
    //                        String computingPowerRange = minComputingPower.equals(maxComputingPower) ? String.valueOf(minComputingPower) : minComputingPower + " - " + maxComputingPower;
    //                        String unit = productMachines.get(0).getUnit();
    //                        int onlyKey1 = onlyKey.incrementAndGet();
    //                        return ProductMachineRangeGroupDto.builder()
    //                                .onlyKey(onlyKey1)
    //                                .powerRange(powerRange)
    //                                .theoryPowerRange(theoryPowerRange)
    //                                .computingPowerRange(computingPowerRange)
    //                                .number(number)
    //                                .price(price)
    //                                .unit(unit)
    //                                .build();
    //                    }
    //            ));
    //}


    @Override
    public Result<String> addProduct(ProductURDVo productURDVo) {
        //校验是否存在收款钱包，不存在无法创建商品

        List<LeaseShopConfig> leaseShopConfig = leaseShopConfigMapper.selectList(new LambdaQueryWrapper<LeaseShopConfig>()
                .eq(LeaseShopConfig::getShopId, productURDVo.getShopId()).eq(LeaseShopConfig::getDel, 0));
        if (leaseShopConfig.isEmpty()){
            return Result.fail("添加商品失败,请先绑定收款钱包");
        }
        String algorithm = Algorithm.getAlgorithm(productURDVo.getCoin());
        String coinFullName = Algorithm.getCoinFullName(productURDVo.getCoin());
        LeaseProduct product = LeaseProduct.builder()
                .image(productURDVo.getImage())
                .name(productURDVo.getName())
                .algorithm(algorithm)
                .description(productURDVo.getDescription())
                .state(productURDVo.getState())
                .type(productURDVo.getType())
                .coin(productURDVo.getCoin())
                .shopId(productURDVo.getShopId())
                .coinFullName(coinFullName)
                .build();
        boolean save = save(product);
        if (!save){
            return Result.fail("新增商品失败");
        }
        return Result.success("新增商品成功");
    }

    @Override
    @Transactional
    public Result<String>  updateProduct(ProductURDVo productURDVo) {;
        PriceDto priceDto = leaseProductMachineMapper.getPriceRange(productURDVo.getId());
        BigDecimal maxPrice = BigDecimal.ZERO;
        BigDecimal minPrice = BigDecimal.ZERO;
        if (priceDto != null){
            maxPrice = priceDto.getPriceMax();
            minPrice = priceDto.getPriceMin();
        }

        //校验商品是否能够上下架
        if (productURDVo.getState() == 1 && leaseProductMachineMapper.checkHasSaleMachineByProductId(productURDVo.getId()) >= 1){
           return Result.fail("商品下架失败,商品存在租约中矿机");
        }

        //修改商品主表
        String algorithm = Algorithm.getAlgorithm(productURDVo.getCoin());
        String coinFullName = Algorithm.getCoinFullName(productURDVo.getCoin());
        LeaseProduct product = LeaseProduct.builder()
                .id(productURDVo.getId())
                .image(productURDVo.getImage())
                .name(productURDVo.getName())
                .description(productURDVo.getDescription())
                .state(productURDVo.getState())
                .algorithm(algorithm)
                .maxPrice(maxPrice)
                .minPrice(minPrice)
                .type(productURDVo.getType())
                .coinFullName(coinFullName)
                .build();

        boolean b1 = updateById(product);
        if (b1){
            return Result.success("修改商品成功");
        }
        return Result.fail("修改商品失败");
    }

    @Override
    @Transactional
    public Result<String>  deleteProduct(Long id) {
        int i = leaseProductMachineMapper.checkHasSaleMachineByProductId(id);
        if(i >= 1){
            return Result.fail("删除失败,该商品存在租约中的机器");
        }
        boolean updateFather = updateById(LeaseProduct.builder().id(id).del(true).build());
        List<Long> machineIds = leaseProductMachineMapper.getIdsForProductId(id);
        if (updateFather){
            if (!machineIds.isEmpty()){
                leaseProductMachineMapper.update(LeaseProductMachine.builder().del(true).build(),
                        new LambdaQueryWrapper<LeaseProductMachine>().in(LeaseProductMachine::getId, machineIds));
                //删除矿机对应的售价
                leaseProductMachinePriceService.update(LeaseProductMachinePrice.builder().del(true).build(),new LambdaUpdateWrapper<LeaseProductMachinePrice>().in(LeaseProductMachinePrice::getProductMachineId, machineIds));
            }

            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result<List<PayTypeDto>> getSupportPayType() {
        Long shopId = getShopIdByProductId();
        List<PayTypeDto> supportPayType = leaseProductMapper.getSupportPayType(shopId);
        return Result.success(supportPayType);
    }



    @Override
    public Result<List<ProductForWalletConfigDto>> getProductListForShopWalletConfig() {
        Long shopId = getShopIdByProductId();
        //1.获取商品列表
        List<ProductForWalletConfigDto> productForShopWalletConfigDtoList = leaseProductMapper.getProductListForShopWalletConfig(shopId);
        if (productForShopWalletConfigDtoList.isEmpty()){
            return Result.success(productForShopWalletConfigDtoList);
        }
        //2.获取商品对应矿机
        List<ProductMachineForWalletConfigDto> productMachineForWalletConfigDtoList = leaseProductMachineMapper.getProductListForShopWalletConfig(shopId);
        BigDecimal usdtPrice = redisService.getCacheBigDecimal(RedisCoinInfoKey.getPiceKey(productForShopWalletConfigDtoList.get(0).getCoin()));
        Map<Long, List<ProductMachineForWalletConfigDto>> collect = productMachineForWalletConfigDtoList.stream()
                .peek(productMachineForWalletConfigDto -> {
                    productMachineForWalletConfigDto.setTheoryUsdtIncome(productMachineForWalletConfigDto.getTheoryIncome()
                            .multiply(usdtPrice));
                })
                .collect(Collectors.groupingBy(ProductMachineForWalletConfigDto::getProductId));
        for (ProductForWalletConfigDto productForWalletConfigDto : productForShopWalletConfigDtoList) {
            List<ProductMachineForWalletConfigDto> list = collect.get(productForWalletConfigDto.getProductId());
            if (list.isEmpty()){
                productForShopWalletConfigDtoList.remove(productForWalletConfigDto);
            }
            productForWalletConfigDto.setMachineList(list);
        }
        return Result.success(productForShopWalletConfigDtoList);
    }

    public Long getShopIdByProductId(){
        LeaseShop leaseShop = leaseShopMapper.selectOne(new LambdaQueryWrapper<LeaseShop>()
                .select(LeaseShop::getId)
                .eq(LeaseShop::getUserEmail,  SecurityUtils.getUsername())
                .eq(LeaseShop::getDel, false));
        return leaseShop.getId();
    }


    @Override
    @Transactional
    public Result<String> updateProductListForShopWalletConfig(ProductMachineForWalletConfigVo productMachineForWalletConfigVo) {
        List<String> payCoinsList = new ArrayList<>(Arrays.asList(productMachineForWalletConfigVo.getSymbol().split(",")));
        String chain = productMachineForWalletConfigVo.getChain();
        String address = productMachineForWalletConfigVo.getPayAddress();
        LeaseShop leaseShop = leaseShopMapper.selectOne(new LambdaQueryWrapper<LeaseShop>()
                .eq(LeaseShop::getUserEmail, SecurityUtils.getUsername()));
        boolean check = checkHashWalletInfo(leaseShop.getId(),chain,address, payCoinsList);
        if (!check){
            return Result.fail("绑定钱包失败,钱包格式不正确或该链和币种钱包已绑定过");
        }
        String[] symbolList = productMachineForWalletConfigVo.getSymbol().split(",");
        List<ProductMachineForWalletConfigVo.PriceVo> priceAndIdList = productMachineForWalletConfigVo.getProductMachineForWalletConfigVoList();
        List<LeaseProductMachinePrice> leaseProductMachinePriceList = new ArrayList<>();
        for (ProductMachineForWalletConfigVo.PriceVo priceVo : priceAndIdList) {
            String[] priceList = priceVo.getPrice().split(",");
            if (priceList.length != symbolList.length){
                return Result.fail("绑定钱包失败,存在商品矿机未设置新钱包售价");
            }
            for (int i = 0; i < priceList.length; i++) {
                leaseProductMachinePriceList.add(LeaseProductMachinePrice.builder()
                        .productMachineId(priceVo.getProductMachineId())
                        .price(new BigDecimal(priceList[i]))
                        .coin(symbolList[i])
                        .chain(chain)
                        .build());
            }
        }
        boolean b = leaseProductMachinePriceService.saveBatch(leaseProductMachinePriceList);
        if (b || leaseProductMachinePriceList.isEmpty()){
            //绑定钱包新钱包
            List<LeaseShopConfig> shopConfigList = leaseShopConfigMapper.getCoinIconByChainAndCoin(chain, payCoinsList);
            String qrCode = QrCodeUtils.creatRrCode(address, 200, 200);
            for (LeaseShopConfig leaseShopConfig : shopConfigList) {
                leaseShopConfig.setShopId(leaseShop.getId());
                leaseShopConfig.setChain(chain);
                leaseShopConfig.setPayAddress(address);
                leaseShopConfig.setQrcode(qrCode);
            }
            boolean insetWallet = leaseShopConfigService.saveBatch(shopConfigList);
            if (insetWallet){
                return Result.success("绑定钱包成功");
            }
            throw new ProductSoldOutException ("钱包绑定失败");
        }
        throw new ProductSoldOutException ("新币种钱包商品售价新增失败");
    }


    /**
     * 钱包格式校验，以及判断该链和币种钱包是否已存在
     * @param chain
     * @param address
     * @param coinList
     * @return
     */
    public boolean checkHashWalletInfo(Long shopId,String chain,String address,List<String> coinList){
        if (!WalletRuleCheckUtils.checkAddress(chain,address)){
            return false;
        }
        List<LeaseShopConfig> configList = leaseShopConfigMapper.selectList(new LambdaQueryWrapper<LeaseShopConfig>()
                .eq(LeaseShopConfig::getShopId, shopId)
                .eq(LeaseShopConfig::getChain, chain)
                .in(LeaseShopConfig::getPayCoin, coinList)
                .eq(LeaseShopConfig::getDel, false)
        );
        if (!configList.isEmpty()){
            return false;
        }
        return true;
    }
}
