<?php

namespace App\Http\Controllers\Pay;


use App\Facade\Site;
use App\Libs\ApiResponse;
use App\Models\User\User;
use App\Services\Pay\PayService;
use App\Services\Pay\ProductService;
use App\Transformer\Pay\PayTransformer;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Redis;
use Vinkla\Hashids\Facades\Hashids;
use Log;
use Ycpay\Byte;
use App\Services\User\UserService;

class PayController extends BaseController
{
    use ApiResponse;
    protected $payService;

    public function __construct(
        PayService $payService
    )
    {
        $this->payService = $payService;
    }

    public function create_order(Request $request) {
        $uid = Site::getUid();
        $user = User::find($uid);
        \Log::info('create_order:'.$uid.' request:'.json_encode($request->all()));
        $product_id = $request->get('product_id');
        
        $phone_type = $request->has('phone_type')?$request->get('phone_type'):'android';
        if (!in_array($phone_type,['ios','android'])){
            $phone_type = 'android';
        }
        if(empty($product_id) || empty($user)) return $this->error('50013:参数异常');
        
//         if(empty($uid)) return $this->error('50012:非法登录');
        
        $trade_no = generateOrderSn();
        
        $product = ProductService::getProductSingle($product_id);
        if(empty($product)) return $this->error('50013:参数异常product_id');
        
        $price = $product->price;
        
        // 内测uid 1分钱
        if (in_array($uid, explode(',', env('TEST_UID')))) {
            $price = 0.01;
            \Log::info('create_order_1fen_uid:'.$uid);
        }

        if(empty($price)) return $this->error('50013:参数异常price');

        $send_order_id = Site::getSendOrderId();
        $distribution_channel_id = Site::getChannelId();
        if(empty($distribution_channel_id)) return $this->error('50013:参数异常channel_id');
        
        $from_bid = Site::getRecentBid();
        $create_ip = getIpAddr();
        $order_type = $product->type;
        
        $result = $create_order_param = [];
        $order_param = [
            'price'=>$price,
            'uid'=>$uid,
            'order_type'=>$order_type,
            'distribution_channel_id'=>$distribution_channel_id,
            'create_ip'=>$create_ip,
            'from_bid'=>$from_bid,
            'send_order_id'=>$send_order_id,
            'trade_no'=>$trade_no,
            'product_id'=>$product_id,
            'pay_type'=>'Byte',
            'openid'=>$user->openid,
            'phone_type'=>$phone_type,
        ];
        \Log::info('order_param:'.json_encode($order_param));
        $result = $this->payService->create_order($order_param);


        //{"err_no":0,"err_tips":"success","data":{"order_id":"N7230729566975953204","order_token":"CgwIARDGJRiuMiABKAESTgpMszqeb0L8DTtnY44geDAfYHAsrZrKRsbwMz8GdAz8fRmJwGJf860xXpHLTPBlka94g6Gsm6NuyakLaHYoTmtg9uHag7rRZVGXrpnDtRoA.L","url":""}}
        //{"err_no":2008,"err_tips":"\u7b7e\u540d\u6821\u9a8c\u5f02\u5e38\uff0c\u8bf7\u4f7f\u7528\u6b63\u786e\u7684\u7b7e\u540d","data":null}

        if(isset($result['err_no']) && $result['err_no'] == 0){
            $create_order_param = [
                'trade_no'=>$trade_no,
                'order_id'=>$result['data']['order_id'],
                'order_token'=>$result['data']['order_token'],
                'pay_url'=>$result['data']['url'],
                
            ];
            
            // 维护orders的url字段和order_id字段 
            $order = $this->payService->getByTradeNo($trade_no);
            $order->tiktok_order_id = $result['data']['order_id'];
            $order->pay_url = $result['data']['url'];
            $order->save();

        }else{
            if(isset($result['err_tips'])){
                $error_msg = $result['err_tips'];
            }else{
                $error_msg = isset($result['msg'])?$result['msg']:'';
            }
            \Log::info('create_order_ept:'.$error_msg);
            return $this->error('20010:创建订单异常');
        }

        return $this->success($create_order_param, [new PayTransformer(), 'createOrderParams']);
    }
    
    /**
     * 抖音官方回调
    {
    	"msg": "{\"appid\":\"tta48fd2323bb0abbc01\",\"cp_orderno\":\"2023051916413016844856905211716\",
    	\"cp_extra\":\"\",\"way\":\"2\",\"channel_no\":\"2023051922001465081408495054\",\"channel_gateway_no\":\"\",
    	\"payment_order_no\":\"DPS2305191641249038630039365653\",\"out_channel_order_no\":\"2023051922001465081408495054\",
    	\"total_amount\":1,\"status\":\"SUCCESS\",\"seller_uid\":\"72265320820071651950\",\"extra\":\"\",
    	\"item_id\":\"\",\"paid_at\":1684485701,\"message\":\"\",\"order_id\":\"N7234810920067680567\",
    	\"ec_pay_trade_no\":\"DTPP2305191641229006646669375653\"}",
    	"msg_signature": "d4402df600eee04fd3350259c1656a10b6006679",
    	"nonce": "7346",
    	"timestamp": "1684485701",
    	"type": "payment",
    	"_url": "\/pay\/receive_dy_pay_notify"
    }
     * 

     */
    function dycallback(Request $request)
    {
        $callback_params = $request->all();
        \Log::info('dycallback:'.json_encode($callback_params));
        $callback_params = json_decode(json_encode($callback_params),true);

        $trade_no = $transaction_id = '';
        if(isset($callback_params['msg']) && $callback_params['msg']){
            $callback_params_decode = json_decode($callback_params['msg'],true);
            
            $trade_no = $callback_params_decode['cp_orderno'];
            $order_id = $callback_params_decode['order_id'];
            $transaction_id = $callback_params_decode['channel_no'];
        }
        
        \Log::info('dycallback:trade_no:'.$trade_no.' transaction_id:'.$transaction_id.' order_id:'.$order_id);

        $calllback =  $this->payService->orderCallBack($trade_no, $transaction_id,$order_id);
        if($calllback){
            \Log::info('dycallback:trade_no_success'.$trade_no);
            exit('{"err_no":0,"err_tips":"success"}');
        }
        \Log::info('dycallback:trade_no_fail'.$trade_no);
        
        exit('fail');
    }
    
    // 退款回调
    function refund_dycallback(Request $request)
    {
        $callback_params = $request->all();
        \Log::info('refund_dycallback:'.json_encode($callback_params));
        
        exit('{"err_no":0,"err_tips":"success"}');
    }
    
    
    /**
     * TODO  加上查询逻辑
     * @param Request $request
     * @return mixed
     */
    public function query_user_pay(Request $request) {
        $uid = Site::getUid();
        
        \Log::info('query_user_pay:'.$uid.' request:'.json_encode($request->all()));
        
        $trade_no = $request->get('trade_no');
        if(empty($trade_no)) return $this->error('50013:参数异常');
        
        return $this->success(['is_paid'=>1]);
    }
    
    /**
     * 前端支付相关信息回调
     * @param Request $request
     * @return mixed
     */
    public function pay_info_callback(Request $request) {
        $uid = Site::getUid();
        $user = User::find($uid);
        \Log::info('pay_info_callback:'.$uid.' request:'.json_encode($request->all()));
        
        $trade_no = $request->get('trade_no');
        $order_status = $request->get('order_status');
        if(empty($order_status) || empty($trade_no)) return $this->error('50013:参数异常');
        
        // 当前只支持 取消支付，待支付和成功在其他函数直接执行
        if(in_array($order_status,[2])){
            $this->payService->report_to_douyin($trade_no, $user->openid, $order_status);
        }
        
        
        return $this->success(['is_success'=>1]);
    }

}
