<?php

namespace App\Http\Controllers\Mounting\Business;

use Illuminate\Http\Request;
use DB;
use App\Services\LoginUserService;

use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use Yansongda\LaravelPay\Facades\Pay;
use App\Http\Models\Services\Order;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use App\Services\Business\WashPayservice;
use WechatPay\GuzzleMiddleware\Util\MediaUtil;
use GuzzleHttp\Exception\RequestException;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use App\Http\Models\Api\Common;

class PayController extends Controller
{
    // 商户号 1619735999 
    protected $mchid = '1643850123';
    protected $appid = 'wx5a9e016f8ebb40c7';
    // protected $apiKey = 'a92d64dd5fcf2d72cd12df9aeb9c7a5a';
    protected $apiKey = '43424c7e0ddb071d42b783216d8f09cc';
    public $dataService = null;

    public function __construct()
    {
        // $this->dataService = $service = new WashPayservice();
        // $this->bootWithService($service);
    }

    public function addAccount(Request $request)
    {
        $url = 'https://api.mch.weixin.qq.com/v3/ecommerce/applyments/';
        // $request_json = json_decode($request['json_data']);
        $request_json['out_request_no'] = $request['out_request_no'];//业务申请编号
        $request_json['organization_type'] = $request['organization_type'];//主体类型
        // 营业执照信息 主体为“个体工商户/企业”时，请上传营业执照
        if ($request['organization_type'] == 2) {
        	$request_json['business_license_info']['business_license_copy'] = $request['business_license_copy'];//营业执照
        	$request_json['business_license_info']['business_license_number'] = $request['business_license_number'];//注册号
        	$request_json['business_license_info']['merchant_name'] = $request['merchant_name'];//商户名称
        	$request_json['business_license_info']['legal_person'] = $request['legal_person'];//法人
        	$request_json['business_license_info']['company_address'] = $request['company_address'];//注册地址
        	$request_json['business_license_info']['business_time'] = $request['business_time'];//营业期限
        }

        $request_json['id_doc_type'] = $request['id_doc_type'];//经营者/法人证件类型
        $request_json['id_card_info']['id_card_copy'] = $request['id_card_copy'];//身份证人像面照片
        $request_json['id_card_info']['id_card_national'] = $request['id_card_national'];//身份证国徽面照片
        $request_json['id_card_info']['id_card_name'] = $request['id_card_name'];//身份证姓名
        $request_json['id_card_info']['id_card_number'] = $request['id_card_number'];//身份证号
        $request_json['id_card_info']['id_card_address'] = $request['id_card_address'];//身份证地址
        $request_json['id_card_info']['id_card_valid_time_begin'] = $request['id_card_valid_time_begin'];//身份证开始时间
        $request_json['id_card_info']['id_card_valid_time'] = $request['id_card_valid_time'];//身份证结束时间


        $request_json['owner'] = true;//若经营者/法人是最终受益人，则填写：true
        // $request_json['need_account_info'] = true;//是否填写结算账户信息
        $request_json['contact_info'] = $request['contact_info'];//超级管理员信息
        $request_json['contact_info']['contact_type'] = $request['contact_type'];//超级管理员类型
        $request_json['contact_info']['contact_name'] = $request['contact_name'];//超级管理员姓名
        $request_json['contact_info']['contact_id_card_number'] = $request['contact_id_card_number'];//超级管理员身份证件号码
        $request_json['contact_info']['mobile_phone'] = $request['mobile_phone'];//超级管理员手机
        $request_json['contact_info']['contact_email'] = $request['contact_email'];//超级管理员手机
        $request_json['sales_scene_info']['store_name'] = $request['store_name'];//店铺名称
        $request_json['sales_scene_info']['store_qr_code'] = $request['store_qr_code'];//店铺小程序二维码
        $request_json['sales_scene_info']['mini_program_sub_appid'] = $request['mini_program_sub_appid'];//小程序appid
        $request_json['account_info']['bank_account_type'] = $request['bank_account_type'];//账户类型
        $request_json['account_info']['account_bank'] = $request['account_bank'];//开户银行
        $request_json['account_info']['account_name'] = $request['account_name'];//开户名称
        $request_json['account_info']['bank_address_code'] = $request['bank_address_code'];//开户银行省市编码
        // $request_json['settlement_info']['settlement_id'] = 802;//结算规则ID
        $request_json['settlement_info']['settlement_id'] = 800;//结算规则ID
        // $request_json['settlement_info']['qualification_type'] = '速送';//结算规则ID
        // $request_json['business_addition_desc'] = '五公里内汽车零部件配送';//结算规则ID
        $request_json['account_info']['account_number'] = $request['account_number'];//银行账号
        $request_json['merchant_shortname'] = $request['merchant_shortname'];//商户简称

        if ($request_json['id_card_info']['id_card_name']) {
            $request_json['id_card_info']['id_card_name'] = WashPayservice::getEncrypt($request_json['id_card_info']['id_card_name']);
        }
        if ($request_json['id_card_info']['id_card_address']) {
            $request_json['id_card_info']['id_card_address'] = WashPayservice::getEncrypt($request_json['id_card_info']['id_card_address']);
        }
        if ($request_json['id_card_info']['id_card_number']) {
            $request_json['id_card_info']['id_card_number'] = WashPayservice::getEncrypt($request_json['id_card_info']['id_card_number']);
        }
        if ($request_json['account_info']['account_number']) {
            $request_json['account_info']['account_number'] = WashPayservice::getEncrypt($request_json['account_info']['account_number']);
        }
        if ($request_json['account_info']['account_name']) {
            $request_json['account_info']['account_name'] = WashPayservice::getEncrypt($request_json['account_info']['account_name']);
        }
        if ($request_json['contact_info']['contact_name']) {
            $request_json['contact_info']['contact_name'] = WashPayservice::getEncrypt($request_json['contact_info']['contact_name']);
        }
        if ($request_json['contact_info']['contact_id_card_number']) {
            $request_json['contact_info']['contact_id_card_number'] = WashPayservice::getEncrypt($request_json['contact_info']['contact_id_card_number']);
        }
        if ($request_json['contact_info']['mobile_phone']) {
            $request_json['contact_info']['mobile_phone'] = WashPayservice::getEncrypt($request_json['contact_info']['mobile_phone']);
        }
        if ($request_json['contact_info']['contact_email']) {
            $request_json['contact_info']['contact_email'] = WashPayservice::getEncrypt($request_json['contact_info']['contact_email']);
        }
        // dump($request_json);die;
        $data = json_encode($request_json);
        // dump($data);die;
        return WashPayservice::_Postresponse($url, $data);
    }

    /**
     * getApplymentByid 查询申请状态 电商收付通可用
     *  方式1：业务申请编号查询申请状态；
     * @param string applyment_id 申请单ID
     */
    public function getApplymentByid(Request $request)
    {
    	$applyment_id = $request['applyment_id'];
        $url = 'https://api.mch.weixin.qq.com/v3/ecommerce/applyments/' . $applyment_id;
        $ret = WashPayservice::_Getresponse($url);
        $data = json_decode($ret, true);
        //银行账户和名称需解密
        if (isset($data['account_validation']['account_name'])) {
            $name = $data['account_validation']['account_name'];
            $names = WashPayservice::getPrivateEncrypt($name);
            $data['account_validation']['account_name'] = $names;
        }
        if (isset($data['account_validation']['account_no'])) {
            $account_no = $data['account_validation']['account_no'];
            $account_no = WashPayservice::getPrivateEncrypt($account_no);
        }
        $ret = json_encode($data);
        return $ret;
    }

    //获取私钥
    private static function getPrivateKey($filepath)
    {
        return openssl_get_privatekey(file_get_contents($filepath));
    }

    //加载证书 公钥
    public static function getCertificate($filepath)
    {
        return openssl_x509_read(file_get_contents($filepath));
    }

    public function uploadFile(Request $request)
    {
		// 实例化一个媒体文件流，注意文件后缀名需符合接口要求
		$media = new MediaUtil(getcwd().'/营业执照.jpg');
        // dump($media);
        // dump(getcwd().'/身份证正面马跃.jpg');
        // die;
		// 商户相关配置
		$merchantId = '1619735999'; // 商户号
		$merchantSerialNumber = '3528755B65D15A9DC3F1B98A6A9D2783BBA14002'; // 商户API证书序列号

		$merchantPrivateKey = self::getPrivateKey(getcwd() . config('apisystem.SSLKEY_PATH')); // 商户私钥
		$wechatpayCertificate = self::getCertificate(getcwd() . '/pay/weixin/cert/apiclient_20220622_cert.pem'); // 商户私钥
		// 微信支付平台配置
		// $wechatpayCertificate = PemUtil::loadCertificate(getcwd() . '/pay/weixin/cert/'.'apiclient_'.date('Ymd').'_cert'.'.pem'); // 微信支付平台证书

		// 构造一个WechatPayMiddleware
		$wechatpayMiddleware = WechatPayMiddleware::builder()
		    ->withMerchant($merchantId, $merchantSerialNumber, $merchantPrivateKey) // 传入商户相关配置
		    ->withWechatPay([ $wechatpayCertificate ]) // 可传入多个微信支付平台证书，参数类型为array
		    ->build();

		// 将WechatPayMiddleware添加到Guzzle的HandlerStack中
		$stack = HandlerStack::create();
		$stack->push($wechatpayMiddleware, 'wechatpay');

		// 创建Guzzle HTTP Client时，将HandlerStack传入
		$client = new Client(['handler' => $stack]);
		// 正常使用Guzzle发起API请求
		// 接下来，正常使用Guzzle发起API请求，WechatPayMiddleware会自动地处理签名和验签
		try {
		    $resp = $client->request('POST', 'https://api.mch.weixin.qq.com/v3/merchant/media/upload', [
		        'body' => $media->getStream(),
		        'headers' => [
		            'Accept'       => 'application/json',
		            'content-type' => $media->getContentType(),
		        ]
		    ]);

		    echo $resp->getStatusCode().' '.$resp->getReasonPhrase()."\n";
		    echo $resp->getBody()."\n";
		} catch (RequestException $e) {
		    // 进行错误处理
		    echo $e->getMessage()."\n";
		    if ($e->hasResponse()) {
		        echo $e->getResponse()->getStatusCode().' '.$e->getResponse()->getReasonPhrase()."\n";
		        echo $e->getResponse()->getBody();
		    }
		    return;
		}
    }

	public function getSignature()
	{
		// Authorization: <schema> <token>
		$url_parts = parse_url($url);
		$canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
		$message = $http_method."\n".
		    $canonical_url."\n".
		    $timestamp."\n".
		    $nonce."\n".
		    $body."\n";

		openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
		$sign = base64_encode($raw_sign);

		$schema = 'WECHATPAY2-SHA256-RSA2048';
		$token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
	    $merchant_id, $nonce, $timestamp, $serial_no, $sign);
	    return $token;
	}

    public function wxpay(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'wxpay';
        logFileRecord($log_record, 'pc/Pay/wxpay', 2);
        $find_shor = DB::table('shop_order')
            ->leftJoin('shop', 'shop_id', '=', 'shor_shop_id')
            ->where('shor_number', $request['shor_number'])
            ->select('shor_state', 'shor_goo_price', 'shor_goo_num', 'shor_pay_amount', 'shor_goo_name', 'shop_shve_id', 'type', 'shor_goo_id', 'shor_number')
            ->first();
        if (empty($find_shor)) {
            return response()->json(['code'=>500,'msg'=>'未找到该订单','data'=>'']);
        }
        if ($find_shor->type == 1 || $find_shor->type == 2) {
            if ($find_shor->shor_goo_id < $find_shor->shop_shve_id) {
                return response()->json(['code'=>500, 'msg'=>'此订单版本低于店铺版本', 'data'=>'']);
            }
        }
        if ($find_shor->shor_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'此订单不是待付款状态', 'data'=>'']);
        }
        if (empty($find_shor->shor_pay_amount)) {
            return response()->json(['code'=>500, 'msg'=>'支付金额错误', 'data'=>'']);
        }
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $out_trade_no = $find_shor->shor_number;
        $body = '商品详情';
        $total_fee = $find_shor->shor_pay_amount;
        $trade_type = 'NATIVE';
        $product_id = '001';
        $notify_url = config('apisystem.server_name_https').'/index.php/api/v1/Pay/notify';
        $timestamp = time();
        $wepay_res = WashPayservice::createJsBizPackage($total_fee, $out_trade_no, $body, $notify_url, $timestamp, $config);
        return response()->json($wepay_res);
    }

    public function notify(Request $request) {
        $get_input = file_get_contents("php://input");
        $data['get_input'] = $get_input;
        Common::write_log($data, 1, 'wxpayNotify');
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $notify_res = WashPayservice::notify($get_input, $config);
        echo $notify_res;
    }

    /**
     * 退款
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-11-19
     * @param  Request          $request [description]
     */
    public function Mztuikuan(Request $request) {
        $find_order = DB::table('shop_order')
            ->where('shor_number', $request['shor_number'])
            ->first();
        $orderName = $find_order->shor_goo_name . '退款';
        $sub_mch_id = '1643850123';
        $out_refund_no = 'TK'.time().rand(10000,99999);
        $transaction_id = $find_order->shor_other_num;
        $outTradeNo = $find_order->shor_number;
        $refund_fee = $find_order->shor_paid_money;
        $total_fee = $find_order->shor_pay_amount;
        $notify_url = config('apisystem.server_name_https').'/index.php/api/v1/Pay/MztuikuannotifyPay';
        $refund_desc = $orderName;
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $refund_res = WashPayservice::Mztuikuan($transaction_id, $outTradeNo, $out_refund_no, $total_fee, $refund_fee, $refund_desc, $config);
        $refund_data = json_decode($refund_res, true);
        if (isset($refund_data['refund_id']) && !empty($refund_data['refund_id'])) {
            $refund_data_res = true;
        } else {
            $refund_data_res = false;
        }
        return response()->json(['data'=>$refund_data]);
    }

    public function MztuikuannotifyPay(Request $request) {
        $get_input = file_get_contents("php://input");
        $data['get_input'] = $get_input;
        Common::write_log($data, 1, 'MztuikuannotifyPay');
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $notify_res = WashPayservice::MztuikuannotifyPay($get_input, $config);
        echo $notify_res;
    }
}
