package com.czg.service.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.czg.market.dto.MkDistributionConfigDTO;
import com.czg.market.entity.MkDistributionConfig;
import com.czg.market.entity.MkDistributionLevelConfig;
import com.czg.market.entity.MkDistributionUser;
import com.czg.market.service.MkDistributionConfigService;
import com.czg.market.service.MkDistributionLevelConfigService;
import com.czg.market.service.MkDistributionUserService;
import com.czg.market.vo.MkDistributionConfigVO;
import com.czg.order.entity.OrderInfo;
import com.czg.service.market.mapper.MkDistributionConfigMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.List;

/**
 * 分销配置 服务层实现。
 *
 * @author ww
 * @since 2025-10-25
 */
@Service
@CacheConfig(cacheNames = "distributionConfig")
public class MkDistributionConfigServiceImpl extends ServiceImpl<MkDistributionConfigMapper, MkDistributionConfig> implements MkDistributionConfigService {

    @Resource
    private MkDistributionLevelConfigService levelConfigService;
    @Resource
    @Lazy
    private MkDistributionUserService distributionUserService;

    @Override
    @Cacheable(key = "#shopId")
    public MkDistributionConfigVO detail(Long shopId) {
        MkDistributionConfig config = getOne(new QueryWrapper().eq(MkDistributionConfig::getShopId, shopId));
        if (config == null) {
            config = new MkDistributionConfig();
            config.setShopId(shopId);
            save(config);
            config = getOne(new QueryWrapper().eq(MkDistributionConfig::getShopId, shopId));
        }
        MkDistributionConfigVO configVO = BeanUtil.copyProperties(config, MkDistributionConfigVO.class);
        configVO.setLevelConfigList(levelConfigService.list(new QueryWrapper()
                .eq(MkDistributionLevelConfig::getDistributionConfigId, config.getId())
                .orderBy(MkDistributionLevelConfig::getLevel).asc()));
        return configVO;
    }

    @Override
    @CacheEvict(key = "#shopId")
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(Long shopId, MkDistributionConfigDTO dto) {
        MkDistributionConfig config = getOne(new QueryWrapper().eq(MkDistributionConfig::getShopId, shopId));
        if (config == null) {
            config = new MkDistributionConfig();
            config.setShopId(shopId);
            save(config);
            config = getOne(new QueryWrapper().eq(MkDistributionConfig::getShopId, shopId));
        }
        List<MkDistributionUser> distributionUserList = distributionUserService.list(new QueryWrapper().eq(MkDistributionUser::getShopId, shopId));
        // 邀请人数变动
        if (dto.getInviteCount() != null && !config.getInviteCount().equals(dto.getInviteCount())) {
            distributionUserList.forEach(item -> item.setStatus(item.getInviteCount() >= dto.getInviteCount() ? 1 : 0));
            distributionUserService.updateBatch(distributionUserList);
        }
        BeanUtil.copyProperties(dto, config);

        if (dto.getLevelConfigList() != null) {
            levelConfigService.updateByShopId(dto.getLevelConfigList(), config.getShopId(), config.getId());
        }

        boolean b = updateById(config);
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            MkDistributionConfig finalConfig = config;
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    // 事务成功提交后执行消息发送
                    distributionUserList.forEach(item -> {
                        distributionUserService.initLevel(finalConfig, item);
                    });
                    distributionUserService.updateBatch(distributionUserList);
                }
            });
        }
        return b;
    }


    @Override
    public String rechargeQrCode(Long shopId, BigDecimal amount) {
        try {
            // 生成二维码图片
            BufferedImage image = QrCodeUtil.generate(
                    "https://cashier.sxczgkj.com/payTest?shopId=" + shopId + "&amount=" + amount,
                    500,
                    500
            );

            // 转为字节流
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);

            // 转 Base64
            String base64 = Base64Encoder.encode(os.toByteArray());
            return "data:image/png;base64," + base64;
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }
}
