<?php
/**
 * Created by PhpStorm.
 * User: 86132
 * Date: 2020/9/3
 * Time: 13:32
 */

namespace app\api\controller;

use EasyWeChat\Foundation\Application;
use think\Db;
use app\common\controller\Api;

/**
 * 会员接口
 */
class Vip extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 用户接口
     * @ApiTitle    (会员接口-验证)
     * @ApiSummary  (验证)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Vip/UserInfoRult)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": {
    }
    })
     */
    public function UserInfoRult()
    {
        $user_id = $this->is_token($this->request->header());
        $user = Db::name('user')->where('id', $user_id)->find();
        if (empty($user['car_num']) || empty($user['color']) || empty($user['car_type']) || empty($user['address']) || empty($user['address_con'])) {
            $this->error('请先完善信息', 0);
            die;
        }
        $this->success('成功', 1);
    }

    /**
     * 用户接口
     * @ApiTitle    (会员接口-确认信息)
     * @ApiSummary  (确认信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Vip/OkBuyVip)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": {
    "price": "200.00",
    "con": "有效期30个自然日",
    "order_sn": "202009031647375986403120",
    "address": "河北省唐山市路南区",
    "car_num": "冀B123456",
    "car_type": "AE86",
    "color": "五颜六色的白"
    }
    })
     */
    public function OkBuyVip()
    {
        $user_id = $this->is_token($this->request->header());
        $id = input('id');
        $vip = Db::name('vip')->where('id', $id)->find();
        $user = Db::name('user')->where('id', $user_id)->find();
        if (empty($user['car_num']) || empty($user['color']) || empty($user['car_type']) || empty($user['address']) || empty($user['address_con'])) {
            $this->error('请先完善信息', 0);
            die;
        }
        $order_sn = $this->order_sn();
        $data = [
            'order_sn' => $order_sn,
            'user_id' => $user_id,
            'status' => 0,
            'vip_id' => $id,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $is_order = Db::name('order')->insert($data);
        if (!$is_order) {
            $this->error('订单创建失败', 0);
            die;
        }
        $return = [
            'price' => $vip['price'],
            'con' => $vip['con'],
            'order_sn' => $order_sn,
            'address' => $user['address'],
            'address_con' => $user['address_con'],
            'car_num' => $user['car_num'],
            'car_type' => $user['car_type'],
            'color' => $user['color']
        ];
        $this->success('成功', $return);
    }


    /**
     * 用户接口
     * @ApiTitle    (会员接口-微信支付)
     * @ApiSummary  (微信支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Vip/WeChatPay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="order_sn", type="integer", required=true, description="订单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    })
     */
    public function WechatPay()
    {
        $user_id = $this->is_token($this->request->header());
        $param = $this->request->param();
        $openid = Db::name('user')->where('id', $user_id)->value('openid');
        $domain = $this->request->domain();
        $price_id = Db::name('order')->where('order_sn', $param['order_sn'])->value('vip_id');
        $price = Db::name('vip')->where('id', $price_id)->value('price');
        $data = [
            'amount' => $price,
            'orderid' => $param['order_sn'],
            'type' => "wechat",
            'title' => "会员开通",
            'notifyurl' => $domain . "/api/vip/notify/paytype/wechat",
            'returnurl' => $domain . "/api/vip/baidu",
            'method' => "miniapp",
            'openid' => $openid
        ];
        $return = \addons\epay\library\Service::submitOrder($data);
        echo $return;
    }


    /**
     * @ApiTitle    (会员接口-支付成功回调)
     * @ApiSummary  (支付成功回调)
     * @ApiMethod (POST)
     * @ApiRoute    (/api/pay/notify)
     * @ApiParams   (name="paytype", type="string", required=true, description="")
     * @ApiReturnParams   (name="code", type="integer", required=true,  sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code":"1",
    "msg": "返回成功",
    })
     */
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            die;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            //$data['out_trade_no'] 订单号
            $order_sn = $data['out_trade_no'];
            $order = Db::name('order')->where('order_sn', $order_sn)->find();
            if ($order['status'] == 1) {
                return $pay->success('支付成功');
                die;
            }
            //更改订单状态
            $is_order = Db::name('order')->where('order_sn', $order_sn)->update(['status' => 1]);
            if (!$is_order) {
                $this->error('订单状态修改失败', 0);
                die;
            }
            //更改用户会员状态
            $user = Db::name('user')->where('id', $order['user_id'])->find();
            //是否是会员
            $savetime = $this->exptime($order['vip_id']);
            if ($user['vip'] == 1) {
                $is_update = Db::name('user')->where('id', $order['user_id'])->update(['exptime' => $user['exptime'] + $savetime + 86400 * 3]);
                Db::name('renwu')->where('user_id', $order['user_id'])->update(['endtime' => $user['exptime'] + $savetime + 86400 * 3]);
            } else {
                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $order['user_id'],
                    'vip_id' => $order['vip_id'],
                    'type' => 2,
                    'createtime' => time(),
                    'startime' => time() + 86400 * 3,
                    'endtime' => time() + $savetime + 86400 * 3
                ];
                $is_renwu = Db::name('renwu')->insert($data);
                if (!$is_renwu) {
                    $this->error('任务创建失败', 0);
                    die;
                }
                $is_update = Db::name('user')->where('id', $order['user_id'])->update(['exptime' => time() + $savetime + 86400 * 3, 'vip' => 1]);
            }
            if (!$is_update) {
                $this->error('个人信息会员状态修改失败', 0);
                die;
            }
            //你可以在此编写订单逻辑

        } catch (Exception $e) {
        }
        echo $pay->success('支付成功');
    }

    //returnurl
    public function baidu()
    {
        header("Location: http://www.baidu.com");
    }


    public function exptime($vip)
    {
        if ($vip == 1) {
            $time = 86400 * 30;
        }
        if ($vip == 2) {
            $time = 86400 * 90;
        }
        if ($vip == 3) {
            $time = 86400 * 365;
        }
        return $time;
    }
}