<?php

namespace SRVX\Api\Controllers\Alipay;

use SRVX\Api\Controllers\ControllerBase;
use SRVX\Msg;
use SRVX\Service\Common\SysCfgService;
use SRVX\Service\Pay\EasyAlipayService;
use SRVX\Service\Pay\ExtraAlipayService;
use SRVX\Service\Pay\PayService;
use App\constants\Common as ICommon;
use SRVX\Utils\Sredis;


class SplitAccountController extends ControllerBase
{

    public function initialize()
    {
        parent::initialize();
    }

    public function indexAction()
    {
        $this->s->demo()->demo();
    }

    public function relationBindAction()
    {
        if ($this->request->isPost()) {
            $args = $this->request->getJsonRawBody(true);
            $this->logger($args, "relationBindAction", true);
            if (empty($args["app_id"]) || empty($args["merchant_id"]) || empty($args["out_request_no"]) || empty($args["receiver_list"])) {
                $this->api(Msg::NewError(500, '缺少必要參數！'));
            }
            $uid            = $this->userInfo["uid"];
            $merchant_id    = $args["merchant_id"] ?? "";
            $app_id         = $args["app_id"] ?? "";
            $out_request_no = $args["out_request_no"] ?? "";
            $receiver_list  = $args["receiver_list"] ?? "";
            $payService     = new PayService();
            $app            = $payService->getPayConfig($app_id);
            if ($app == false) $this->api(Msg::NewError(500, 'APP_ID有誤'));
            //判斷app是否可用
            if ($app->state != ICommon::APP_STATE_USE) $this->api(Msg::NewError(500, 'APP暫不可用'));
            $config     = [];
            $notify_url = $this->redis->get(ICommon::ALI_PAY_NOTIFY_URL_CACHE_KEY);
            if ($notify_url == false) $notify_url = (new SysCfgService())->getSet(['pay_ali_notify_url'])["pay_ali_notify_url"];
            $appInfo = json_decode($app->alipay_configure, true);
            if ($app->mode == ICommon::APP_MODE_INDEPENDENT) {
                $config = [
                    "pay_ali_app_id"      => $appInfo["app_id"],
                    "pay_ali_public_key"  => $appInfo["public_key"],
                    "pay_ali_private_key" => $appInfo["private_key"],
                ];
            }
            //判斷店鋪號是否可以用
            $merchantAlipayAuthorize = $payService->getAppAuthToken($merchant_id);
            if ($merchantAlipayAuthorize == false) $this->api(Msg::NewError(500, '店鋪號有誤'));
            if ($merchantAlipayAuthorize->state != ICommon::MERCHANT_STATE_USE) $this->api(Msg::NewError(500, '店鋪暫未授權'));
            $app_auth_token = $merchantAlipayAuthorize->app_auth_token;
            $result         = (new EasyAlipayService($config))->splitAccountForRelationBind($out_request_no, $receiver_list, $app_auth_token);
            if (!$result["status"]) {
                //调用失败
                $this->api(Msg::NewError(500, $result["msg"] ?? $result["sub_msg"]));
            }
            $this->api($result["data"]);
        } else {
            $this->api(Msg::NewError(500, '提交方式错误！'));
        }
    }

    public function relationUnBindAction()
    {
        if ($this->request->isPost()) {
            $args = $this->request->getJsonRawBody(true);
            if (empty($args["app_id"]) || empty($args["merchant_id"]) || empty($args["out_request_no"]) || empty($args["receiver_list"])) {
                $this->api(Msg::NewError(500, '缺少必要參數！'));
            }
            $uid            = $this->userInfo["uid"];
            $merchant_id    = $args["merchant_id"] ?? "";
            $app_id         = $args["app_id"] ?? "";
            $out_request_no = $args["out_request_no"] ?? "";
            $receiver_list  = $args["receiver_list"] ?? "";
            $payService     = new PayService();
            $app            = $payService->getPayConfig($app_id);
            if ($app == false) $this->api(Msg::NewError(500, 'APP_ID有誤'));
            //判斷app是否可用
            if ($app->state != ICommon::APP_STATE_USE) $this->api(Msg::NewError(500, 'APP暫不可用'));
            $config     = [];
            $notify_url = $this->redis->get(ICommon::ALI_PAY_NOTIFY_URL_CACHE_KEY);
            if ($notify_url == false) $notify_url = (new SysCfgService())->getSet(['pay_ali_notify_url'])["pay_ali_notify_url"];
            $appInfo = json_decode($app->alipay_configure, true);
            if ($app->mode == ICommon::APP_MODE_INDEPENDENT) {
                $config = [
                    "pay_ali_app_id"      => $appInfo["app_id"],
                    "pay_ali_public_key"  => $appInfo["public_key"],
                    "pay_ali_private_key" => $appInfo["private_key"],
                ];
            }
            //判斷店鋪號是否可以用
            $merchantAlipayAuthorize = $payService->getAppAuthToken($merchant_id);
            if ($merchantAlipayAuthorize == false) $this->api(Msg::NewError(500, '店鋪號有誤'));
            if ($merchantAlipayAuthorize->state != ICommon::MERCHANT_STATE_USE) $this->api(Msg::NewError(500, '店鋪暫未授權'));
            $app_auth_token = $merchantAlipayAuthorize->app_auth_token;
            $result         = (new EasyAlipayService($config))->splitAccountForRelationUnbind($out_request_no, $receiver_list, $app_auth_token);
            if (!$result["status"]) {
                //调用失败
                $this->api(Msg::NewError(500, $result["msg"] ?? $result["sub_msg"]));
            }
            $this->api($result["data"]);
        }
        $this->api(Msg::NewError(500, '提交方式错误！'));
    }

    public function relationBatchQueryAction()
    {
        if (!$this->request->isPost()) $this->api(Msg::NewError(500, '提交方式错误！'));
        $args = $this->request->getJsonRawBody(true);
        if (empty($args["app_id"]) || empty($args["merchant_id"]) || empty($args["out_request_no"]) || empty($args["page_num"]) || empty($args["page_size"])) {
            $this->api(Msg::NewError(500, '缺少必要參數！'));
        }
        $uid            = $this->userInfo["uid"];
        $merchant_id    = $args["merchant_id"] ?? "";
        $app_id         = $args["app_id"] ?? "";
        $out_request_no = $args["out_request_no"] ?? "";
        $page_num       = $args["page_num"] ?? "";
        $page_size      = $args["page_size"] ?? "";
        $payService     = new PayService();
        $app            = $payService->getPayConfig($app_id);
        if ($app == false) $this->api(Msg::NewError(500, 'APP_ID有誤'));
        //判斷app是否可用
        if ($app->state != ICommon::APP_STATE_USE) $this->api(Msg::NewError(500, 'APP暫不可用'));
        $config     = [];
        $notify_url = $this->redis->get(ICommon::ALI_PAY_NOTIFY_URL_CACHE_KEY);
        if ($notify_url == false) $notify_url = (new SysCfgService())->getSet(['pay_ali_notify_url'])["pay_ali_notify_url"];
        $appInfo = json_decode($app->alipay_configure, true);
        if ($app->mode == ICommon::APP_MODE_INDEPENDENT) {
            $config = [
                "pay_ali_app_id"      => $appInfo["app_id"],
                "pay_ali_public_key"  => $appInfo["public_key"],
                "pay_ali_private_key" => $appInfo["private_key"],
            ];
        }
        //判斷店鋪號是否可以用
        $merchantAlipayAuthorize = $payService->getAppAuthToken($merchant_id);
        if ($merchantAlipayAuthorize == false) $this->api(Msg::NewError(500, '店鋪號有誤'));
        if ($merchantAlipayAuthorize->state != ICommon::MERCHANT_STATE_USE) $this->api(Msg::NewError(500, '店鋪暫未授權'));
        $app_auth_token = $merchantAlipayAuthorize->app_auth_token;
        $result         = (new EasyAlipayService($config))->splitAccountForRelationBatchQuery($out_request_no, $page_num, $page_size, $app_auth_token);
        if (!$result["status"]) {
            //调用失败
            $this->api(Msg::NewError(500, $result["msg"] ?? $result["sub_msg"]));
        }
        $this->api($result["data"]);
    }

    public function splitAccountForOrderSettleAction()
    {
        if (!$this->request->isPost()) $this->api(Msg::NewError(500, '提交方式错误！'));
        $args = $this->request->getJsonRawBody(true);
        $this->logger($args, "splitAccountForOrderSettle", true);
        if (empty($args["app_id"]) || empty($args["merchant_id"]) || empty($args["out_request_no"]) || empty($args["trade_no"]) || empty($args["royalty_parameters"])) {
            $this->api(Msg::NewError(500, '缺少必要參數！'));
        }
        $uid                = $this->userInfo["uid"];
        $merchant_id        = $args["merchant_id"] ?? "";
        $app_id             = $args["app_id"] ?? "";
        $out_request_no     = $args["out_request_no"] ?? "";
        $trade_no           = $args["trade_no"] ?? "";
        $royalty_parameters = $args["royalty_parameters"] ?? "";
        $payService         = new PayService();
        $app                = $payService->getPayConfig($app_id);
        if ($app == false) $this->api(Msg::NewError(500, 'APP_ID有誤'));
        //判斷app是否可用
        if ($app->state != ICommon::APP_STATE_USE) $this->api(Msg::NewError(500, 'APP暫不可用'));
        $config     = [];
        $notify_url = $this->redis->get(ICommon::ALI_PAY_NOTIFY_URL_CACHE_KEY);
        if ($notify_url == false) $notify_url = (new SysCfgService())->getSet(['pay_ali_notify_url'])["pay_ali_notify_url"];
        $appInfo = json_decode($app->alipay_configure, true);
        if ($app->mode == ICommon::APP_MODE_INDEPENDENT) {
            $config = [
                "pay_ali_app_id"      => $appInfo["app_id"],
                "pay_ali_public_key"  => $appInfo["public_key"],
                "pay_ali_private_key" => $appInfo["private_key"],
            ];
        }
        //判斷店鋪號是否可以用
        $merchantAlipayAuthorize = $payService->getAppAuthToken($merchant_id);
        if ($merchantAlipayAuthorize == false) $this->api(Msg::NewError(500, '店鋪號有誤'));
        if ($merchantAlipayAuthorize->state != ICommon::MERCHANT_STATE_USE) $this->api(Msg::NewError(500, '店鋪暫未授權'));
        $app_auth_token = $merchantAlipayAuthorize->app_auth_token;
        $result         = (new EasyAlipayService($config))->splitAccountForOrderSettle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token);
        if (!$result["status"]) {
            //调用失败
            $this->api(Msg::NewError(500, $result["msg"] ?? $result["sub_msg"]));
        }
        $this->api($result["data"]);
    }

    public function splitAccountForRefundAction()
    {
        if (!$this->request->isPost()) $this->api(Msg::NewError(500, '提交方式错误！'));
        $args = $this->request->getJsonRawBody(true);
        $this->logger($args, "splitAccountForRefund", true);
        if (empty($args["app_id"]) || empty($args["merchant_id"]) || empty($args["out_trade_no"]) || empty($args["trade_no"]) || empty($args["refund_amount"])
            || empty($args["refund_reason"]) || empty($args["out_request_no"]) || empty($args["refund_royalty_parameters"])) {
            $this->api(Msg::NewError(500, '缺少必要參數！'));
        }
        $uid                       = $this->userInfo["uid"];
        $merchant_id               = $args["merchant_id"] ?? "";
        $app_id                    = $args["app_id"] ?? "";
        $out_trade_no              = $args["out_trade_no"] ?? "";
        $trade_no                  = $args["trade_no"] ?? "";
        $refund_amount             = $args["refund_amount"] ?? "";
        $refund_reason             = $args["refund_reason"] ?? "";
        $out_request_no            = $args["out_request_no"] ?? "";
        $refund_royalty_parameters = $args["refund_royalty_parameters"] ?? "";
        $payService                = new PayService();
        $app                       = $payService->getPayConfig($app_id);
        if ($app == false) $this->api(Msg::NewError(500, 'APP_ID有誤'));
        //判斷app是否可用
        if ($app->state != ICommon::APP_STATE_USE) $this->api(Msg::NewError(500, 'APP暫不可用'));
        $config     = [];
        $notify_url = $this->redis->get(ICommon::ALI_PAY_NOTIFY_URL_CACHE_KEY);
        if ($notify_url == false) $notify_url = (new SysCfgService())->getSet(['pay_ali_notify_url'])["pay_ali_notify_url"];
        $appInfo = json_decode($app->alipay_configure, true);
        if ($app->mode == ICommon::APP_MODE_INDEPENDENT) {
            $config = [
                "pay_ali_app_id"      => $appInfo["app_id"],
                "pay_ali_public_key"  => $appInfo["public_key"],
                "pay_ali_private_key" => $appInfo["private_key"],
            ];
        }
        //判斷店鋪號是否可以用
        $merchantAlipayAuthorize = $payService->getAppAuthToken($merchant_id);
        if ($merchantAlipayAuthorize == false) $this->api(Msg::NewError(500, '店鋪號有誤'));
        if ($merchantAlipayAuthorize->state != ICommon::MERCHANT_STATE_USE) $this->api(Msg::NewError(500, '店鋪暫未授權'));
        $app_auth_token = $merchantAlipayAuthorize->app_auth_token;
        $result         = (new EasyAlipayService($config))->splitAccountForRefund($out_trade_no, $trade_no, $refund_amount, $refund_reason, $out_request_no, $refund_royalty_parameters, $app_auth_token);
        if (!$result["status"]) {
            //调用失败
            $this->api(Msg::NewError(500, $result["msg"] ?? $result["sub_msg"]));
        }
        $this->api($result["data"]->httpBody);
    }
}
