<?php

namespace App\Http\Controllers\V1;
use App\Models\User;
use App\Models\UserMember;
use App\Models\UserMemberOrder;
use Illuminate\Http\Request;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;
/**
 * 支付
 */
class PayController extends Controller
{
    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;
        //如果用户被删除，会自动退出登录
        if (!empty($this->user->deleted_at)) {
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
        Factory::setOptions($this->getOptions());
    }
    public function getOptions(){
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = '2016082201783461';
        $options->merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDrHSXWmI/CgI5sdy+RWLKQixj4PwUnkKq+vSxSSkWBCnL0y3/TOQDSCdYENLc61mXZBi7Aq6igGt7Fr5Kdul35KxMsZa1OJ4i3fGG1y2KC3DePzwduIRn8n/INgKAeOAwJaCWFhQ5Ux+c4U2pFMWFtKKgpfVq2Yotm8pH+IUUflKn2UhlSu60W9sHp/LIqrHgh1NztnEQG7Bhlp+5RJ7qHiZi1C88w99s9ff43TAuWFiN6JQwmIMLnH5XsJU/qa7G4QrMFawPKXyU/tvB/IC5pWUJfRC+x03JMvBT+DZ9qDIcyDRh3Wsmdb8tYKnw5wpzRLZDY1MJG63vaLiMRTRsXAgMBAAECggEAT8Dwb+4KfgkLxwFbEmvLDrsQek0uW3B4awFSwotNLmuz+RP6xVTF0XnirkSPjxbhL5AoVdUk+0KCJP7ctkJc1EPnWh0Xf7Zrawp3PqrCPO+krVSmCZaS8R30ht4F8ppCgwJgD/3Fkb7J0VKCbvxENzoeaQyLs+iTrxVDrrfscbxevx75juU0A0bmIOOYuFWGvVjVBMqxb5ZlayuB73nq3rDqzaC8MxVquN8j8K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V6EGCsBbN8GA/kF7dnHPbzps32eurMIysvmhhulAd+D3O/580lQh6cmcUVc3EZ01lfq2Ki+jM2B8EVTyegqS9ADsIVGa//1hJ7i2J2ulgD1Ros5WBZ8rebsd6Qhq/0uJeOksEFA/Fxv209yp+gKnidUozX7ACDalqHp38OeRw0YWRRICyKh1pPkW7n+hj2GElIBPZUc9SWPkNIkCHwExjV1ha6BkrdiBeLrkKjgh1ul6rTG7AeQdtW54nOWmt7caNJ/swnA7zi8n9j/FAzF9tz4mflVCvdOZYO0PCs+Gea4QVYh2X3wIDAQAB";
        $options->notifyUrl = 'https://t19.9026.com/api/pay/alipay_notify'; //https://t19.9026.com/api/pay/alipay_notify
        return $options;
    }
    /**
     * @return void
     * 构建支付
     */
    public function payment(Request $request){
        $member_id = $request->get('member_id');
        $pay_type = $request->get('pay_type');
        $money = $request->get('money');
        if(!$money || !$pay_type || !$member_id){
            return $this->error("缺少参数！");
        }
        $member = UserMember::query()->where('id',$member_id)->first();
        if(!$member){
            return $this->error("购买选项不存在！");
        }
        $data = [
            'user_id' => $this->userId,
            'days' => $member->month * 30,// 续费时间 = 月份 * 默认一个月30天
            'pay_type' => $pay_type,
            'status' => 0,
            'order_no' => date('YmdHis') . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT), // 订单号
            'money' => $member->money // 续费金额
        ];
        $order = UserMemberOrder::query()->create($data);
        if(!$order){
            return $this->error("操作失败！");
        }
        if($pay_type == 1){ // 支付宝支付
            $result = Factory::payment()->page()->pay("加入企业会员",$order->order_no,$order->money,'');
            dd($result->body);
            return $this->success($result->body);
        }else{
            return $this->error("正在开发中...");
        }
    }

    /**
     * @return void
     * 支付宝回调地址
     */
    public function alipayNotify(Request $request){
        $params = $request->all();
        $result = Factory::payment()->common()->verifyNotify($params);
        if ($result) {
            // 验证成功
            $out_trade_no = $params['out_trade_no'];
//            $trade_no = $params['trade_no'];
            $order = UserMemberOrder::query()->where('order_no','=',$out_trade_no)->first(); //查询订单信息

            UserMemberOrder::query()->where('id',$order->id)->update(['status'=>1,'pay_time'=>time()]);

//            $user = User::query()->where('id','=',$order->user_id)->first(); //查询用户信息
//            $end_time = $order->days * 86400; // 天数换取时间戳(会员结束时间)
//            // 剩下会员时长
//            if(!empty($user->end_time)){
//                if($user->end_time > time()){
//                    $user->end_time = strtotime($user->end_time) +  $end_time;
//                }
//            }else{
//                $user->start_time = time(); // 当前时间
//                $user->end_time = time() + $end_time; // 会员结束时间
//            }
//            $user->member_type = 2; // 变为企业会员
//            $order->status = 1;
//            $order->pay_time = time();
//            $order->save();
//            $user->save();
            return 'success';
        } else {
            // 验证失败
            return 'failure';
        }
    }

}
