<?php

namespace app\api\controller\activity;

use app\models\store\StoreRechargeCard;
use app\models\user\UserRechargeCard;
use app\models\user\User;
use app\Request;
use crmeb\services\UtilService;
use crmeb\services\CacheService;

/**
 * 充值卡类
 * Class StoreRechargeCardController
 * @package app\api\controller\activity
 */
class StoreRechargeCardController
{
	/**
     * 充值卡列表选择
     */
    public function index(Request $request)
    {
        $rechargeCard = StoreRechargeCard::getAll($request->mer_id());
        if (!count($rechargeCard)) return app('json')->successful([]);
        return app('json')->successful($rechargeCard->toArray());
    }

    /**
     * 充值卡详情
     */
    public function detail(Request $request, $id)
    {
    	if (!$id || !($rechargeCardOne = StoreRechargeCard::getRechargeCardOne($id))) return app('json')->fail('充值卡不存在或已下架');
    	return app('json')->successful($rechargeCardOne->toArray());
    }

    /**
     * 充值卡购买
     */
    public function buy_recharge_card(Request $request)
    {
    	list($id, $uid) = UtilService::getMore([
    		['id', ''],
            ['uid', ''],
        ], $request, true);
        if (!$id) return app('json')->fail('参数错误');
        if (!$chargeCardOne = StoreRechargeCard::getRechargeCardOne($id)) return app('json')->fail('充值卡不存在或已下架');
        if ($uid && !User::find($uid)) return app('json')->fail('此用户不存在');
        $status = $chargeCardOne['is_brokerage'] ? 1 : 0;
        $rechargeOrder = UserRechargeCard::addRecharge($request->uid(), $id, $chargeCardOne['price'], $chargeCardOne['give_money'], 0, $chargeCardOne['is_brokerage'], $uid, $status, $request->mer_id());
    	if (!$rechargeOrder) return app('json')->fail('充值订单生成失败!');
        try {
            return app('json')->successful(UserRechargeCard::jsPay($rechargeOrder, $request->mer_id()));
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    /**
     * 获取用户充值记录
     */
    public function get_user_recharge_card_list(Request $request)
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 20]
        ], $request);
        $where['uid'] = $request->uid();
        $where['mer_id'] = $request->mer_id();
        $where['paid'] = 1;
        return app('json')->successful(UserRechargeCard::getUsereRechargeCardList($where));
    }
}