<?php
/**
 * @author: helei
 * @createTime: 2016-07-28 17:23
 * @description: 支付宝订单查询接口
 */

namespace Payment\Query\Ali;

use Payment\Common\Ali\AliBaseStrategy;
use Payment\Common\Ali\Data\Query\ChargeQueryData;
use Payment\Common\AliConfig;
use Payment\Common\PayException;
use Payment\Config;

class AliChargeQuery extends AliBaseStrategy
{
    public function getBuildDataClass()
    {
        $this->config->method = AliConfig::TRADE_QUERY_METHOD;
        return ChargeQueryData::class;
    }
    
    protected function retData(array $data)
    {
        $url = parent::retData($data); // TODO: Change the autogenerated stub

        try {
            $ret = $this->sendReq($url);
        } catch (PayException $e) {
            throw $e;
        }

        if ($this->config->returnRaw) {
            $ret['channel'] = Config::ALI_CHARGE;
            return $ret;
        }

        return $this->createBackData($ret);
    }

    /**
     * 处理支付宝返回的数据，统一处理后返回
     * @param array $data  支付宝返回的数据
     * @return array
     * @author helei
     */
    protected function createBackData(array $data)
    {
        // 新版本
        if ($data['code'] !== '10000') {
            return $retData = [
                'is_success'    => 'F',
                'error' => $data['sub_msg']
            ];
        }

        // 正确情况
        $retData = [
            'is_success'    => 'T',
            'response'  => [
                'amount'   => $data['total_amount'],
                'channel'   => Config::ALI_CHARGE,
                'order_no'   => $data['out_trade_no'],
                'buyer_id'   => $data['buyer_user_id'],
                'trade_state'   => $this->getTradeStatus($data['trade_status']),
                'transaction_id'   => $data['trade_no'],
                'time_end'   => $data['send_pay_date'],

                'receipt_amount' => $data['receipt_amount'],// 实收金额，单位为元，两位小数。
                'pay_amount'    => $data['buyer_pay_amount'],// 买家实付金额，单位为元
                'point_amount' => $data['point_amount'],// 使用集分宝支付的金额
                'invoice_amount' => $data['invoice_amount'],// 交易中用户支付的可开具发票的金额，单位为元，两位小数
                'fund_bill_list' => empty($data['fund_bill_list']) ? '' : $data['fund_bill_list'],// 支付成功的各个渠道金额信息
                'logon_id'   => $data['buyer_logon_id'],// 买家支付宝账号
            ],
        ];

        return $retData;
    }
}
