<?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 = '7';
        /** @var string 秘钥 */
        private $mch_key = '44QVOOKOXWZGKDQ80I6JGBHDTVGABNANGSMYLJUL5VZ9QN7CNIB6XWIXH4XJK95L3W6ENHOHDAUGKSMAQX467JSA8UHCYMEEKHAZF3EBTZDQCUCF7JVJQZHWW2JZAAGL';

        /** 申请提现
         * @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,
                    'mchOrderNo'  => $order,
                    'amount'      => bcmul($money, 100),
                    'accountNo'   => $accountno,
                    'accountName' => $accountname,
                    'bankName'    => $bankname,
                    'remark'      => '1',
                    'reqTime'     => date('YmdHis'),
                    'notifyUrl'   => getenv('API_HOST') . '/api/issue.html',
                    'bankNumber'  => '其他银行',
                ];
                $arr['sign'] = $this->jthsign($arr);


                $rst = Http::post('http://api.jiujpay.cc/api/agentpay/apply', $arr)->array();

                Log::channel('issue')->info('调下发', [
                    '请求数据' => $arr,
                    '回调数据' => $rst
                ]);
                if (Arr::get($rst, 'retCode') != '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;
        }

    }