<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\service\qrcode;

/**
 * 订单核销二维码
 * Class Extract
 * @package app\common\service\qrcode
 */
class Extract extends BaseQRcode
{
    // 当前客户端 (默认H5)
    private string $channel;

    // 当前用户信息
    private $user;

    // 订单ID
    private int $orderId;

    /**
     * 构造方法
     * Extract constructor.
     * @param string $channel 二维码渠道(小程序码、h5码)
     * @param $user
     * @param int $orderId
     */
    public function __construct($user, int $orderId, string $channel = 'H5')
    {
        parent::__construct();
        $this->user = $user;
        $this->orderId = $orderId;
        $this->channel = $channel;
    }

    /**
     * 获取小程序码
     * @return string
     * @throws \cores\exception\BaseException
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getImage(): string
    {
        // 判断二维码文件存在则直接返回url
        if (file_exists($this->getPosterPath())) {
            return $this->getPosterUrl();
        }
        // 下载二维码
        $scene = "oid:{$this->orderId}";
        $qrcode = $this->getQrcode($this->storeId, $scene, 'pages/order/extract/check', $this->channel);
        return $this->savePoster($qrcode);
    }

    /**
     * 保存并获取图片
     * @param $qrcode
     * @return string
     */
    private function savePoster($qrcode): string
    {
        copy($qrcode, $this->getPosterPath());
        return $this->getPosterUrl();
    }

    /**
     * 二维码文件路径
     * @return string
     */
    private function getPosterPath(): string
    {
        // 保存路径
        $tempPath = web_path() . "temp/{$this->storeId}/";
        !is_dir($tempPath) && mkdir($tempPath, 0755, true);
        return $tempPath . $this->getPosterName();
    }

    /**
     * 二维码文件名称
     * @return string
     */
    private function getPosterName(): string
    {
        return 'extract_' . md5("{$this->orderId}_{$this->user['user_id']}_{$this->channel}") . '.png';
    }

    /**
     * 二维码url
     * @return string
     */
    private function getPosterUrl(): string
    {
        return base_url() . 'temp/' . $this->storeId . '/' . $this->getPosterName() . '?t=' . time();
    }
}