<?php

namespace app\common\service\payment;

use think\facade\Request;
use app\common\enum\Terminal;
use app\common\exception\BaseException;
use app\common\model\Payment as PaymentModel;
use app\common\model\order\Order as OrderModel;
use app\common\model\order\OrderGoods as OrderGoodsModel;
use app\common\model\order\Recharge as RechargeModel;
use app\common\service\Config;
use app\common\model\UsersAuth as UsersAuthModel;
use app\common\service\Users as UsersService;

/**
 * @package app\common\service\payment
 * @class Payment
 * @author xzncit 2024/3/16
 */
class Payment {

    public static function recharge($params){
        $payment = PaymentModel::where("id",$params["pay_id"])->find();
        if(empty($payment)){
            throw new BaseException("您选择的支付方式不存在",0);
        }

        $order = RechargeModel::where(["id"=>$params["order_id"],"user_id"=>UsersService::get("id",0)])->find();
        if(empty($order)){
            throw new BaseException("您要支付的订单不存在",0);
        }

        if($order["pay_status"] != 2){
            throw new BaseException("您的订单已支付",1,[
                "isPay"=>1
            ]);
        }

        $class = "app\\common\\library\\payment\\" . ucfirst($payment["code"]);
        if(!class_exists($class)){
            throw new BaseException("您选择支付的方式不存在",0);
        }

        try{
            RechargeModel::startTrans();
            RechargeModel::where("id",$order["id"])->save(["pay_type"=>$payment["id"]]);
            $array = [
                "id"            => $order["id"],
                "user_id"       => $order["user_id"],
                "goods_name"    => "用户充值",
                "order_no"      => $order["order_no"],
                "order_amount"  => $order["pay_price"]
            ];
            $data = self::{$payment["code"]}($array);
            $payment = invoke($class);
            $result = $payment->create($data);
            RechargeModel::commit();
            return $result;
        }catch (\Exception $ex){
            RechargeModel::rollback();
            throw new BaseException($ex->getMessage(),0);
        }
    }

    public static function order($params){
        $payment = PaymentModel::where("id",$params["pay_id"])->find();
        if(empty($payment)){
            throw new BaseException("您选择的支付方式不存在");
        }

        $order = OrderModel::where(["id"=>$params["order_id"],"user_id"=>UsersService::get("id",0)])->find();
        if(empty($order)){
            throw new BaseException("您要支付的订单不存在",0);
        }

        if($order["pay_status"] != 1){
            throw new BaseException("您的订单已支付",1,[
                "isPay"=>1
            ]);
        }

        $class = "app\\common\\library\\payment\\" . ucfirst($payment["code"]);
        if(!class_exists($class)){
            throw new BaseException("您选择支付的方式不存在",0);
        }

        try{
            OrderModel::startTrans();
            OrderModel::where("id",$order["id"])->save(["pay_id"=>$payment["id"]]);
            $order["goods_name"] = OrderGoodsModel::where("order_id",$order["id"])->order("id","ASC")->value("goods_name","");
            $data = self::{$payment["code"]}($order);
            $payment = invoke($class);
            $result = $payment->create($data);
            OrderModel::commit();
            return $result;
        }catch (\Exception $ex){
            OrderModel::rollback();
            throw new BaseException($ex->getMessage(),0);
        }
    }

    public static function wechat($order){
        $array    = [
            "appid"     => "",
            "segment"   => "",
            "order"     => [
                "description"  => $order["goods_name"],
                "out_trade_no" => $order["order_no"],
                "notify_url"   => url("api/payment.wechat/index",[],false,true),
                "amount" => [
                    "total" => $order["order_amount"] * 100
                ],
            ]
        ];

        $terminal = Terminal::getTerminalNo(Request::header("Client-Type","h5"));
        $array["terminal"] = $terminal;
        if($terminal == 1){
            $array["segment"] = "/v3/pay/transactions/jsapi";
            $array["appid"]   = Config::getArray("wechat.appid","");
        }else if($terminal == 9){
            $array["segment"] = "/v3/pay/transactions/h5";
            $array["appid"]   = Config::getArray("wechat.appid","");
            $array["order"]["scene_info"] = [
                "payer_client_ip"=>Request::ip(),
                "h5_info"=>[
                    "type"=>"iOS"
                ]
            ];
        }else if($terminal == 2){
            $array["segment"] = "/v3/pay/transactions/jsapi";
            $array["appid"]   = Config::getArray("miniprogram.appid","");
        }else if(in_array($terminal,[10,11])){
            $array["segment"] = "/v3/pay/transactions/app";
            $array["appid"]   = Config::getArray("weixin.appid","");
        }

        if(in_array($terminal,[1,2])){
            $user = UsersAuthModel::where(["user_id"=>UsersService::get("id"),"terminal"=>$terminal])->find();
            if(empty($user["openid"])){
                throw new BaseException("获取用户授权OPENID失败",0);
            }

            $array["order"]["payer"] = [
                "openid"=>$user["openid"]
            ];
        }

        return $array;
    }

    public static function alipay($order){
        $array    = [
            "subject"   => $order["goods_name"],
            "order"     => [
                "out_trade_no" => $order["order_no"],
                "order_amount" => $order["order_amount"]
            ]
        ];

        $array['terminal'] = Terminal::getTerminalNo(Request::header("Client-Type","h5"));
        return $array;
    }

    public static function balance($order) {
        return [
            "type"          => $order["type"],
            "promoter_id"   => $order["promoter_id"],
            "order_id"      => $order["id"],
            "user_id"       => $order["user_id"],
            "order_amount"  => $order["order_amount"]
        ];
    }

}