<?php
/**
 * Created by PhpStorm.
 * User: 86132
 * Date: 2020/10/27
 * Time: 18:46
 */

namespace app\api\controller;

use think\Db;
use app\common\controller\Api;

/**
 * 支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 支付接口
     * @ApiTitle    (协议支付)
     * @ApiSummary  (协议支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/AgreementPay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", 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':'返回成功',
    'data':{
    })
     */
    public function AgreementPay()
    {
        $UserId = $this->IsToken($this->request->header());
        $OrderSn = input('OrderSn');
        $UserInfo = Db::name('user')->where('id', $UserId)->find();
        $PayOrder = $this->PayOrder();
        $domain = $this->request->domain();
        $OrderInfo = Db::name('agreement')->where('OrderSn', $OrderSn)->find();
        $Money = $OrderInfo['UpMoney'] + $OrderInfo['MonthMoney'];
        //生成交易流水
        $data = [
            'PayOrder' => $PayOrder,
            'OrderSn' => $OrderSn,
            'type' => 1,
            'status' => 0,
            'user_id' => $UserId,
            'money' => $Money,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $InsertPayOrder = Db::name('pay_order')->insert($data);
        if (!$InsertPayOrder) {
            $this->error('支付订单生成失败', 0);
        }
        $data = [
            'amount' => $Money,
            'orderid' => $PayOrder,
            'type' => "wechat",
            'title' => "协议开通",
            'notifyurl' => $domain . "/api/pay/AgreementPayNotify/paytype/wechat",
            'returnurl' => $domain . "/api/pay/baidu",
            'method' => "miniapp",
            'openid' => $UserInfo['openid']
        ];
        $return = \addons\epay\library\Service::submitOrder($data);
        echo $return;
    }


    /**
     * 订单接口
     * @ApiTitle    (协议支付回调)
     * @ApiSummary  (协议支付回调)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/AgreementPayNotify)
     * @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 AgreementPayNotify()
    {
        $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('pay_order')->where('PayOrder', $order_sn)->find();
            if ($order['status'] == 1) {
                return $pay->success('支付成功');
                die;
            }
            //在此编写订单逻辑
            //修改支付订单状态
            $UpdateStatus = Db::name('pay_order')->where('PayOrder', $data['out_trade_no'])->update(
                [
                    'status' => 1,
                    'updatetime' => time(),
                    'WeChatOrder' => $data['transaction_id']
                ]
            );
            if (!$UpdateStatus) {
                $this->error('修改支付订单状态失败', 0);
                die;
            }
        } catch (Exception $e) {
        }
        echo $pay->success('支付成功');
    }


    /**
     * 支付接口
     * @ApiTitle    (充值租金)
     * @ApiSummary  (充值租金)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/AddMoney)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", type="integer", required=true, description="订单号")
     * @ApiParams   (name="Money", 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':'返回成功',
    'data':{
    })
     */
    public function AddMoney()
    {
        $UserId = $this->IsToken($this->request->header());
        $OrderSn = input('OrderSn');
        $Money = input('Money');
        $UserInfo = Db::name('user')->where('id', $UserId)->find();
        $PayOrder = $this->PayOrder();
        $domain = $this->request->domain();
        //生成交易流水
        $data = [
            'PayOrder' => $PayOrder,
            'OrderSn' => $OrderSn,
            'type' => 1,
            'status' => 0,
            'user_id' => $UserId,
            'money' => $Money,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $InsertPayOrder = Db::name('pay_order')->insert($data);
        if (!$InsertPayOrder) {
            $this->error('支付订单生成失败', 0);
        }
        $data = [
            'amount' => $Money,
            'orderid' => $PayOrder,
            'type' => "wechat",
            'title' => "充值租金",
            'notifyurl' => $domain . "/api/pay/AddMoneyNotify/paytype/wechat",
            'returnurl' => $domain . "/api/pay/baidu",
            'method' => "miniapp",
            'openid' => $UserInfo['openid']
        ];
        $return = \addons\epay\library\Service::submitOrder($data);
        echo $return;
    }


    /**
     * 订单接口
     * @ApiTitle    (充值租金回调)
     * @ApiSummary  (充值租金回调)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/AddMoneyNotify)
     * @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 AddMoneyNotify()
    {
        $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('pay_order')->where('PayOrder', $order_sn)->find();
            if ($order['status'] == 2) {
                return $pay->success('支付成功');
                die;
            }
            //在此编写订单逻辑
            //修改支付订单状态
            $UpdateStatus = Db::name('pay_order')->where('PayOrder', $data['out_trade_no'])->update(
                [
                    'status' => 1,
                    'updatetime' => time(),
                    'WeChatOrder' => $data['transaction_id']
                ]
            );
            $OrderInfo = Db::name('agreement')->where('OrderSn', $order['OrderSn'])->find();
            $Money = $OrderInfo['Money'] + $order['money'];
            Db::name('agreement')->where('OrderSn', $order['OrderSn'])->update(['Money' => $Money]);
            if (!$UpdateStatus) {
                $this->error('修改支付订单状态失败', 0);
                die;
            }
        } catch (Exception $e) {
        }
        echo $pay->success('支付成功');
    }
}