<?php

namespace app\business;

use Illuminate\Support\Arr;
use support\Db;
use support\Redis;
use Throwable;
use yzh52521\EasyHttp\Http;

class PayFourBusiness
{


    static private $url      = "http://ximen-api.zhangsan16688.com/api/order";
    static private $apikey   = 'etn94hsTDv07h7Yw0VXRNcp8VQz9442C';
    static private $memberid = 600569;

    /**
     * @param array $param [
     * order_no
     * ]
     * @return array
     */
    static public function payment($order_no, $pay_bankcode, $money, $url = '')
    {
        if (empty($url)) {
            $url = getenv('WEB_HOST');
        }
        $arr              = [
            'amount'      => $money,//金额，单位为元，精确到小数点后两位
            'outOrderNum' => $order_no,//商户订单号
            'mchNum'      => self::$memberid,//商户号
            'payType'     => $pay_bankcode,//通道类型
            'timestamp'   => time(),//发送请求的时间戳
            'notifyUrl'   => getenv('API_HOST') . '/api/pay/payment_callback_four.html',//异步通知地址，支付成功后将支付成功消息以POST请求发送给这个网址
        ];
        $arr['sign']      = self::payMd5sign($arr);
        $arr['returnUrl'] = $url;
        $data             = Http::post(self::$url, $arr)->array();
        return ['data' => $data, 'arr' => $arr];
    }

    static public function payMd5sign(array $param)
    {
        /* @对数组键进行ASCII码排序*/
        ksort($param);
        $arr = [];
        //将数组进行重组装

        foreach ($param as $k => $v) {
            if (!empty($v)) {
                $arr[] = $k . '=' . $v;
            }
        }
        //转换成字符串并且拼接上密钥
        $sign = implode('&', $arr) . '&key=' . self::$apikey;

        return strtoupper(md5($sign));

    }

    /** 生成订单号
     * @param array $param
     * @return int
     * @throws \Exception
     */
    static public function orderAdd(array $param)
    {
        try {
            $goods = Db::table('wa_goods')->where('id', $param['id'])->first();
            if (empty($goods)) {
                throw new \Exception('产品不存在!');
            }
            $payAisleData = Db::table('wa_pay_aisle')->where('characteristic', $param['pay_characteristic'])->first();
            if (empty($payAisleData)) {
                throw new \Exception('支付类型不存在!');
            }
            $characteristic = $payAisleData->characteristic;
            $pay_type       = $payAisleData->type;
            $order_no       = date('YmdHis') . mt_rand(1000, 9999);
            $payorderId     = Db::table('wa_payorder')->insertGetId([
                'goods_id'           => $goods->id,
                'goods_type'         => $goods->type,
                'user_id'            => $param['user_data']['id'],
                'order_no'           => $order_no,
                'pay_characteristic' => $characteristic,
                'pay_type'           => $pay_type,
                'money'              => bcmul($goods->pay_price, $param['num'], 2),
                'num'                => $param['num'],
                'name'               => Arr::get($param, 'name', null),
                'mobile'             => Arr::get($param, 'mobile', null),
                'number'             => Arr::get($param, 'number', null),
                'address'            => Arr::get($param, 'address', null),
                'created_at'         => date('Y-m-d H:i:s'),
                'updated_at'         => date('Y-m-d H:i:s'),
            ]);

        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return $payorderId;
    }

    /** 开通银行卡生成订单号
     * @param array $param
     * @return int
     * @throws \Exception
     */
    static public function CardorderAdd(array $param)
    {
        try {
            $goods = Db::table('wa_goods')->where('id', $param['id'])->first();
            if (empty($goods)) {
                throw new \Exception('产品不存在!');
            }
            $price_money = bcmul($goods->pay_price, $param['num']);
            if ($param['user_data']['money_one'] < $price_money) {
                throw new \Exception('华润财富余额不足!');
            }
            $payorderId = Db::table('wa_payorder')->insertGetId([
                'goods_id'           => $goods->id,
                'goods_type'         => $goods->type,
                'user_id'            => $param['user_data']['id'],
                'order_no'           => date('YmdHis') . mt_rand(1000, 9999),
                'pay_characteristic' => 0,
                'pay_type'           => 0,
                'is_pay'             => 2,
                'money'              => $price_money,
                'num'                => 1,
                'created_at'         => date('Y-m-d H:i:s'),
                'updated_at'         => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return $payorderId;
    }

    /**提现
     * @return void
     */
    static public function tx_withdraw($param, $service_charge = '')
    {
        try {

            $payAisleData = Db::table('wa_pay_aisle')->where('characteristic', $param['pay_characteristic'])->first();
            if (empty($payAisleData)) {
                throw new \Exception('支付类型不存在!');
            }
            $payorderId = Db::table('wa_payorder')->insertGetId([
                'goods_type'         => 1001,
                'user_id'            => $param['user_data']['id'],
                'order_no'           => date('YmdHis') . mt_rand(1000, 9999),
                'pay_characteristic' => $payAisleData->characteristic,
                'pay_type'           => $payAisleData->type,
                'money'              => bcmul($param['money'], $service_charge, 2),
                'withdraw_money'     => $param['money'],
                'mold_type'          => $param['mold'],
                'created_at'         => date('Y-m-d H:i:s'),
                'updated_at'         => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return $payorderId;
    }

    /** 购买原始股
     * @param $num
     * @param $user_id
     * @param $pay_characteristic
     * @return int
     * @throws \Exception
     */
    static public function orderAddInitialShare($num, $user_id, $pay_characteristic)
    {
        try {
            $wa_system    = Db::table('wa_system')->first();
            $payAisleData = Db::table('wa_pay_aisle')->where('characteristic', $pay_characteristic)->first();
            if (empty($payAisleData)) {
                throw new \Exception('支付类型不存在!');
            }

            $payorderId = Db::table('wa_payorder')->insertGetId([
                'goods_id'           => 0,
                'goods_type'         => 10,
                'user_id'            => $user_id,
                'order_no'           => date('YmdHis') . mt_rand(1000, 9999),
                'pay_characteristic' => $payAisleData->characteristic,
                'pay_type'           => $payAisleData->type,
                'money'              => bcmul($wa_system->money_five_value, $num, 2),
                'num'                => $num,
                'created_at'         => date('Y-m-d H:i:s'),
                'updated_at'         => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return $payorderId;
    }

    /** 提现回调
     * @param $data
     * @return void
     * @throws \Exception
     */
    static public function payorderJkjtx($data)
    {

        try {
            /** @var  $bankCard  银行卡 */
            $bankCard = Db::table('wa_bank_card')->where('uid', $data['user_id'])->first();

            $withdrawId = Db::table('wa_withdraw')->insertGetId([
                'order_no'        => date('YmdHis') . mt_rand(10000, 99999),
                'user_id'         => $data['user_id'],
                'money'           => $data['withdraw_money'],
                'type'            => $data['mold_type'],
                'affiliated_bank' => $bankCard->affiliated_bank,
                'account_holder'  => $bankCard->account_holder,
                'card_number'     => $bankCard->card_number,
                'created_at'      => date('Y-m-d H:i:s'),
                'updated_at'      => date('Y-m-d H:i:s'),
            ]);

            StreamBusiness::delStream($data['user_id'], $data['withdraw_money'], streamType4, $data['mold_type'], moldTypefild($data['mold_type']), $withdrawId);
        } catch (Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }

    }

    /** 支付回调
     * @param $orderNo
     * @return void
     */
    static public function paymentCallback($orderNo)
    {
        try {
            $payorder = Db::table('wa_payorder')->where('order_no', $orderNo)->first();
            if ($payorder->is_pay != 1) {
                throw new \Exception('订单已处理!');
            }
            self::payorderSave(collect($payorder)->toArray());

        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return true;
    }

    /** 购买原始股权回调
     * @param $data
     * @return void
     */
//    static public function goodsStockRights($data)
//    {
//        try {
//            $goodsData=Db::table('wa_goods')->where('id',$data['goods_id'])->first();
//            $thisDay=date('Y-m-d H:i:s');
//            /** @var  $futureDay  未来时间*/
//            $futureDay=futureDay(1095);
//
//            $myGoodsId=Db::table('wa_my_goods')->insertGetId([
//                'user_id'       =>  $data['user_id'],
//                'goods_id'      =>  $goodsData->id,
//                'money'         =>  $data['money'],
//                'on'            =>  date('YmdHis').mt_rand(1000,9999),
//                'type'          =>  $goodsData->type,
//                'pay_id'        =>  $data['id'],
//                'stock_rights'  =>  $goodsData->stock_rights,
//                'unit_price'    =>  $goodsData->unit_price,
//                'refund_amount' =>  $data['money'],
//                'expiretime'    =>  strtotime($futureDay),
//                'expiredate'    =>  $futureDay,
//                'created_at'    =>  $thisDay,
//                'updated_at'    =>  $thisDay
//            ]);
//
//
////            StreamBusiness::addStream($data['user_id'],bcmul($goodsData->stock_rights,$goodsData->unit_price,2),streamType5,moldType4,moldTypefild(moldType4),$data['id']);
//
//            $usersData=Db::table('wa_users')->where('id',$data['user_id'])->first();
//            $system=Db::table('wa_system')->first();
//            if(!empty($usersData->pid) && !empty($system->rebate)){
//                StreamBusiness::addStream($usersData->pid,$system->rebate,streamType10,moldType4,moldTypefild4,$data['id']);
//            }
//            if(!empty($usersData->ppid) && !empty($system->rebate_one)){
//                StreamBusiness::addStream($usersData->ppid,$system->rebate_one,streamType10,moldType4,moldTypefild4,$data['id']);
//            }
//
//            if(!empty($usersData->toppid) && !empty($system->rebate_two)){
//                StreamBusiness::addStream($usersData->toppid,$system->rebate_two,streamType10,moldType4,moldTypefild4,$data['id']);
//            }
//
//            /** 新增消费数据 */
//            Db::table('wa_users')->where('id',$data['user_id'])->increment('invest_money',$data['money']);
//
//            Db::table('wa_goods')->where('id',$goodsData->id)->decrement('num',1);
//
//        }catch (\Throwable $exception){
//            throw new \Exception($exception->getMessage());
//        }
//    }

    /** 订单回调处理
     * @param $data 订单信息
     * @return void
     */
    static public function payorderSave($data)
    {
        try {
            self::payorderGoods($data);
            Db::table('wa_payorder')->where('id', $data['id'])->update([
                'is_pay'     => 2,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
        return true;
    }

    /** 商品回调
     * @param $data
     * @return void
     * @throws \Exception
     */
    static public function payorderGoods($data)
    {
        try {
            $goodsData = Db::table('wa_goods')->where('id', $data['goods_id'])->first();
            $thisDay   = date('Y-m-d H:i:s');
            /** @var  $futureDay  未来时间 */
            $futureDay = futureDay(1095);
            $myGoodsId = Db::table('wa_my_goods')->insertGetId([
                'user_id'       => $data['user_id'],
                'goods_id'      => $goodsData->id,
                'money'         => $data['money'],
                'num'           => $data['num'],
                'on'            => date('YmdHis') . mt_rand(1000, 9999),
                'type'          => $goodsData->type,
                'pay_id'        => $data['id'],
                'bonus'         => $goodsData->bonus,
                'refund_amount' => $data['money'],
                'name'          => Arr::get($data, 'name', null),
                'mobile'        => Arr::get($data, 'mobile', null),
                'number'        => Arr::get($data, 'number', null),
                'address'       => Arr::get($data, 'address', null),
                'expiretime'    => strtotime($futureDay),
                'expiredate'    => $futureDay,
                'created_at'    => $thisDay,
                'updated_at'    => $thisDay,
            ]);
            $userlist  = Db::table('wa_users')->where('id', $data['user_id'])->first();

//            if (!empty($goodsData->bonus)) {
//                Db::table('wa_cron_task')->insert([
//                    'user_id'           => $data['user_id'],
//                    'goods_id'          => $goodsData->id,
//                    'order_id'          => $data['id'],
//                    'money'             => $data['money'],
//                    'bonus'             => $goodsData->bonus,
//                    'goods_type'        => $goodsData->type,
//                    'day_dividend_time' => strtotime(date('Y-m-d', strtotime('+1 days')) . ' 08:00:00'),
//                    'dividend_time'     => strtotime($futureDay),
//                    'created_at'        => $thisDay,
//                    'updated_at'        => $thisDay,
//                    'my_good_id'        => $myGoodsId,
//                ]);
//                StreamBusiness::addStream($data['user_id'], $goodsData->bonus, streamType9, moldType5, moldTypefild5, $data['id']);
//            }
            if (!empty($goodsData->balance)) {
                StreamBusiness::addStream($data['user_id'], $goodsData->balance, streamType9, moldType3, moldTypefild3, $data['id']);
            }
            /** 新增消费数据 */
            Db::table('wa_users')->where('id', $data['user_id'])->increment('invest_money', $data['money']);
            Db::table('wa_goods')->where('id', $goodsData->id)->decrement('num', $data['num']);

            /** 分佣 */
//                $user   = Db::table('wa_users')->where('id', $data['user_id'])->first();
//                $system = Db::table('wa_system')->first();
//                if (!empty($user->pid) && !empty($system->rebate)) {
//                    StreamBusiness::addStream($user->pid, bcmul($goodsData->pay_price, bcdiv($system->rebate, 100, 2), 2), streamType10, moldType7, moldTypefild7, $data['id']);
//                }
//                if (!empty($user->ppid) && !empty($system->rebate_one)) {
//                    StreamBusiness::addStream($user->ppid, bcmul($goodsData->pay_price, bcdiv($system->rebate_one, 100, 2), 2), streamType10, moldType7, moldTypefild7, $data['id']);
//                }
//
//                if (!empty($user->toppid) && !empty($system->rebate_two)) {
//                    StreamBusiness::addStream($user->toppid, bcmul($goodsData->pay_price, bcdiv($system->rebate_two, 100, 2), 2), streamType10, moldType7, moldTypefild7, $data['id']);
//                }


        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /** 国债订单回调处理
     * @param $data 订单信息
     * @return void
     */
    static public function CardpayorderSave($data)
    {

        try {
            $goodsData = Db::table('wa_goods')->where('id', $data['goods_id'])->first();
            $thisDay   = date('Y-m-d H:i:s');
            /** @var  $futureDay  未来时间 */
            $futureDay = futureDay(1095);
            $myGoodsId = Db::table('wa_my_goods')->insertGetId([
                'user_id'       => $data['user_id'],
                'goods_id'      => $goodsData->id,
                'money'         => $data['money'],
                'num'           => $data['num'],
                'on'            => date('YmdHis') . mt_rand(1000, 9999),
                'type'          => $goodsData->type,
                'pay_id'        => $data['id'],
                'bonus'         => $goodsData->bonus,
                'refund_amount' => $data['money'],
                'expiretime'    => strtotime($futureDay),
                'expiredate'    => $futureDay,
                'created_at'    => $thisDay,
                'updated_at'    => $thisDay,
            ]);

            if (!empty($goodsData->bonus)) {
                Db::table('wa_cron_task')->insert([
                    'user_id'           => $data['user_id'],
                    'goods_id'          => $goodsData->id,
                    'order_id'          => $data['id'],
                    'money'             => $data['money'],
                    'bonus'             => $goodsData->bonus,
                    'goods_type'        => $goodsData->type,
                    'day_dividend_time' => strtotime(date('Y-m-d', strtotime('+1 days')) . ' 00:10:00'),
                    'dividend_time'     => strtotime($futureDay),
                    'created_at'        => $thisDay,
                    'updated_at'        => $thisDay,
                    'my_good_id'        => $myGoodsId,
                ]);
                StreamBusiness::addStream($data['user_id'], $goodsData->bonus, streamType14, moldType1, moldTypefild1, $data['id']);
            }

            StreamBusiness::delStream($data['user_id'], $data['money'], streamType17, moldType2, moldTypefild2, $data['id']);
            Db::table('wa_goods')->where('id', $goodsData->id)->decrement('num', $data['num']);

        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }


}