<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\business\PaymentBusiness;
use app\common\controller\Api;
use app\common\model\BillModel;
use app\common\model\HotelModel;
use app\common\model\HotelOrderModel;
use app\common\model\HotelRoomModel;
use app\common\model\PayOrderModel;
use app\common\model\UniversityEventModel;
use app\common\model\Wallet;
use app\utils\CurlUtil;
use app\utils\Service\Tencent\TencentIm;
use think\Db;

/**
 * 老年大学 活动板块
 */
class Payment extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * order_no 下级的订单表 订单号
     * order_type 订单来源:hotel_order=酒店订单;hotel_canteen_order=餐厅订单;university_event_apply=活动订单;offline_shop_order=线下订单
     * @return true
     */
    public function page()
    {
        $user_id = $this->auth->id;
        $params = $this->request->param();
        if (empty($params['order_no']) || empty($params['order_type'])) {
            return $this->error('请选择订单');
        }
        $tableName = $params['order_type'];
        $orderNo = $params['order_no'];

        $paymentBusiness = new PaymentBusiness();
        if (!$paymentBusiness->createOrder($user_id,$orderNo,$tableName)){
            return $this->error($paymentBusiness->getMessage(),$paymentBusiness->getData());
        }

        // 支付订单ID
        $bill_id = $paymentBusiness->getData()['bill_id'];

        // 获取用户余额
        $wallet = (new Wallet())->getWallet($user_id);

        return $this->success('获取成功',['bill_id'=>$bill_id,'wallet'=>$wallet]);
    }

    public function submit()
    {
        $user_id = $this->auth->id;
        $params = $this->request->param();
        if (empty($params['bill_id'])) {
            return $this->error('请选择订单');
        }

        if (empty($params['pay_type']) || empty($params['platform'])) {
            return $this->error('请选择支付方式');
        }

        $model = new BillModel();
        $bill = $model->getDetail(['id'=>$params['bill_id']]);
        if (!$bill || $bill['status'] !== 0) {
            return $this->error('订单已支付');
        }

        if (!$model->where('id',$params['bill_id'])->update(['pay_type'=>$params['pay_type'],'platform'=>$params['platform']])){
            return $this->error('操作失败');
        }

        // 拉起支付 余额支付
        $log_type = Wallet::BILL_LOG_TYPE[$bill['table_name']];
        $remark = Wallet::log_type[$log_type];
        if ($params['pay_type'] == 'wallet') {
            Db::startTrans();
            //钱包更新
            $walletService = new Wallet();
            if (!$walletService->change($user_id, -$bill['pay_amount'], 'money', $log_type, $remark, $bill['table_name'], $bill['table_id'])) {
                Db::rollback();
                return $this->error($walletService->getMessage());
            }
            // 支付成功,更改支付状态
            $paymentBusiness = new PaymentBusiness();
            if (!$paymentBusiness->deal($bill['order_no'])){
                Db::rollback();
                return $this->error($paymentBusiness->getMessage());
            }
            Db::commit();
            return $this->success('支付成功');
        }

        // 第三方支付下单
        $params = [
            'type'      => $params['pay_type'],
            'orderid'   => $bill['order_no'],
            'title'     => $remark,
            'amount'    => $bill['pay_amount'],
            'method'    => $params['platform'],
            'notifyurl' => config('pay_notify_url') . "/api/notify/bill/pay_type/{$params['pay_type']}",
            'returnurl' => '',
        ];
        // 如果是小程序则需要添加 openid
        if ($params['pay_type'] == 'wechat' && $params['platform'] == 'miniapp') {
            $params['openid'] = $this->auth->mini_openid;
        }
        $res = Service::submitOrder($params);
        if ($params['pay_type'] == 'wechat') {
            return $this->success('下单成功', json_decode($res, true));
        }
        return $this->success('下单成功', $res);
    }
}