<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Db;
use addons\epay\library\Service;
use think\Exception;
use addons\unishop\extend\Hashids;
/**
 * 支付订单，回调订单
 */
class Unishop extends Api
{
    protected $noNeedLogin = ['order_notify_base'];
    protected $noNeedRight = ['*'];

    //支付订单
    public function pay_order(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }
        $pay_type = input('pay_type','alipay');
        $platform = input('platform','app');
        $orderid = input('order_id',0);

        if(empty($orderid)){
            $this->error();
        }
        $orderid = Hashids::decodeHex($orderid);

        if(!in_array($pay_type,['wechat','alipay','wallet'])){
            $this->error();
        }

        $uid = $this->auth->id;
        $map = [
            'id'       => $orderid,
            'user_id'  => $uid,
            'status'   => 1,
            'have_paid'=> 0,
        ];
        $orderinfo = Db::name('unishop_order')->where($map)->find();
        if(empty($orderinfo)){
            $this->error('请刷新重试');
        }

        //余额支付
        if($pay_type == 'wallet'){
            Db::startTrans();

            //扣钱
            $rs_wallet = model('wallet')->lockChangeAccountRemain($this->auth->id,'money',-$orderinfo['total_price'],31,'商城购物','unishop_order',$orderid);
            if($rs_wallet['status'] == false){
                Db::rollback();
                $this->error($rs_wallet['msg']);
            }

            //订单改为已支付
            $order_update['pay_type'] = 2;
            $order_update['have_paid'] = time();
            $update_rs = Db::name('unishop_order')->where($map)->update($order_update);
            if(!$update_rs){
                Db::rollback();
                $this->error('支付失败,重试一下吧');
            }

            Db::commit();

            $result = [
                'pay_type' => $pay_type,
                'pay_params' => '',
            ];
            $this->success(1,$result);
        }

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

        $data['pay_type'] = $pay_type;
        $data['platform'] = $platform;
        $data['order_status'] = 0;
        $data['table_name'] = 'unishop_order';
        $data['table_id'] = $orderid;

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

        //下单
        $params = [
            'type'         => $pay_type,
            'orderid'      => $data['out_trade_no'],
            'title'        => '支付订单',
            'amount'       => $data['order_amount'],
//            'amount'       => 0.01,
            'method'       => $platform,
            'notifyurl' => config('pay_notify_url').'/api/unishop/order_notify_base/paytype/'.$pay_type,
            'returnurl' => '',
        ];

        $res = Service::submitOrder($params);

        $result = [
            'pay_type'=> $pay_type,
            'pay_params'=> $pay_type

        ];
        if($pay_type == 'wechat'){
            $result['pay_params'] = json_decode($res,true);
        }else{
            $result['pay_params'] = $res;
        }

        $this->success(1,$result);
    }

    //异步回调对外方法
    public function order_notify_base(){

        //验签
        $paytype = input('paytype','alipay');
        $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->order_notify_do($out_trade_no,$paytype);
        if($rs === false){
            //不论结果都应返回success
            return $pay->success()->send();
            exit;
        }else{
            //不论结果都应返回success
            return $pay->success()->send();
            exit;
        }

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

    //异步逻辑
    private function order_notify_do($out_trade_no,$paytype){

        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;
        }

        //逻辑开始
        $nowtime = time();

        $paytype_enum = [
            'wechat' => 3,
            'alipay' => 4,
        ];

        //订单改为已支付
        $update = [
            'have_paid'=>$nowtime,
            'pay_type' =>$paytype_enum[$paytype],
            'pay_out_trade_no' =>$out_trade_no,
        ];
        $rs_order = Db::name('unishop_order')->where('id',$orderInfo['table_id'])->update($update);
        if($rs_order === 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;
        }

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


    }



    //异步日志
    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;

    }


}
