package com.haha.service.impl;

import com.haha.common.constant.CommonConstants;
import com.haha.common.exception.BusinessException;
import com.haha.entity.Distributor;
import com.haha.mapper.DistributorMapper;
import com.haha.service.DistributorQrcodeService;
import com.haha.service.DistributorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
@RequiredArgsConstructor
public class DistributorQrcodeServiceImpl implements DistributorQrcodeService {

    private final DistributorMapper distributorMapper;
    private final DistributorService distributorService;

    @Value("${distributor.qrcode.appid:}")
    private String appid;

    @Value("${distributor.qrcode.page-path:pages/index/index}")
    private String pagePath;

    @Value("${distributor.qrcode.param-name:distributorCode}")
    private String paramName;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String generateQrcode(Long distributorId) {
        Distributor distributor = distributorService.getById(distributorId);
        if (distributor == null || distributor.getDeleted() == CommonConstants.DELETED) {
            throw new BusinessException(404, "分销员不存在");
        }

        if (distributor.getQrcodeContent() != null) {
            return distributor.getQrcodeContent();
        }

        String qrcodeContent = buildQrcodeContent(distributor.getCode());
        log.info("[分销二维码] 生成二维码内容 - distributorId: {}, code: {}, content: {}", 
                distributorId, distributor.getCode(), qrcodeContent);

        distributor.setQrcodeContent(qrcodeContent);
        distributorService.updateById(distributor);

        return qrcodeContent;
    }

    @Override
    public byte[] downloadQrcode(Long distributorId) {
        throw new BusinessException(400, "二维码由前端动态生成，无需下载");
    }

    private String buildQrcodeContent(String distributorCode) {
        if (appid == null || appid.isEmpty()) {
            log.warn("[分销二维码] 未配置微信小程序appid，使用默认格式");
            return "DISTRIBUTOR:" + distributorCode;
        }

        String query = paramName + "=" + distributorCode;
        String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
        
        return String.format("weixin://dl/business/?appid=%s&path=%s&query=%s",
                appid,
                URLEncoder.encode(pagePath, StandardCharsets.UTF_8),
                encodedQuery);
    }
}
