<?php

namespace App\Handlers;

use App\Models\TradeBill as TradeBillW;
use Illuminate\Console\Command;

class TradeBill extends Command
{

    public function getDownWithdraw($bill_date){
//        $bill_type=$request->input('bill_type');
//        $bill_date=$request->input('bill_date');
//        $tar_type=$request->input('tar_type');
        $url='https://api.mch.weixin.qq.com/v3/bill/tradebill?bill_date='.$bill_date;// .'&bill_type='.$bill_type.'&tar_type='.$tar_type

        $merchant_id=config('wechat.payment.default.mch_id');//商户号
        $serial_no=config('wechat.payment.default.serial_no');//不是平台证书序列号

        $handle=new SignHandler();
        $mch_private_key=$handle->getPublicKey();//读取商户api证书公钥 getPublicKey()获取方法 见下文
        $timestamp=time();//时间戳
        $nonce=$handle->nonce_str();//随机字符串
        $body="";
        $sign=$handle->sign($url,'GET',$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no);//签名
        $header=[
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign,
            'Accept:application/json',
            'User-Agent:' . $merchant_id,
            'Content-Type:application/json',
            'Wechatpay-Serial:' . $handle->getzhengshu()//获取平台证书序列号
        ];
        $result=$handle->curl($url,'',$header,'GET');
        $res=json_decode($result,true);
        $con= $this->down($res['download_url']);

//        return $this->success($con);
    }

    public function down($url){
        $merchant_id=config('wechat.payment.default.mch_id');//商户号
        $serial_no=config('wechat.payment.default.serial_no');//不是平台证书序列号
        $handle=new SignHandler();
        $mch_private_key=$handle->getPublicKey();//读取商户api证书公钥 getPublicKey()获取方法 见下文
        $timestamp=time();//时间戳
        $nonce=$handle->nonce_str();//随机字符串
        $body="";
        $sign=$handle->sign($url,'GET',$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no);//签名
        $header=[
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign,
            'Accept:application/json',
            'User-Agent:' . $merchant_id,
            'Content-Type:application/json',
            'Wechatpay-Serial:' . $handle->getzhengshu()//获取平台证书序列号
        ];

        $result=$handle->curl($url,'',$header,'GET');

        $res = $this->deal_WeChat_response($result);
        $trade_date = $res['bill'][0]['trade_date'];
        $trade_info = TradeBillW::where('trade_date',$trade_date)->first();
        if(!$trade_info){
            if(count($res['bill']) > 1000){
                $arr = array_chunk($res['bill'],1000);
                foreach($arr as $key=>$val){
                    TradeBillW::insert($val);
                }
            }else{
                TradeBillW::insert($res['bill']);
            }
        }
        return $res;
    }

    public function deal_WeChat_response($response){
        $result  = array();
        $response = str_replace(","," ",$response);
        $response = explode(PHP_EOL, $response);
        foreach ($response as $key=>$val){
            if(strpos($val, '`') !== false){
                $data = explode('`', $val);
                array_shift($data); // 删除第一个元素并下标从0开始
                if(count($data) == 27){ // 处理账单数据
                    $result['bill'][] = array(
                        'pay_time'       => $data[0], // 支付时间
                        'app_id'        => $data[1], // app_id
                        'mch_id'        => $data[2], // 商户id
                        'sub_mch_id'        => $data[3], // 特约商户id
                        'imei'         => $data[4], // 设备号
                        'order_sn_wx'     => $data[5], // 微信订单号
                        'order_sn_sh'     => $data[6], // 商户订单号
                        'user_tag'       => $data[7], // 用户标识
                        'pay_type'       => $data[8], // 交易类型
                        'pay_status'      => $data[9], // 交易状态
                        'bank'         => $data[10], // 付款银行
                        'money_type'      => $data[11], // 货币种类
                        'total_amount'     => $data[12], // 应结订单金额
                        'coupon_amount'    => $data[13], // 代金券金额
                        'refund_number_wx'   => $data[14], // 微信退款单号
                        'refund_number_sh'   => $data[15], // 商户退款单号
                        'refund_amount'    => $data[16], // 退款金额
                        'coupon_refund_amount' => $data[17], // 充值券退款退款金额
                        'refund_type'     => $data[18], // 退款类型
                        'refund_status'    => $data[19], // 退款状态
                        'goods_name'      => $data[20], // 商品名称
                        'goods_data_bag'      => $data[21], // 商户数据包
                        'service_charge'    => $data[22], // 手续费
                        'rate'         => $data[23], // 费率
                        'order_account'         => $data[24], // 订单金额
                        'apply_refund_account'         => $data[25], // 申请退款金额
                        'rate_remark'         => $data[26], // 费率备注
                        'trade_date'        => date("Y-m-d", strtotime($data[0]))
                    );
                }
                if(count($data) == 7){ // 统计数据
                    $result['summary'] = array(
                        'order_num'    => $data[0],  // 总交易单数
                        'turnover'    => $data[1],  // 应结订单总金额
                        'refund_turnover' => $data[2],  // 退款总金额
                        'coupon_turnover' => $data[3],  // 充值券退款总金额
                        'rate_turnover'  => $data[4],  // 手续费总金额
                        'order_turnover'  => $data[5],  // 订单总金额
                        'apply_refund_turnover'  => $data[6],  // 申请退款总金额
                    );
                }
            }
        }
        return $result;
    }
}
