<?php

namespace App\Handlers;

use App\Models\ProfitSharing as ProfitSharingW;
use Illuminate\Console\Command;

class ProfitSharing extends Command
{

    public function getprofitsharing($bill_date){
//        $bill_date=$request->input('bill_date');
//        $sub_mchid=$request->input('sub_mchid');
//        $tar_type=$request->input('tar_type');
        $url='https://api.mch.weixin.qq.com/v3/profitsharing/bills?bill_date='.$bill_date;// .'&account_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'],'sharing');
//        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_profit_sharing($result);
        $sharing_date = $res['sharing'][0]['sharing_date'];
        $sharing_info = ProfitSharingW::where('sharing_date',$sharing_date)->first();
        if(!$sharing_info){
            if(count($res['sharing']) > 1000){
                $arr = array_chunk($res['sharing'],1000);
                foreach($arr as $key=>$val){
                    ProfitSharingW::insert($val);
                }
            }else{
                ProfitSharingW::insert($res['sharing']);
            }
        }
        return $res;
    }

    public function deal_profit_sharing($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) == 9) { // 处理账单数据
                    $result['sharing'][] = array(
                        'sharing_time'       => $data[0], // 分账时间
                        'sharing_originator'        => $data[1], // 分账发起方
                        'sharing_user'        => $data[2], // 分账方
                        'wx_order_no'      => $data[3], // 微信订单号
                        'wx_refund_no'         => $data[4], // 微信分账方/回退单号
                        'sharing_detail_no'     => $data[5], // 分账明细单号
                        'mch_refund_no'     => $data[6], // 商户分账/回退单号
                        'order_amount'       => $data[7], // 订单金额
                        'sharing_recipient'       => explode(' ',$data[8])[0], // 分账接收方
                        'amount'      => explode(' ',$data[8])[1], // 金额
                        'sharing_type'         => explode(' ',$data[8])[2], // 业务类型
                        'sharing_status'      => explode(' ',$data[8])[3], // 处理状态
                        'sharing_desc'     => explode(' ',$data[8])[4], // 分账描述
                        'remark'    => explode(' ',$data[8])[5], // 备注
                        'sharing_date'   => date("Y-m-d", strtotime($data[0])), // 分账日期
                    );
                }
                if(count($data) == 5){ // 统计数据
                    $result['summary'] = array(
                        'sharing_num'    => $data[0],  // 总条数
                        'sharing_success_amount'    => $data[1],  // 分账成功出资金
                        'sharing_fail_turnover' => $data[2],  // 分账失败已转回分账方
                        'thaw_funds_amount' => $data[3],  // 解冻资金给分账方
                        'refund_amount'  => $data[4],  // 分账回退资金
                    );
                }
            }
        }
        return $result;
    }
}
