package com.hzs.third.share.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.config.OssConfig;
import com.hzs.common.core.enums.EShareType;
import com.hzs.common.core.utils.BarCodeUtils;
import com.hzs.common.domain.third.share.TShareCode;
import com.hzs.third.share.dto.ShareServiceDTO;
import com.hzs.third.share.mapper.TShareCodeMapper;
import com.hzs.third.share.service.ITShareCodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * 分享编码 服务实现类
 *
 * @author hzs
 * @since 2023-03-15
 */
@Service
public class TShareCodeServiceImpl extends ServiceImpl<TShareCodeMapper, TShareCode> implements ITShareCodeService {

    @Value("${share.sharePath}")
    private String sharePath;

    @Override
    public String queryShareCode(ShareServiceDTO dto) {
        String resultCode = null;

        // 分享业务类型
        EShareType eShareType = dto.getEShareType();
        // 分享业务ID
        Long pkBusiness = dto.getPkBusiness();

        // 查询该业务数据库中是否存在
        LambdaQueryWrapper<TShareCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TShareCode::getBusinessType, eShareType.getValue());
        queryWrapper.eq(TShareCode::getPkBusiness, pkBusiness);
        TShareCode tShareCode = baseMapper.selectOne(queryWrapper);
        if (null != tShareCode) {
            resultCode = tShareCode.getPath();
        } else {
            // 如果不存在，则需要新生成
            String code = Base64Encoder.encode(pkBusiness.toString().getBytes(StandardCharsets.UTF_8));

            switch (eShareType) {
                case SHARE:
                    // 分享注册
                    resultCode = sharePath + "?code=" + code;
                    break;
                default:
            }

            // 生成分享二维码，并且上传OSS
            resultCode = BarCodeUtils.createZeroQRCode(resultCode);

            tShareCode = new TShareCode();
            tShareCode.setBusinessType(eShareType.getValue());
            tShareCode.setPkBusiness(pkBusiness);
            tShareCode.setPath(resultCode);
            tShareCode.setPkOperator(dto.getUserId());
            baseMapper.insert(tShareCode);
        }

        return OssConfig.getFilePath() + resultCode;
    }

}
