<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\CoinRecord;
use app\api\model\Delivery;
use app\api\model\DeliveryTrade;
use app\api\model\Order;
use app\api\model\Prizerecord;
use app\api\model\RechargeOrder;
use app\common\controller\Frontend;
use think\Db;
use app\api\library\Retail;

/**
 * 支付宝支付接口
 * Class Alipay
 * @package app\api\controller
 * @version 1.0
 * @author fuyelk <fuyelk@fuyelk.com>
 */
class Alipay extends Frontend
{
    protected $noNeedLogin = ['notifyx', 'boxpaysuccess', 'rechargesuccess'];
    protected $noNeedRight = ['*'];

    /**
     * 盲盒订单支付
     * @throws \Exception
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function boxpay($orderid = '')
    {
        if (empty($orderid)) {
            $this->error('订单ID不能为空');
        }

        $order = Order::where('id', $orderid)->where('user_id', $this->auth->id)->where('status', 'unpay')->find();
        if (empty($order)) {
            $this->error('订单有误', '');
        }
      $mny = mt_rand(1,4)/100;
        $coin_price = $order->rmb_amount + $mny;  
        $params = [
            //'amount' => $order->rmb_amount,
             'amount' => $coin_price,
            'orderid' => $order->out_trade_no,
            'type' => "alipay",
            'title' => $order->box_name,
            'notifyurl' => $this->request->domain() . '/api/alipay/notifyx/orderfrom/buybox',
            'returnurl' => $this->request->domain() . '/api/alipay/boxpaysuccess',
            'method' => "wap",
        ];

        $query = input('get.');
        if (isset($query['orderid'])) {
            unset($query['orderid']);
        }
        $this->auth->redis->set($order->out_trade_no, $query, 60 * 30); // 将参数存入缓存，30分钟


//echo 222;
echo \addons\eepay\Service::pay($params);

      //  echo \addons\epay\library\Service::submitOrder($params);
    }

    /**
     * 充值订单支付
     * @throws \Exception
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function rechargepay($orderid = '')
    {
        if (empty($orderid)) {
            $this->error('订单ID不能为空');
        }

        $order = RechargeOrder::where('id', $orderid)->where('user_id', $this->auth->id)->where('status', 'unpay')->find();
        if (empty($order)) {
            $this->error('订单有误', '');
        }
 $mny = mt_rand(1,4)/100;
        $coin_price = $order->rmb_amount + $mny;  
        $params = [
            'amount' => $coin_price,
            'orderid' => $order->out_trade_no,
            'type' => "alipay",
            'title' => '充值',
            'notifyurl' => $this->request->domain() . '/api/alipay/notifyx/orderfrom/recharge',
            'returnurl' => $this->request->domain() . '/api/alipay/rechargesuccess',
            'method' => "wap",
        ];

        $query = input('get.');
        if (isset($query['orderid'])) {
            unset($query['orderid']);
        }
        $this->auth->redis->set($order->out_trade_no, $query, 60 * 30); // 将参数存入缓存，30分钟


//print_r($params);


echo \addons\eepay\Service::payssss($params);

     //   echo \addons\epay\library\Service::submitOrder($params);
    }

    /**
     * 发货订单支付
     * @throws \Exception
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function deliverypay($orderid = '')
    {
        if (empty($orderid)) {
            $this->error('订单ID不能为空');
        }

        $order = DeliveryTrade::where('id', $orderid)->where('user_id', $this->auth->id)->where('status', 'unpay')->find();
        if (empty($order)) {
            $this->error('订单有误', '');
        }
        $mny = mt_rand(1,4)/100;
        $coin_price = $order->rmb_amount + $mny;  
        $params = [
            'amount' => $order->rmb_amount,
            'orderid' => $order->out_trade_no,
            'type' => "alipay",
            'title' => '快递费用',
            'notifyurl' => $this->request->domain() . '/api/alipay/notifyx/orderfrom/delivery',
            'returnurl' => $this->request->domain() . '/api/alipay/deliverypaysuccess',
            'method' => "wap",
        ];

        $query = input('get.');
        if (isset($query['orderid'])) {
            unset($query['orderid']);
        }
        $this->auth->redis->set($order->out_trade_no, $query, 60 * 30); // 将参数存入缓存，30分钟

      //  echo \addons\epay\library\Service::submitOrder($params);
      
      
     echo \addons\eepay\Service::payfh($params);
 
    }

    /**
     * 盲盒、充值支付回调
     */
    public function notifyx($orderfrom = '')
    {
        // 回调只能来自于购买盲盒和充值
        if (!in_array($orderfrom, ['buybox', 'recharge', 'delivery'])) {
            dta(input(), '支付宝回调有误');
            echo '请求有误';
            return;
        }
file_put_contents('./1.txt','wjinlaile');
        $pay = Service::checkNotify('alipay');
        if (!$pay) {
            dta('支付宝签名错误', __METHOD__ . ' ' . __LINE__);
            echo '签名错误';
            return;
        }

        Db::startTrans();
file_put_contents('./2.txt',json_encode($pay));
        try {
            $data = $pay->verify()->toArray();
            $usefulTemplate = array(
                'invoice_amount' => '12.34',
                'trade_status' => 'TRADE_SUCCESS',
                'receipt_amount' => '12.34',
                'buyer_pay_amount' => '12.34',
                'notify_time' => '2021-07-16 14:40:39',
                'out_trade_no' => '20210716144024',
                'total_amount' => '12.34',
                'trade_no' => '2021071622001413960501380461',
            );
file_put_contents('./3.txt',json_encode($data));
            if ('TRADE_SUCCESS' != strtoupper($data['trade_status'])) {
                dta(array_intersect_key($data, $usefulTemplate), '支付宝支付失败');
                echo '支付失败';
                return;
            }

            // 购买盲盒订单，更新盲盒订单
            if ('buybox' == $orderfrom) {
                $order = Order::where('out_trade_no', $data['out_trade_no'])->where('status', 'unpay')->find();
                if (empty($order)) {
                    dta(array_intersect_key($data, $usefulTemplate), '订单有误，支付失败');
                    echo '支付失败';
                    return;
                }
                $order->save([
                    'pay_method' => 'alipay',
                    'pay_rmb' => $data['total_amount'],
                    'alipay_trade_no' => $data['trade_no'],
                    'pay_time' => time(),
                    'status' => 'unused',
                    'backend_read' => 0,
                ]);
            }

            // 充值订单
            if ('recharge' == $orderfrom) {
                $order = RechargeOrder::where('out_trade_no', $data['out_trade_no'])->where('status', 'unpay')->find();
                if (empty($order)) {
                    dta(array_intersect_key($data, $usefulTemplate), '订单有误，支付失败');
                    echo '支付失败';
                    return;
                }

                $order->save([
                    'pay_method' => 'alipay',
                    'pay_rmb' => $data['total_amount'],
                    'alipay_trade_no' => $data['trade_no'],
                    'pay_time' => time(),
                    'status' => 'paid',
                    'backend_read' => 0,
                ]);

                $user = \app\common\model\User::where('id', $order->user_id)->find();

                // 给账户充值前
                $coin_before = $user->coin;

                // 增加金币余额
                $user->setInc('coin', $order->coin_amount);

                // 创建金币记录
                CoinRecord::create([
                    'user_id' => $user->id,
                    'before' => $coin_before,
                    'after' => $user->coin,
                    'coin' => $order->coin_amount,
                    'order_id' => $order->id,
                    'type' => 'recharge', // 变更类型:pay_box=支付盲盒,recharge=充值,fromwallet=余额转入,refund=退款
                ]);

               
            }

            // 发货订单
            if ('delivery' == $orderfrom) {
                $trade = DeliveryTrade::where('out_trade_no', $data['out_trade_no'])->where('status', 'unpay')->find();
                if (empty($trade)) {
                    dta(array_intersect_key($data, $usefulTemplate), '订单有误，支付失败');
                    echo '支付失败';
                    return;
                }

                // 变更发货交易订单状态
                $trade->save([
                    'pay_method' => 'alipay',
                    'pay_rmb' => $data['total_amount'],
                    'alipay_trade_no' => $data['trade_no'],
                    'pay_time' => time(),
                    'status' => 'paid'
                ]);

                // 变更发货订单状态
                $deliveryOrder = Delivery::where('delivery_trade_id', $trade->id)->select();
                $prizeIds = [];
                foreach ($deliveryOrder as $order) {
                    $order->save(['status' => 'undelivered']);
                    $prizeIds[] = $order->prize_id;
                }

                // 变更奖品状态
                Prizerecord::whereIn('id', $prizeIds)->update(['status' => 'delivery', 'delivery_time' => time()]);
            }

        } catch (\Exception $e) {
            Db::rollback();
            dta($e->getMessage(), '支付宝回调执行出错');
            echo '错误';
            return;
        }
        Db::commit();
        echo $pay->success();
    }

    /**
     * 盲盒支付成功后用户会被重定向到这里
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function boxpaysuccess()
    {
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn('alipay');

        // 读取缓存里的参数
        $query = $this->auth->redis->get($out_trade_no);
        if (!$query || !is_array($query)) {
            $query = [];
        }
        $query['status'] = 1;

        if (!$pay) {
            $query['status'] = 0;
        }

        $query['out_trade_no'] = $out_trade_no;
        $params = http_build_query($query);

        // 将用户重定向到前端页面
        $this->redirect($this->request->domain() . "/h5/#/pagesA/pages/camera?" . $params);
    }

    /**
     * 充值支付成功后用户会被重定向到这里
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function rechargesuccess()
    {
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn('alipay');

        // 读取缓存里的参数
        $query = $this->auth->redis->get($out_trade_no);
        if (!$query || !is_array($query)) {
            $query = [];
        }
        $query['status'] = 1;

        if (!$pay) {
            $query['status'] = 0;
        }

        $params = http_build_query($query);

        // 将用户重定向到前端页面
        $this->redirect($this->request->domain() . "/h5/#/pages/me/wallet?" . $params);
    }

    /**
     * 发货订单支付成功后用户会被重定向到这里
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function deliverypaysuccess()
    {
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn('alipay');

        // 读取缓存里的参数
        $query = $this->auth->redis->get($out_trade_no);
        if (!$query || !is_array($query)) {
            $query = [];
        }
        $query['status'] = 1;

        if (!$pay) {
            $query['status'] = 0;
        }

        $params = http_build_query($query);

        // 将用户重定向到前端页面
        $this->redirect($this->request->domain() . "/h5/#/pages/me/order?type=0?" . $params);
    }
}