package com.jeequan.jeepay.pay.ctrl.scanimg;

import com.jeequan.jeepay.core.model.QRCodeParams;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.CacheTk;
import com.jeequan.jeepay.pay.ctrl.payorder.AbstractPayOrderController;
import com.jeequan.jeepay.pay.util.CodeImgUtil;
import com.jeequan.jeepay.service.impl.CacheTkService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/*
* jeepay 扫描图片生成器
*
* @author terrfly
*
* @date 2021/6/8 17:28
*/
@RestController
@RequestMapping("/api/scan")
public class ScanImgController extends AbstractPayOrderController {

    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private CacheTkService cacheTkService;

    /** 返回 图片地址信息  **/
    @RequestMapping("/imgs/{aesStr}.png")
    public void qrImgs(@PathVariable("aesStr") String aesStr) throws Exception {
        if(aesStr.startsWith(SeqKit.TOKEN_PREFIX)){
            CacheTk cacheTk = cacheTkService.getById(aesStr);
            if(cacheTk.getType() == QRCodeParams.TYPE_ROUTE){
                aesStr = sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/pages/route/index?"+JeepayKit.TOKEN_KEY+"="+cacheTk.getTk();
            }else{
                String extParams = "&price="+ AmountUtil.convertCent2Dollar(cacheTk.getAmount()) + "&order_no="+ cacheTk.getSourceId() + "&env=scan";
                aesStr = sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/pages/payment/index?"+JeepayKit.TOKEN_KEY+"="+cacheTk.getTk() + extParams;
            }
        }else{
            aesStr = JeepayKit.aesDecode(aesStr);
        }
        int width = getValIntegerDefault("width", 200);
        int height = getValIntegerDefault("height", 200);
        CodeImgUtil.writeQrCode(response.getOutputStream(), aesStr, width, height);
    }
}
