<?php

namespace App\Services\Pay;

use App\Services\Service;
use Illuminate\Support\Facades\DB;

class TicketService extends Service
{

    public const TICKET = array(
        1 => [
            'name' => '5折购买券',
            'discount' => 0.5,
            'description' => '购买卡片时5折消费',
            'validity' => 86400
        ],
        2 => [
            'name' => '5折购买券',
            'discount' => 0.5,
            'description' => '购买卡片时5折消费',
            'validity' => 86400
        ],
        3 => [
            'name' => '72小时活动入场券',
            'discount' => 0,
            'description' => '72小时活动入场券',
            'validity' => 86400 * 31
        ],
        4 => [
            'name' => '免费解锁券',
            'discount' => 0,
            'description' => '免费解锁卡片一次',
            'validity' => 86400 * 365 * 10
        ],
        5 => [
            'name' => '免费解锁券',
            'discount' => 0,
            'description' => '免费解锁卡片一次',
            'validity' => 86400 * 365 * 10
        ]
    );

    /**
     * 创建卡片[存在uid则领取]
     * @param  int  $type  类型
     * @param  int  $uid  用户
     * @param  int  $cnt  数量
     * @return mixed    参数cnt为1时返回卡券id；否则返回true
     */
    public function create(int $type = 1, int $uid = 0, int $cnt = 1)
    {
        $data = array();
        for ($i = 0; $i < $cnt; $i++) {
            $add = array(
                'name' => self::TICKET[$type]['name'],
                'description' => self::TICKET[$type]['description'],
                'code' => bin2hex(\openssl_random_pseudo_bytes(4)),
                'type' => $type,
                'create_time' => time()
            );
            if ($uid) {
                $add['uid'] = $uid;
                $add['get_time'] = time();
                $add['validity_time'] = time() + self::TICKET[$type]['validity'];
            }
            array_push($data, $add);
        }
        if (1 == $cnt) {
            return DB::table("kdgx_partner_charge_user_ticket")->insertGetId($data[0]);
        } else {
            DB::table("kdgx_partner_charge_user_ticket")->insert($data);
            return true;
        }
    }
}
