<?php
defined('IN_WEB') or die('Include Error!');

/**
 * 安卓退款订单处理
 */
class ModelRefundgoogle
{

    //响应是一个 JSON 字符串，其中包含已作废购买交易的列表。如果结果数量超过了在 maxResults 请求参数中指定的数量，响应就会包含一个 nextPageToken 值，您可以将该值传递给后续请求来查看更多结果。列表中的第一个结果显示的是最早作废的购买交易。
    //参考:https://developers.google.com/android-publisher/voided-purchases?hl=zh-cn
    private $_refundApi = 'https://www.googleapis.com/androidpublisher/v3/applications/%s/purchases/voidedpurchases?access_token=%s&type=1';

    /**
     * 从谷歌支付api获取退款订单列表
     * @param int $startTime
     * @param int $endTime
     */
    public function getRefundListFromGoogle($startTime = 0, $endTime = 0, $nextPageToken = '') {
        if(IS_DEBUF){
            return [];
        }
        $package = oo::commonOprModel('paymentgoogle')->getPackageName();
        $token = !empty($nextPageToken) ? $nextPageToken : oo::commonOprModel('paymentgoogle')->getToken();
        $url = sprintf($this->_refundApi, $package, $token);
        if(!empty($startTime)){
            $url .= "&startTime={$startTime}";
        }
        if(!empty($endTime)){
            $url .= "&endTime={$endTime}";
        }
        return $this->curlGetHttps($url);
    }

    /**
     * 处理谷歌退款订单
     * @param $day 日期
     * @return bool
     */
    public function dealRefundOrders($day = 0, $nextPageToken = '') {
        $startTime = $endTime = 0;
        if(!empty($day)){
            $startTime = strtotime($day) * 1000;
            //$endTime = (strtotime($day) + 24 * 3600) * 1000 - 1;
        }
        $arr = $this->getRefundListFromGoogle($startTime, $endTime, $nextPageToken);
        //$file = WWWROOT .'voidedpurchases.txt';
        //$tmp = file_get_contents($file);
        //if(empty($tmp)){
        //    oo::logs()->debug3(["err"=>'get refund summarylist error, no data'],'refund_err');
        //    return false;
        //}
        //$arr = $tmp ? json_decode($tmp, true) : [];
        if(empty($arr['voidedPurchases'])){ //退款订单列表为空
            return true;
        }
        $refundArr = [];
        foreach($arr['voidedPurchases'] as $val){
            $refundArr[] = $val['orderId'];
            if(count($refundArr) > 50){
                $ret = $this->upRefundArr($refundArr);
                if(!$ret){
                    oo::logs()->debug3(["err"=>'update refund summarylist error',"param"=>$refundArr],'refund_err');
                }
                $refundArr = [];
            }
        }
        if(count($refundArr) > 0){
            $ret = $this->upRefundArr($refundArr);
        }
        if(!empty($arr['tokenPagination'])){
            return $this->dealRefundOrders($day, $arr['tokenPagination']['nextPageToken']);
        }
        return $ret;
    }

    /**
     * 更新退款订单
     */
    private function upRefundArr($arr, $type = 1) {
        $tb = otable::summarylist();
        $in = implode("','", $arr);
        $sql = "UPDATE {$tb} SET sl_status = 3 WHERE sl_platform_serial_num IN('".$in."')";
        $res1 = oo::commonOprDb('payment')->query($sql);
        $year = date("Y",strtotime('-1 days', time()));
        $year =intval($year)<2022?2022:intval($year);
        $tb2 = otable::orderNew($year);
        $sql2 = "update {$tb2} set status=3 where external_order_id IN('".$in."')";
        $res2 = oo::commonOprDb('common')->query($sql2);
        oo::logs()->debug3(["nums"=>count($arr),"orderList"=>$arr,"res1"=>$res1,"res2"=>$res2],"refundOrder.log");
        return ;
    }

    /**
     * 获取json格式的curl get请求结果
     * @param $url
     * @return array
     */
    function curlGetHttps($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmp = curl_exec($curl); // 执行操作
        if (!IS_DEBUF && curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmp ? (array)json_decode($tmp, true) : []; // 返回数据，json格式
    }
}
