<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service;
use app\common\library\Tenim;
/**
 * 订单支付回调
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];



    //充值金币 异步回调对外方法
    public function recharge_notify_base(){

        //验签
        $paytype = input('paytype','wechat');
        $notify_file = $this->notify_log_start($paytype);
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            exit;
        }

        //验证，拿订单号等信息
        $data = $pay->verify();
        $out_trade_no = $data['out_trade_no'];
        //订单查询
        $info = Db::name('pay_order')->where('out_trade_no',$out_trade_no)->find();

        if(empty($info)){
            return $pay->success()->send();
            exit;
        }

        if($info['order_status'] != 0)
        {
            return $pay->success()->send();
            exit;
        }
        //你可以在此编写订单逻辑
        $rs = $this->recharge_notify_do($out_trade_no);
        if($rs === false){
            //不论结果都应返回success
            return $pay->success()->send();
            exit;
        }else{
            //不论结果都应返回success
            return $pay->success()->send();
            exit;
        }

        //默认
        return $pay->success()->send();
        exit;
    }

    public function recharge_notify_test(){
        $out_trade_no = input('out_trade_no');
        $rs = $this->recharge_notify_do($out_trade_no);
        dump($rs);
    }

    //充值金币 逻辑
    public function recharge_notify_do($out_trade_no,$log_type = 10,$remark = '余额充值'){

        Db::startTrans();
        $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
        if (empty($orderInfo)) {
            Db::rollback();
            return false;
        }

        if($orderInfo['order_status'] != 0){
            Db::rollback();
            return false;
        }

        $user_id = $orderInfo['user_id'];

        //逻辑开始
        $args = json_decode($orderInfo['args'],true);
        $giftmoney = isset($args['giftmoney']) ? $args['giftmoney'] : 0;
        $rechargemoney = bcadd($orderInfo['order_amount'],$giftmoney,2);
        $result = model('Wallet')->lockChangeAccountRemain($user_id,'money',$rechargemoney,$log_type, $remark,'pay_order',$orderInfo['id']);
        if($result['status']===false)
        {
            Db::rollback();
            return false;
        }
        //逻辑结束


        //状态
        $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
        if($ros === false) {
            Db::rollback();
            return false;
        }

        //vip价格
        $user_info = Db::name('user')->field('is_vipprice')->where('id',$user_id)->find();
        if($user_info['is_vipprice'] == 0){
            $recharge_sum = Db::name('user_money_log')->where('user_id',$user_id)->where('log_type','IN',[10,15])->sum('change_value');
            if($recharge_sum >= config('site.vipprice_recharge_sum')){
                Db::name('user')->where('id',$user_id)->update(['is_vipprice' => 1]);
            }
        }

        //我的
        $user_wallet = Db::name('user_wallet')->field('intro_level,money,intro_uid')->where('user_id',$user_id)->find();

        //上级
        $intro_uid = $user_wallet['intro_uid'];
        $up_wallet = Db::name('user_wallet')->field('intro_level,money,intro_uid')->where('user_id',$intro_uid)->find();

        //星级配置
        $intro_level_config = Db::name('intro_level_config')->order('id asc')->select();
//        $intro_level_column = array_column($intro_level_config,'intro_bili','id'); // [id => intro_bili]

        //入金升级
        if($orderInfo['order_amount'] >= config('site.intro_rujin_money')){

            //自己入金
            if($user_wallet['intro_level'] == '-1'){

                //看看直推了几个，就给升到对应的星级
                $intro_num = Db::name('user_wallet')->where('intro_uid',$user_id)->where('intro_level','neq','-1')->count();//我直推的个数（入金的）
                $level = $this->get_intro_level($intro_level_config,$intro_num);
                Db::name('user_wallet')->where('user_id',$user_id)->update(['intro_level'=>$level]); //我升级了,最低入金，最高顶级

                //上级升级
                if($up_wallet && $up_wallet['intro_level'] != 5){
                    //看看直推了几个，就给升到对应的星级
                    $intro_num = Db::name('user_wallet')->where('intro_uid',$intro_uid)->where('intro_level','neq','-1')->count();//直推的个数（入金的）
                    $level = $this->get_intro_level($intro_level_config,$intro_num);
                    Db::name('user_wallet')->where('user_id',$intro_uid)->update(['intro_level'=>$level]); //升级了
                }
            }

        }

        //提成
        $chuju = config('site.intro_chuju_min_money');
        if($user_wallet['money'] >= $chuju && $user_wallet['intro_level'] != '-1'){
        if($up_wallet && $up_wallet['money'] >= $chuju && $up_wallet['intro_level'] != '-1' && $up_wallet['intro_level'] >= $user_wallet['intro_level']){

            //上级提成
            $intro_intro_recharge_bili = config('site.intro_intro_recharge_bili');//比例
            $intro_money = bcdiv(bcmul($orderInfo['order_amount'],$intro_intro_recharge_bili,2),100,2);
            if($intro_money > 0){
                $result = model('Wallet')->lockChangeAccountRemain($intro_uid,'intromoney',$intro_money,101, '直推充值'.$orderInfo['order_amount'],'pay_order',$orderInfo['id']);
                if($result['status']===false)
                {
                    Db::rollback();
                    return false;
                }
            }

            //上上级提成
            $top_uid = $up_wallet['intro_uid'];
            $top_wallet = Db::name('user_wallet')->field('intro_level,money')->where('user_id',$top_uid)->find();
            if($top_wallet && $top_wallet['money'] >= $chuju && $top_wallet['intro_level'] != '-1' && $top_wallet['intro_level'] >= $up_wallet['intro_level']){

                $intro_top_recharge_bili = config('site.intro_top_recharge_bili'); //比例
                $top_money = bcdiv(bcmul($orderInfo['order_amount'],$intro_top_recharge_bili,2),100,2);
                if($top_money > 0){
                    $result = model('Wallet')->lockChangeAccountRemain($top_uid,'intromoney',$top_money,102, '间推充值'.$orderInfo['order_amount'],'pay_order',$orderInfo['id']);
                    if($result['status']===false)
                    {
                        Db::rollback();
                        return false;
                    }
                }
            }

        }
        }


        //默认提交
        Db::commit();
        return true;
    }

    //根据直推人数，得出应升的等级
    private function get_intro_level($intro_level_config,$intro_num){
        $rs = 0;
        foreach($intro_level_config as $key => $level){
            if($intro_num >= $level['intro_count']){
                $rs = $level['id'];
            }
        }
        return $rs;
    }


////////////////////////////////////////////////////////////////////////



    //异步日志
    private function notify_log_start($paytype = 'wechat'){
        //记录支付回调数据
        ignore_user_abort(); // run script in background
        set_time_limit(30);
        // 日志文件 start
        $log_base_dir = '../epaylog/'.$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;

    }
}
