<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service;
/**
 * 充值配置与充值订单
 */
class Payios extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //vip ios用的
    public function vip_config_ios(){
        $list = Db::name('payvip_config_ios')->field('id,money,days,title')->where('is_show',1)->order('weight asc,id asc')->select();
        $data['vipconfig'] = $list;
        $data['vip_endtime'] = model('wallet')->getWallet($this->auth->id,'vip_endtime');
        $data['is_vip'] = $data['vip_endtime'] > time() ? 1 : 0;
        $data['avatar'] = localpath_to_netpath($this->auth->avatar);
        $this->success('success',$data);
    }

    //vip用的,创建订单
    public function vip_recharge_ios(){
        $rc_id = input('rc_id',0);
        $platform = 'app';
        $uid = $this->auth->id;

        if(!$rc_id){
            $this->error('请选择会员套餐');
        }

        if(!$this->user_auth_limit()){
            $this->error('请先完成实名认证');
        }

        //赋值money
        $recharge_config = Db::name('payvip_config_ios')->where('id',$rc_id)->find();
        $money = $recharge_config['money'];

        if($money<=0)
        {
            $this->error('支付金额必须大于0');
        }
        if($money > 10000){
            $this->error('支付金额太大');
        }

        //创建订单
        $data = [];
        $data['user_id'] = $uid;
        $data['out_trade_no'] = createUniqueNo('V',$uid); // 数据库订单号加密
        $data['order_amount'] = $money;
        $data['createtime'] = time();

        $data['pay_type'] = 'ios';
        $data['platform'] = $platform;
        $data['order_status'] = 0;
        $data['table_name'] = 'vip_recharge';
        $data['table_id'] = 0;
        $data['args'] = json_encode(['days'=>$recharge_config['days'],'bundle_id'=>$recharge_config['bundle_id']]);

        $orderid = Db::name('pay_order')->insertGetId($data);

        $this->success('success',$data['out_trade_no']);
    }

    //vip,苹果内购支付回调
    public function vip_notify_ios(){
        $notify_file = $this->notify_log_start('ios');

        //苹果内购的验证收据
        $receipt_data = input('apple_receipt', '', 'trim');
        $order_no = input('order_no', '', 'trim');

        if (!$receipt_data || !$order_no) {
            $this->error('缺少参数');
        }

        Db::startTrans();
        // 查找订单
        $order_info = Db::name('pay_order')->where(['out_trade_no' => $order_no])->lock(true)->find();
        if (!$order_info) {
            Db::rollback();
            $this->error('订单丢失');
        }
        if ($order_info['order_status'] == 1) {
            Db::rollback();
            $this->success('充值成功');
        }

        // 验证支付状态
        $result = $this->validate_apple_pay($receipt_data);
        if (!$result['status']) {// 验证不通过
            Db::rollback();
            $this->error($result['message']);
        }

        $count = count($result['data']['receipt']['in_app']);
        $use_count = $count - 1;
        $args = json_decode($order_info['args'],true);
        if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != $args['bundle_id']) {
            Db::rollback();
            $this->error('非法请求,请立刻停止');
        }

        //逻辑开始
        //先充值
        $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
        if($user_info['vip_endtime'] < time()){
            //过期了
            $vip_endtime = time() + (intval($args['days']) * 86400);
        }else{
            //追加vip
            $vip_endtime = $user_info['vip_endtime'] + (intval($args['days']) * 86400);
        }
        $update_data = [
            'vip_endtime'=>$vip_endtime,
        ];
        $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
        if($result === false)
        {
            Db::rollback();
            $this->error('充值失败');
        }

        // 修改订单状态
        $ros = Db::name('pay_order')->where(['out_trade_no' => $order_no])->update(['order_status'=>1,'notifytime'=>time()]);
        if($ros === false) {
            Db::rollback();
            $this->error('充值失败');
        }

        Db::commit();
        $this->success('充值成功');

        //逻辑结束
    }



    //金币充值
    public function gold_config_ios(){
        $list = Db::name('paygold_webcon_ios')->field('id,money,gold')->where('is_show',1)->order('weigh asc,id asc')->select();
        $data['goldconfig'] = $list;

        $wallet = model('wallet')->getWallet($this->auth->id);
        $data['wallet'] = $wallet;
        $data['money_to_gold'] = config('site.money_to_gold');
        $this->success('success',$data);
    }

    //充值金币 创建订单
    public function gold_recharge_ios(){

        $rc_id     = input_post('rc_id',0);
        $pay_type  = 'ios';
        $platform  = 'app';
        $uid = $this->auth->id;

        if(!$rc_id){
            $this->error('请选择充值金额');
        }

        if(!$this->user_auth_limit()){
            $this->error('请先完成实名认证');
        }

        //赋值money
        $recharge_config = Db::name('paygold_webcon_ios')->where('id',$rc_id)->find();
        $money = $recharge_config['money'] ?: 0;
        $gold  = $recharge_config['gold'] ?: 0;


        //
        if($money<=0)
        {
            $this->error('支付金额必须大于0');
        }
        if($money > 10000){
            $this->error('支付金额太大');
        }

        //创建订单
        $data['user_id'] = $uid;
        $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
        $data['order_amount'] = $money;
        $data['createtime'] = time();

        $data['pay_type'] = $pay_type;
        $data['platform'] = $platform;
        $data['order_status'] = 0;
        $data['table_name'] = 'gold_recharge';
        $data['table_id'] = 0;
        $data['args'] = json_encode(['gold'=>$gold,'bundle_id'=>$recharge_config['bundle_id']]);

        $orderid = Db::name('pay_order')->insertGetId($data);

        $this->success('success',$data['out_trade_no']);
    }

    //vip,苹果内购支付回调
    public function gold_notify_ios(){
        $notify_file = $this->notify_log_start('ios');

        //苹果内购的验证收据
        $receipt_data = input('apple_receipt', '', 'trim');
        $order_no = input('order_no', '', 'trim');

        if (!$receipt_data || !$order_no) {
            $this->error('缺少参数');
        }

        Db::startTrans();
        // 查找订单
        $order_info = Db::name('pay_order')->where(['out_trade_no' => $order_no])->lock(true)->find();
        if (!$order_info) {
            Db::rollback();
            $this->error('订单丢失');
        }
        if ($order_info['order_status'] == 1) {
            Db::rollback();
            $this->success('充值成功');
        }

        // 验证支付状态
        $result = $this->validate_apple_pay($receipt_data);
        if (!$result['status']) {// 验证不通过
            Db::rollback();
            $this->error($result['message']);
        }

        $count = count($result['data']['receipt']['in_app']);
        $use_count = $count - 1;
        $args = json_decode($order_info['args'],true);
        if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != $args['bundle_id']) {
            Db::rollback();
            $this->error('非法请求,请立刻停止');
        }

        //逻辑开始
        //先充值
        $result = model('Wallet')->lockChangeAccountRemain($order_info['user_id'],'gold',$args['gold'],10, '金币充值','pay_order',$order_info['id']);
        if($result['status']===false)
        {
            Db::rollback();
            return false;
        }

        // 修改订单状态
        $ros = Db::name('pay_order')->where(['out_trade_no' => $order_no])->update(['order_status'=>1,'notifytime'=>time()]);
        if($ros === false) {
            Db::rollback();
            $this->error('充值失败');
        }

        Db::commit();
        $this->success('充值成功');

        //逻辑结束
    }

///////////////////////////////////////////////////////////////////////////////////////////////
    //异步日志
    private function notify_log_start($paytype = 'ios'){
        //记录支付回调数据
        ignore_user_abort(); // run script in background
        set_time_limit(30);
        // 日志文件 start
        $log_base_dir = '../paylog/'.$paytype.'/';
        if (!is_dir($log_base_dir))
        {
            mkdir($log_base_dir, 0770, true);
            @chmod($log_base_dir, 0770);
        }
        $notify_file = $log_base_dir.'notify.txt';
        if(!file_exists($notify_file)) {
            @touch($notify_file);
            @chmod($notify_file, 0770);
        }
        if(filesize($notify_file)>5242880)//大于5M自动切换
        {
            rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
        }
        if(!file_exists($notify_file)) {
            @touch($notify_file);
            @chmod($notify_file, 0770);
        }
        // 日志文件 end
        //开始写入
        $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
        if($_REQUEST && $paytype == 'alipay') {
            file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
        } else {
            $xml = file_get_contents("php://input");
            file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
            $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
            file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);
        }

        ini_set('display_errors','On');

        return $notify_file;

    }

    /**
     * 验证AppStore内付
     * @param string $receipt_data 付款后凭证
     * @return array                验证是否成功
     */
    function validate_apple_pay($receipt_data = '') {
        // 验证参数
        if (strlen($receipt_data) < 20) {
            $result = array(
                'status' => false,
                'message' => '非法参数'
            );
            return $result;
        }
        // 请求验证
        $html = $this->curl($receipt_data);
        $data = json_decode($html, true);
//        p($data);die;

        if ($data['status'] == '21002') {
            $this->error('21002');
        }

        // 如果是沙盒数据 则验证沙盒模式 21008;正式数据 21007
//        if ($data['status'] == '21007') {
//            // 请求验证
//            $html = $this->curl($receipt_data, 1);
//            $data = json_decode($html, true);
//            $data['sandbox'] = '1';
//        }
        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }
//        if ($data['receipt']['bundle_id'] != 'com.liuniukeji.mayivideo') {
        if ($data['receipt']['bundle_id'] != 'com.huxiu.tken') {
            $result = array(
                'status' => false,
                'message' => '非法请求',
                'data' => $data
            );
            return $result;
        }
        // 判断是否购买成功
        if (intval($data['status']) === 0) {
            $result = array(
                'status' => true,
                'message' => '购买成功',
                'data' => $data
            );
        } else {
            $result = array(
                'status' => false,
                'message' => '购买失败 status:' . $data['status']
            );
        }

        return $result;
    }

    /**
     * 21000 App Store不能读取你提供的JSON对象25
     * 21002 receipt-data域的数据有问题
     * 21003 receipt无法通过验证
     * 21004 提供的shared secret不匹配你账号中的shared secret
     * 21005 receipt服务器当前不可用
     * 21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
     * 21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
     * 21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
     */
    function curl($receipt_data, $sandbox = 0) {
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS, 320);
//        $POSTFIELDS = '{' . '"receipt-data":' . '"' . $receipt_data . '"' .'}';
//        p($POSTFIELDS);die;
        //正式购买地址 沙盒购买地址
        $url_buy = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
//        if ($sandbox > 0) {
        if (config('site.ios_pay_sandbox') > 0) {
            $url = $url_buy;
        } else {
            $url = $url_sandbox;
        }

        // 上架通过直接使用正式地址
//        $url = $url_sandbox;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加,不加会报SSL 错误
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        curl_close($ch);

        if ($errno != 0) {
            return $errno;
        } else {
            return $response;
        }
    }

}