<?php

use App\Base\Base;

use App\Exception\custom\PayException;
use App\Services\pay\PayService;
use App\Services\refund\RefundService;
use Api\PhpUtils\Log\FileLog;


class OrderController extends Base
{
    /**
     * 创建支付订单，返回前端ping++的支付信息
     */
    public function payAction()
    {
        $params = $this->params;
        $user_id    = $params['user_id'];
        $order_id = $params['order_id'];
        $pay_method_id = $params['pay_method_id'] ?? 106;

        $extra = [];
        if(!empty($params['extra'])) {
            if(is_string($params['extra'])) {
                $extra = json_decode($params['extra'], true);
            } else {
                $extra = $params['extra'];
            }
        }

        if( isset($params['pkg']) && ($params['pkg'] == 'com.yanjiaoquan.app965004')) {
            $pingxx_id = \Yaf\Application::app()->getConfig()->get('pingxx_yjq.appid');
        } else {
            $pingxx_id = \Yaf\Application::app()->getConfig()->get('pingxx.appid');
        }

        $paySrv = new PayService();
        $ret = $paySrv->do_pay($order_id, $user_id, $pingxx_id, $pay_method_id, $extra);

        //兼容C端客户端支付，调整返回结构，ping++ 返回 order，原生：微信、支付宝返回charge
        $result = [];
        $result[] = ['k'=>'order', 'v'=>$ret];
        $this->success(['result'=>$result]);
    }

    public function refundAction() {

        $params = $this->getRequest()->getPost();

        if(!empty($params['order_item_id'])) {
            if(!is_array($params['order_item_id'])) {
                $params['order_item_id'] = explode(',', $params['order_item_id']);
            }

        } else {
            $params['order_item_id'] = [];
        }

        if(empty($params['order_id'])) {
            throw new PayException(['cus' => 1]);
        }

        $refundSrv = new RefundService();
        $ret = $refundSrv->do_refund($params['order_id'], $params['order_item_id']);

        $this->success(['result'=>$ret]);
    }

    public function chargesAction() {
        $params = $this->getRequest()->getPost();

        $order_id    = $params['order_id'] ?? '';
        $paySrv = new PayService();
        $ret = $paySrv->pay_charges($order_id);

        $this->success(['result'=>$ret]);
    }

    public function write_offAction() {

        $params = $this->params;
        $life_account_id    = $params['life_account_id'];
        $order_item_id = $params['order_item_id'];

        $refundSrv = new PayService();
        $ret = $refundSrv->write_off($order_item_id, $life_account_id);

        $this->success(['result'=>$ret]);
    }
}
