<?php

namespace App\Http\Controllers\API\H5;

use App\Http\Controllers\API\XCXApiController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PayController extends Controller
{
  //支付回调.弃用！！！！
  public function Notify()
  {
    $order_num = request('order_num');
    $status = request('status');
    $pay_info = request('pay_info');
    if (!isset($order_num)) return \Yz::echoError1("订单号不能为空");
    $order = DB::table('orders')->where(['order_number' => $order_num])->first();
    if (!$order) return \Yz::echoError1("订单不存在");
    if ($status == 'SUCCESS') {
      $u = DB::table('orders')->where(['order_number' => $order_num])->update([
        'status' => 2
      ]);
      if ($u) {
        return \Yz::Return(true, "更新成功", ['order_num' => $order_num]);
      }
    }

  }

  public function StartPay()
  {
    $id = request('id');
    $orderInfo = DB::table('orders')->where(['id' => $id,])->first();
    if (!$orderInfo) return \Yz::echoError1("未找到有效订单");
    if ($orderInfo->status !== 1) return \Yz::echoError1("订单不是待支付状态不能支付。当前状态:" . $orderInfo->status);
    $personInfo = DB::table('web_user_person')->where(['id' => $orderInfo->person_id, 'is_del' => 0])->first();
    if (!$personInfo) return \Yz::echoError1("就诊人异常");

    $params = [
      'appId' => "1111111111111111",
      'ghzid' => $personInfo->ghzid,
      'orderid' => $orderInfo->order_number,
      'order_desc' => $orderInfo->title,
      'amount' => $orderInfo->true_price * 100,
      'timestamp' => (string)time(),
      'nonce' => self::nonce(),
    ];
  //签名规则?
    $params['sign'] = '';
    $params['notify_url'] = '';
    $XCX = new XCXApiController();
    $data = $XCX::Post('订单支付', $params);
  }

  //订单支付查询
  public function CheckPay()
  {
    $order_number= request('order_number');
    $XCX = new XCXApiController();
    $data = $XCX::Post('订单查询', ['orderid'=>$order_number]);
    //判断如果支付成功，更改订单状态
    if($data['trade_state']==='SUCCESS'){
      DB::table('orders')->where(['order_number'=>$order_number])->update([
        'status'=>2
      ]);
    }
  }
  //退款
  public function Refund()
  {
    $order_number= request('order_number');
  }

  public static function nonce($l = 16)
  {
    $charts = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789";
    $max = strlen($charts) - 1;
    $noncestr = "";
    for ($i = 0; $i < $l; $i++) {
      $noncestr .= $charts[rand(0, $max)];
    }
    return $noncestr;
  }
}
