<?php

namespace app\api\controller\user;

use app\models\order\Level;
use app\models\system\SystemGroupData;
use app\models\user\UserRecharge;
use app\Request;
use crmeb\services\GroupDataService;
use crmeb\services\SystemConfigService;
use crmeb\services\UtilService;

/**
 * 充值类
 * Class UserRechargeController
 * @package app\api\controller\user
 */
class UserRechargeController
{

    /**
     * 小程序充值
     *
     * @param Request $request
     * @return mixed
     */
    public function routine(Request $request)
    {
        list($price, $recharId, $type) = UtilService::postMore([
            [['price', 'f'], 0],
            [['rechar_id', 'd'], 0],
            ['type', 0]
        ], $request, true);
        if (!$price || $price <= 0) return app('json')->fail('参数错误');
        $storeMinRecharge = sys_config('store_user_min_recharge');
        if ($price < $storeMinRecharge) return app('json')->fail('充值金额不能低于' . $storeMinRecharge);
        switch ((int)$type) {
            case 0: //支付充值余额
                $paid_price = 0;
                if ($recharId) {
                    $data = SystemGroupData::getDateValue($recharId);
                    if ($data === false) {
                        return app('json')->fail('您选择的充值方式已下架!');
                    } else {
                        $paid_price = $data['give_money'] ?? 0;
                    }
                }
                $rechargeOrder = UserRecharge::addRecharge($request->uid(), $price, 'routine', $paid_price);
                if (!$rechargeOrder) return app('json')->fail('充值订单生成失败!');
                try {
                    return app('json')->successful(UserRecharge::jsPay($rechargeOrder));
                } catch (\Exception $e) {
                    return app('json')->fail($e->getMessage());
                }
                break;
            case 1: //佣金转入余额
                if (UserRecharge::importNowMoney($request->uid(), $price))
                    return app('json')->successful('转入余额成功');
                else
                    return app('json')->fail(UserRecharge::getErrorInfo());
                break;
            default:
                return app('json')->fail('缺少参数');
                break;
        }
    }

    /**
     * 公众号充值
     *
     * @param Request $request
     * @return mixed
     */
    public function wechat(Request $request)
    {
        list($price, $recharId, $from, $type) = UtilService::postMore([
            [['price', 'f'], 0],
            [['rechar_id', 'd'], 0],
            ['from', 'weixin'],
            ['type', 0]
        ], $request, true);
        if (!$price || $price <= 0) return app('json')->fail('参数错误');
        $storeMinRecharge = sys_config('store_user_min_recharge');
        if ($price < $storeMinRecharge) return app('json')->fail('充值金额不能低于' . $storeMinRecharge);
        switch ((int)$type) {
            case 0: //支付充值余额
                $paid_price = 0;
                if ($recharId) {
                    $data = SystemGroupData::getDateValue($recharId);
                    if ($data === false) {
                        return app('json')->fail('您选择的充值方式已下架!');
                    } else {
                        $user = $request->user();
                        if($user['level']==1)
                        {
                            $paid_price = $data['vip_give_money'] ?? 0;
                        }
                        else
                        {
                            $paid_price = $data['give_money'] ?? 0;
                        }
                    }
                }
                $rechargeOrder = UserRecharge::addRecharge($request->uid(), $price, 'weixin', $paid_price);
                if (!$rechargeOrder) return app('json')->fail('充值订单生成失败!');
                try {
                    if ($from == 'weixinh5') {
                        $recharge = UserRecharge::wxH5Pay($rechargeOrder);
                    } else {
                        $recharge = UserRecharge::wxPay($rechargeOrder);
                    }
                } catch (\Exception $e) {
                    return app('json')->fail($e->getMessage());
                }
                return app('json')->successful(['type' => $from, 'data' => $recharge]);
                break;
            case 1: //佣金转入余额
                if (UserRecharge::importNowMoney($request->uid(), $price))
                    return app('json')->successful('转入余额成功');
                else
                    return app('json')->fail(UserRecharge::getErrorInfo());
                break;
            default:
                return app('json')->fail('缺少参数');
                break;
        }
    }

    /**
     * 充值额度选择
     * @return mixed
     */
    public function index()
    {
        $rechargeQuota = sys_data('user_recharge_quota') ?? [];
        $data['recharge_quota'] = $rechargeQuota;
        $recharge_attention = sys_config('recharge_attention');
        $recharge_attention = explode("\n", $recharge_attention);
        $data['recharge_attention'] = $recharge_attention;
        return app('json')->successful($data);
    }
    /**
     * 会员开通
     * @param Request $request
     * @return mixed
     */
    public function recharge(Request $request)
    {
        //@file_put_contents("level.txt",json_encode(input()));
        list($level_id, $from, $pay_type,$spread_uid,$store_id) = UtilService::postMore([['level_id', 1], ['from', 'weixin'], ['pay_type', 'weixin'],['spread',0],['store_id',0]], $request, true);
        if (!$level_id || $level_id <= 0) return app('json')->fail('参数错误');
        $rechargeOrder = Level::createLevelOrder($request->uid(), $level_id, $pay_type,$spread_uid,$store_id);
        if (!$rechargeOrder) return app('json')->fail('充值订单生成失败!');
        $Order = $rechargeOrder->toArray();
        try {
            switch ($pay_type) {
                case 'weixin':
                    if ($from == 'routine') {
                        $jsConfig = Level::jsPay($Order['order_id']); //订单列表发起支付
                        if (isset($jsConfig['package']) && $jsConfig['package']) {
                            $package = str_replace('prepay_id=', '', $jsConfig['package']);
                            for ($i = 0; $i < 3; $i++) {
                                RoutineFormId::SetFormId($package, $request->uid());
                            }
                        }
                    } else if ($from == 'weixinh5') {
                        $jsConfig = Level::h5Pay($Order['order_id']);
                    } else {
                        $jsConfig = Level::wxPay($Order['order_id']);
                    }
                    if ($from == 'weixinh5') {
                        return app('json')->status('wechat_h5_pay', ['jsConfig' => $jsConfig, 'order_id' => $rechargeOrder['order_id']]);
                    } else {
                        return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $rechargeOrder['order_id']]);
                    }
                    break;
                case 'yue':
                    if (Level::yuePay($Order['order_id'], $request->uid()))
                        return app('json')->status('success', '余额支付成功');
                    else {
                        $error = Level::getErrorInfo();
                        return app('json')->fail(is_array($error) && isset($error['msg']) ? $error['msg'] : $error);
                    }
                    break;
                case 'ali':
                    $rechargeOrder = Level::alipay($Order, $request->uid());
                    if (!$rechargeOrder) return app('json')->fail('开通订单生成失败!');
                    return app('json')->successful(['type' => $from, 'data' => $rechargeOrder]);
                    break;
            }
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }
        return app('json')->fail('支付方式错误');
    }
}