package com.ruoyi.brewery.service.impl;

import java.util.List;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyBarIconLog;
import com.ruoyi.bar.domain.WyBeerQrcodeScanLog;
import com.ruoyi.bar.service.IWyBarIconLogService;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.bar.service.impl.WyBeerQrcodeScanLogServiceImpl;
import com.ruoyi.brewery.domain.WyBeer;
import com.ruoyi.brewery.domain.WyBeerQrcodeBatch;
import com.ruoyi.brewery.mapper.WyBeerQrcodeBatchMapper;
import com.ruoyi.brewery.service.IWyActivityBeerService;
import com.ruoyi.brewery.service.IWyActivityService;
import com.ruoyi.brewery.service.IWyBeerService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.CodeGeneratorUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QRCode.QRCodeUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.IWyPlatformActivityBeerService;
import com.ruoyi.system.service.IWyPlatformActivityService;
import org.springframework.stereotype.Service;
import com.ruoyi.brewery.mapper.WyBeerQrcodeMapper;
import com.ruoyi.brewery.domain.WyBeerQrcode;
import com.ruoyi.brewery.service.IWyBeerQrcodeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 酒品二维码Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-21
 */
@Service
public class WyBeerQrcodeServiceImpl implements IWyBeerQrcodeService {
    @Resource
    private WyBeerQrcodeMapper wyBeerQrcodeMapper;
    @Resource
    private WyBeerQrcodeBatchMapper wyBeerQrcodeBatchMapper;
    @Resource
    private WyBeerQrcodeScanLogServiceImpl wyBeerQrcodeScanLogService;
    @Resource
    private WxMaService wxMaService;

    @Resource
    private IWyActivityBeerService wyActivityBeehiveService;

    @Resource
    private IWyPlatformActivityBeerService wyPlatformActivityBeerService;
    @Resource
    private IWyPlatformActivityService wyPlatformActivityService;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private IWyBarService wyBarService;
    @Resource
    private IWyBarIconLogService iconLogService;
    @Resource
    private IWyActivityService activityService;

    /**
     * 查询酒品二维码
     *
     * @param id 酒品二维码主键
     * @return 酒品二维码
     */
    @Override
    public WyBeerQrcode selectWyBeerQrcodeById(Long id) {
        return wyBeerQrcodeMapper.selectWyBeerQrcodeById(id);
    }

    @Override
    public WyBeerQrcode selectWyBeerQrcodeAllDataById(Long id) {
        final WyBeerQrcode wyBeerQrcode = wyBeerQrcodeMapper.selectWyBeerQrcodeById(id);
        if (wyBeerQrcode != null && wyBeerQrcode.getQrcodeStatus() == 1) {
            final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
            wyBeerQrcodeScanLog.setScanStatus(1);
            wyBeerQrcodeScanLog.setCodeId(id);
            final List<WyBeerQrcodeScanLog> logs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);
            if (logs != null && logs.size() > 0) {
                final Long activityId = logs.get(0).getActivityId();
                wyBeerQrcode.setActivityId(activityId);
                wyBeerQrcode.setActivity(activityService.selectWyActivityById(activityId));
                final Long barId = logs.get(0).getBarId();
                final WyBar wyBar = wyBarService.selectWyBarById(barId);
                wyBeerQrcode.setBarCode(wyBar.getBarNumber());
                final WyBarIconLog wyBarIconLog = new WyBarIconLog();
                final Integer coinCount = iconLogService.selectWyBarIconSum(wyBarIconLog);
                wyBeerQrcode.setCoinCount(coinCount);
            }
        }
        return wyBeerQrcode;
    }

    @Override
    public WyBeerQrcode selectWyBeerQrcodeByCode(String code) {
        return wyBeerQrcodeMapper.selectWyBeerQrcodeByCode(code);
    }

    /**
     * 查询酒品二维码列表
     *
     * @param wyBeerQrcode 酒品二维码
     * @return 酒品二维码
     */
    @Override
    public List<WyBeerQrcode> selectWyBeerQrcodeList(WyBeerQrcode wyBeerQrcode) {
        return wyBeerQrcodeMapper.selectWyBeerQrcodeList(wyBeerQrcode);
    }

    @Override
    public List<WyBeerQrcode> selectWyBeerQrcodeListWithData(WyBeerQrcode wyBeerQrcode) {
        final List<WyBeerQrcode> wyBeerQrcodes = wyBeerQrcodeMapper.selectWyBeerQrcodeList(wyBeerQrcode);
        wyBeerQrcodes.forEach(item -> {
            if (item.getQrcodeStatus() == 1) {
                final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
                wyBeerQrcodeScanLog.setScanStatus(1);
                wyBeerQrcodeScanLog.setCodeId(item.getId());
                final List<WyBeerQrcodeScanLog> logs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);
                if (logs != null && logs.size() > 0) {
                    final Long activityId = logs.get(0).getActivityId();
                    item.setActivityId(activityId);
                    final Long barId = logs.get(0).getBarId();
                    final WyBar wyBar = wyBarService.selectWyBarById(barId);
                    if (wyBar != null) {
                        item.setBarCode(wyBar.getBarNumber());
                    }
                    final WyBarIconLog wyBarIconLog = new WyBarIconLog();
                    wyBarIconLog.setBarId(barId);
                    final Integer coinCount = iconLogService.selectWyBarIconSum(wyBarIconLog);
                    item.setCoinCount(coinCount);
                }
            }
        });
        return wyBeerQrcodes;
    }

    /**
     * 新增酒品二维码
     *
     * @param wyBeerQrcode 酒品二维码
     * @return 结果
     */
    @Override
    public int insertWyBeerQrcode(WyBeerQrcode wyBeerQrcode) {
        wyBeerQrcode.setCreateTime(DateUtils.getNowDate());
        wyBeerQrcode.setBatchSn(generateSn());
        return wyBeerQrcodeMapper.insertWyBeerQrcode(wyBeerQrcode);
    }


    @Transactional
    @Override
    public int batchInsertWyBeerQrcode(WyBeerQrcodeBatch wyBeerQrcodeBatch, String hostUrl) {
        WyBeerQrcode wyBeerQrcodeQuery = new WyBeerQrcode();
        wyBeerQrcodeQuery.setBatchId(wyBeerQrcodeBatch.getId());
        wyBeerQrcodeQuery.setBreweryId(wyBeerQrcodeBatch.getBreweryId());
        final List<WyBeerQrcode> wyBeerQrcodes = this.selectWyBeerQrcodeList(wyBeerQrcodeQuery);
        if (wyBeerQrcodes != null && wyBeerQrcodes.size() > 0) {
            throw new RuntimeException("该批次已生成酒品二维码，请勿重复操作");
        }
        final WyBeer beer = wyBeerService.selectWyBeerById(wyBeerQrcodeBatch.getBeerId());
        Long verifyIconAmount = 0L;
        if (beer.getScanCoinCount() != null) {
            verifyIconAmount = beer.getScanCoinCount();
        }
        Integer successNum = 0;
        for (int i = 0; i < wyBeerQrcodeBatch.getGenerateNum(); i++) {
            WyBeerQrcode wyBeerQrcode = new WyBeerQrcode();
            wyBeerQrcode.setBatchId(wyBeerQrcodeBatch.getId());
            wyBeerQrcode.setBeerId(wyBeerQrcodeBatch.getBeerId());
            wyBeerQrcode.setBreweryId(wyBeerQrcodeBatch.getBreweryId());
//            wyBeerQrcode.setSkuSn(UUID.randomUUID().toString(true));
            wyBeerQrcode.setSkuSn(generateSn());
            wyBeerQrcode.setBatchSn(wyBeerQrcodeBatch.getBatchSn());
            //核销必送啤酒币
            wyBeerQrcode.setVerifyIconAmount(verifyIconAmount);
            final String skuSn = wyBeerQrcode.getSkuSn();
            final String filePath = "/qrcode/" + wyBeerQrcodeBatch.getBatchSn() + "/" + skuSn + ".jpg";
            final String qrcodeUrl = hostUrl + "/profile/upload" + filePath;
            //生成二维码（临时生成普通二维码）
            try {
                QRCodeUtil.encode(skuSn, RuoYiConfig.getUploadPath() + filePath);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            wyBeerQrcode.setQrcodeUrl(qrcodeUrl);
            wyBeerQrcode.setQrcodeStatus(0);
            successNum += wyBeerQrcodeMapper.insertWyBeerQrcode(wyBeerQrcode);
            // 生成小程序码，暂不启用，小程序尚未备案，无法生成
//            try {
//                String filePath = RuoYiConfig.getUploadPath();
//                final File wxaCodeUnlimit = wxMaService.getQrcodeService().createWxaCodeUnlimit("skuSn=" + wyBeerQrcode.getId(), "pages/scan/scanResult");
////                Files.write(Paths.get(filePath), wxaCodeUnlimit);
//            } catch (WxErrorException e) {
//                throw new RuntimeException(e);
//            }
        }
        wyBeerQrcodeBatch.setGenerateState(1);
        wyBeerQrcodeBatch.setUpdateTime(DateUtils.getNowDate());
        wyBeerQrcodeBatchMapper.updateWyBeerQrcodeBatch(wyBeerQrcodeBatch);
        return successNum;
    }

    /**
     * 修改酒品二维码
     *
     * @param wyBeerQrcode 酒品二维码
     * @return 结果
     */
    @Transactional
    @Override
    public int updateWyBeerQrcode(WyBeerQrcode wyBeerQrcode) {
        wyBeerQrcode.setUpdateTime(DateUtils.getNowDate());
        final int i = wyBeerQrcodeMapper.updateWyBeerQrcode(wyBeerQrcode);
        return i;
    }

    /**
     * 批量删除酒品二维码
     *
     * @param ids 需要删除的酒品二维码主键
     * @return 结果
     */
    @Override
    public int deleteWyBeerQrcodeByIds(Long[] ids) {
        return wyBeerQrcodeMapper.deleteWyBeerQrcodeByIds(ids);
    }

    /**
     * 删除酒品二维码信息
     *
     * @param id 酒品二维码主键
     * @return 结果
     */
    @Override
    public int deleteWyBeerQrcodeById(Long id) {
        return wyBeerQrcodeMapper.deleteWyBeerQrcodeById(id);
    }

    /**
     * 生成编号
     */
    private String generateSn() {
        final Integer integer = wyBeerQrcodeBatchMapper.selectBatchCount();
        String sn = CodeGeneratorUtils.generateCode(integer);
        //生成订单号
        final WyBeerQrcode query = new WyBeerQrcode();
        query.setBatchSn(sn);
        final WyBeerQrcode wyBeerQrcode = selectWyBeerQrcodeByCode(sn);
        if (wyBeerQrcode != null) {
            return generateSn();
        }
        return sn;
    }
}
