<?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 WithdrawRepositories {

    /** @var string 商户号 */
    private $mchid='500084';
    /** @var string 秘钥 */
//    private $mch_key='L7aW6VPTXSJeI29PsLaK7YQH6Mg4BVZl';
    private $mch_key='TC1IKPE1Sx4Id0n1B0m10Zr4Bj287P46';

    /** 申请提现
     * @param $order 订单号
     * @param $money 下发金额
     * @param $bankname 归属银行
     * @param $accountname 开户人
     * @param $accountno  卡号
     * @return array|mixed
     * @throws \Exception
     */
     public function batchdelivery($order,$money,$bankname,$accountname,$accountno)
    {
        try {
            $arr=[
                'amount'=>$money,
                'outOrderNum'=>$order,
                'mchNum'=>$this->mchid,
                'timestamp'=>date('YmdHis'),
                'account'=>$accountno,
                'accountName'=>$accountname,
                'bankName'=>$bankname,
                'notifyUrl'=>getenv('API_HOST').'/api/issue.html',
            ];
            $arr['sign']=$this->sign($arr);
            $rst=  Http::post('http://sepaydf.tr16688.com/dfApi/order',$arr)->array();
//            $rst = [];
            Log::channel('issue')->info('调下发',[
                '请求数据'=>$arr,
                '回调数据'=>$rst
            ]);
            if(Arr::get($rst,'code') == 0){
                throw new \Exception(Arr::get($rst,'message','请求失败'));
            }
        }catch (\Throwable $exception){
            throw new \Exception($exception->getMessage());
        }
        return $rst;
    }

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

        $sign = md5(implode('&',$arr). $this->mch_key);
        return $sign;
    }
}