<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/7/16
 * Time: 18:09
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\PaymentInfoModel;
use App\Models\UserInfoModel;
use App\Models\WechatAppModel;
use App\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Auth,Validator;
use App\Services\Base\ErrorCode;

class PayController extends Controller
{
    private $config;
    private $wechat;
    public function __construct()
    {
        parent::__construct();
        $wechat = WechatAppModel::find(1);
        $this->wechat = $wechat;
        $this->config = [
            // 必要配置
            'app_id'             => $wechat->appId,
            'mch_id'             => $wechat->mchId,
            'key'                => $wechat->key,   // API 密钥0

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            //'cert_path'          => public_path().'/pem/', // XXX: 绝对路径！！！！
            //'key_path'           => public_path().'/pem/',      // XXX: 绝对路径！！！！

            'notify_url'         => '/pay/notify',     // 你也可以在下单时单独设置来想覆盖它
        ];
    }


    /**
     * @api {post} /api/pay/recharge 充值（recharge）
     * @apiDescription 充值（recharge）recharge
     * @apiGroup Pay
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {decimal}  price  金额
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *      "json": "{\"appId\":\"wx92066f7587c34617\",\"timeStamp\":\"1532584373\",\"nonceStr\":\"5b5961b537a27\",\"package\":\"prepay_id=wx2613525320101170a0f42d941994171920\",\"signType\":\"MD5\",\"paySign\":\"B4E50A4610F3AC4AE2E12EF2A45D8109\"}"
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function recharge(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'price' => 'required',
            ],[
                'price.required' => 'price不能为空!',

            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        $money = $request->input('price');
        $trade_no = 'Pay'.date('YmdHis').rand(1000,9999);
        $order['user_id'] = $userAuth->id;
        $order['out_trade_no'] = $trade_no;
        $order['price'] = $money;
        $order['to_user'] = 0;
        $order['state'] = 0;
        $order['msg_id'] = 0;
        $order['poundage'] = 0;
        $order['openid'] = $userAuth->openid;
        $order['type'] = 0;
        PaymentInfoModel::create($order);
        $app = Factory::payment($this->config);

        $result = $app->order->unify([
            'body' => '知识付费充值余额',
            'out_trade_no' => $trade_no,
            'total_fee' => $money * 100,
            'trade_type' => 'JSAPI',
            'notify_url' => url('/api/home/notify'),
            'openid' => $userAuth->openid
        ]);
        //dd($result);


        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $payment = Factory::payment($this->config);
            $jssdk = $payment->jssdk;

            $json = $jssdk->bridgeConfig($result['prepay_id']);
            //dd($json);
            return $this->api(compact('json'));
        }else{
            $msg = "签名失败，请稍后再试!";

            return $this->api(compact('msg'));
        }
    }


//下面是回调函数
    public function notify()
    {
        $app = Factory::payment($this->config);
        \Log::info("wechat notify start!");
        $response = $app->handlePaidNotify(function ($notify, $successful) {
            \Log::info($notify);
            if ($notify['result_code'] == 'SUCCESS') {
                $user = UserInfoModel::where('openid',$notify['openid'])->first();
                $data['order_no'] = $notify['out_trade_no'];
                $data['price'] = $notify['total_fee'] / 100;
                $wechat_pay = PaymentInfoModel::where([['user_id',$user->id],['out_trade_no',$notify['out_trade_no']],['state',0]])->first();
                if($wechat_pay){
                    $user->money += $data['price'];
                    $user->save();
                    $wechat_pay->state = 1;
                    $wechat_pay->save();
                }
            } else {
                return $successful('通信失败，请稍后再通知我');
            }
            return true;
        });
        return $response->send();
    }


    /**
     * @api {post} /api/pay/cash 提现（cash）
     * @apiDescription 提现（cash）cash
     * @apiGroup Pay
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {decimal}  price    金额
     * @apiParam {string}  name    真实姓名
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *      "msg": "已成功发起提现，请等待后台审核"
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function cash(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'price' => 'required',
                'name' => 'required',
            ],[
                'price.required' => 'price不能为空!',
                'name.required' => 'name不能为空!'
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $userAuth = Auth('api')->user();
        $trade_no = 'Cash'.date('YmdHis').rand(1000,9999);
        $poundage = $this->wechat->poundage * $data['price'];
        $total = $data['price'] + $poundage;
        if($userAuth->money < $total){
            $msg = '您的余额不足';
            return $this->api($msg);
        }
        DB::beginTransaction();
        $user = UserInfoModel::find($userAuth->id);
        $user->money -= $total;
        $res = $user->save();
        if($res){
            $order['user_id'] = 0;
            $order['out_trade_no'] = $trade_no;
            $order['price'] = $data['price'];
            $order['to_user'] = $userAuth->id;
            $order['state'] = 0;
            $order['name'] = $data['name'];
            $order['msg_id'] = 0;
            $order['poundage'] = 0;
            $order['openid'] = $userAuth->openid;
            $order['type'] = 1;
            $query = PaymentInfoModel::create($order);
            if($query){
                $msg = '已成功发起提现，请等待后台审核';
                DB::commit();
            } else {
                $msg = '提现失败';
                DB::rollback();
            }
        } else {
            $msg = '提现失败';
            DB::rollback();
        }
        return $this->api($msg);

    }

}