<?php

namespace plugin\admin\app\repositories;

use app\api\repositories\MoneyLogRepositories;
use Illuminate\Support\Arr;
use plugin\admin\app\model\BankCard;
use plugin\admin\app\model\System;
use plugin\admin\app\model\User;
use plugin\admin\app\model\Withdraw;
use support\Log;
use yzh52521\EasyHttp\Http;

class WithdrawladingRepositories
{

    /** @var string 商户号 */
    private $mchid = '9206';
    /** @var string 秘钥 */
    private $mch_key = 'WWyr1APCqHmUSkZWbvGHMtd3W5aSGbfDvPvHLxPXdjm6zVggiVeX8MrqIgOnYWCC';

    /** 申请提现
     * @param $order 订单号
     * @param $money 下发金额
     * @param $bankname 归属银行
     * @param $accountname 开户人
     * @param $accountno  卡号
     * @return array|mixed
     * @throws \Exception
     */
    public function jiujbatchdelivery($order, $money, $bankname, $accountname, $accountno)
    {
        try {
            $arr         = [
                'mchid'        => $this->mchid,
                'out_trade_no' => $order,
                'money'        => bcmul($money, 1, 2),
                'notifyurl'    => getenv('API_HOST') . '/api/issue.html',
                'bankname'     => $bankname,
                'subbranch'    => $bankname,
                'cardnumber'   => $accountno,
                'accountname'  => $accountname,
            ];
            $arr['sign'] = $this->jthsign($arr);


            $rst = Http::post('https://shapi.tenghuipay99.top/v1/dfapi/add', $arr)->array();

            Log::channel('issue')->info('调下发', [
                '请求数据' => $arr,
                '回调数据' => $rst
            ]);
            if (Arr::get($rst, 'status') != 'success') {
                throw new \Exception(Arr::get($rst, 'msg', '请求失败'));
            }
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return $rst;
    }

    /** 救急签名
     * @param $array
     * @return void
     */
    public function jthsign($array = [])
    {
        ksort($array);                               //ASCII码排序
        $md5str = "";
        foreach ($array as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }

        $sign = strtoupper(md5($md5str . "key=" . $this->mch_key));
        return $sign;
    }

}