<?php

namespace app\api\controller;

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

    //支付订单
    //微信小程序、微信app下单使用。
    public function pay_order(){
        $pay_type = input('pay_type','wechat');
        $platform = input('platform','miniapp');
        $orderid = input('orderid','0');
        $uid = $this->auth->id;

        $orderinfo = Db::name('order')->where('id',$orderid)->where('user_id',$uid)->find();

        //创建订单
        $data['user_id'] = $uid;
        $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
        $data['order_amount'] = $orderinfo['pay_fee'];
        $data['createtime'] = time();
        $data['pay_type'] = $pay_type;
        $data['order_status'] = 0;
        $data['table_name'] = 'order';
        $data['table_id'] = $orderid;

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

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

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

        if($pay_type == 'wechat'){
            $this->success('success',json_decode($res,true));
        }else{
            $this->success('success',$res);
        }
    }

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

        //验签
        $paytype = input('paytype','wechat');
        $func = input('func','order_notify_do');
        $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->$func($out_trade_no);
        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){

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

        //逻辑开始
        $update = [
            'status'=>10,
            'paytime'=>time(),
            'pay_type'=>$orderInfo['pay_type'],
            'pay_out_trade_no'=>$out_trade_no,
        ];
        $rs_order = Db::name('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 = '../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;

    }

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



    //微信小程序充值
    public function pay_recharge()
    {
        Db::startTrans();
        try {
            $pay_type = input('pay_type','wechat');
            $platform = input('platform','miniapp');
            $id = input('id','0');
            $amounts = intval(input('amounts',0));
            $uid = $this->auth->id;
            $companyId = $this->auth->company_id;
            if (empty($id) && empty($amounts)) {
                throw new Exception('参数错误');
            }
            $gift_amount = 0.00;
            if (!empty($id)) {//验证充值配置
                $where['status'] = 1;//上架
                $orderinfo = Db::name('recharge_config')->where('id',$id)->where($where)->find();
                if (empty($orderinfo)) {
                    throw new Exception('未获取到充值套餐信息');
                }
                $order_amount = $orderinfo['price'];
                $gift_amount = $orderinfo['giftprice'];
            } else {
                $isInt = is_int($amounts);
                if (!$isInt) {
                    throw new Exception('请输入整数');
                }
                if ($amounts < 1) {
                    throw new Exception('充值金额有误');
                }
                $order_amount = $amounts;
            }

            //创建订单
            $data['company_id'] = $companyId;
            $data['user_id'] = $uid;
            $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
            $data['order_amount'] = $order_amount;
            $data['gift_amount'] = $gift_amount;
            $data['createtime'] = time();
            $data['pay_type'] = $pay_type;
            $data['order_status'] = 0;
            $data['table_name'] = 'recharge_config';
            $data['table_id'] = $id;

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

            $openid = $this->auth->mini_openid;
            $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
            $payTest = config('param.pay_test');
            $orderAmount = $payTest == 1 ? 0.01 : $data['order_amount'];
            //下单
            $params = [
                'type'         => $pay_type,
                'orderid'      => $data['out_trade_no'],
                'title'        => '余额充值',
                'amount'       => $orderAmount,
                'method'       => $platform,
                'openid'       => $openid,
                'notifyurl' => $httpStr.'/api/pay/order_notify_base/paytype/'.$pay_type.'/func/recharge',
                'returnurl' => '',
            ];

            $res = Service::submitOrder($params);
            Db::commit();
            if($pay_type == 'wechat'){
                $this->success('充值成功',json_decode($res,true));
            }else{
                $this->success('充值成功',$res);
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 充值到账
     * @param $out_trade_no
     * @return bool
     */
    private function recharge($out_trade_no)
    {
        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;
        }
        //赠送优惠券
        $rg = 'recharge_gift';
        $c = 'coupons';
        $field = $rg.'.*,'.$c.'.name,'.$c.'.info,'.$c.'.days';
        $rechargeGiftWhere['config_id'] = $orderInfo['table_id'];
        $rechargeGiftWhere[$c.'.status'] = 1;
        $rechargeGift = Db::name($rg)->alias($rg)->field($field)
            ->join($c,$c.'.id = '.$rg.'.coupon_id','LEFT')->where($rechargeGiftWhere)->select();
        if (!empty($rechargeGift)) {
            $time = time();
            foreach ($rechargeGift as $key => $value) {
                $endtime = $time + 86400 * $value['days'];
                $userCouponsData[] = [
                    'user_id' => $orderInfo['user_id'],
                    'company_id' => $orderInfo['company_id'],
                    'coupons_id' => $value['coupon_id'],
                    'coupon_name' => $value['name'],
                    'coupon_info' => $value['info'],
                    'createtime' => $time,
                    'endtime' => $endtime,
                    'number' => $value['number'],
                    'remain' => $value['number'],
                    'payorder_id' => $orderInfo['id'],
                    'getfrom' => '充值赠送',
                ];
            }
            $userCouponsRes = Db::name('user_coupons')->insertAll($userCouponsData);
            if (!$userCouponsRes) {
                throw new Exception('赠送优惠失败');
            }
        }
        $userWalletWhere['user_id'] = $orderInfo['user_id'];
        $userWalletWhere['company_id'] = $orderInfo['company_id'];
        $userWalletData = Db::name('user_wallet')->where($userWalletWhere)->find();
        $before = isset($userWalletData['money']) ? $userWalletData['money'] : 0.00;
        $changeValue = bcadd($orderInfo['order_amount'],$orderInfo['gift_amount'],2);
        $remain = bcadd($before,$changeValue,2);
        $time = time();
        //逻辑开始 记录充值明细
        $userMoneyLogData = [
            'user_id'      => $orderInfo['user_id'],
            'company_id'   => $orderInfo['company_id'],
            'log_type'     => 104, //日志类型 104
            'before'       => $before, //之前余额
            'change_value' => $changeValue, //变动金额
            'remain'       => $remain, //剩余金额
            'table'        => 'pay_order', //数据来源
            'table_id'     => $orderInfo['id'], //数据来源ID
            'remark'       => '余额充值', //remark
            'createtime'   => $time,
            'updatetime'   => $time,
        ];
        $userMoneyLogRes = Db::name('user_money_log')->insertGetId($userMoneyLogData);
        if (!$userMoneyLogRes) {
            throw new Exception('充值记录失败');
        }
        //更新钱包余额
        $update = [
            'money' => $remain,
            'updatetime' => $time,
        ];
        $rs_order = Db::name('user_wallet')->where($userWalletWhere)->update($update);
        if(!$rs_order){
            Db::rollback();
            return false;
        }
        //商家端金额更新
        $companyWalletWhere['user_id'] = $orderInfo['company_id'];
        $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->find();
        $companyMoneyBefore = isset($companyWalletRes['money']) ? $companyWalletRes['money'] : 0.00;
        $companyMoneyNew = bcadd($companyMoneyBefore,$orderInfo['order_amount'],2);
        $companyMoneyData = [
            'money' => $companyMoneyNew,
        ];
        $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->update($companyMoneyData);
        if (!$companyWalletRes) {
            Db::rollback();
            return false;
        }
        //商家端记录日志
        $companyMoneyLogData = [
            'user_id'      => $orderInfo['user_id'],//用户ID
            'log_type'     => 204,//日志类型
            'before'       => $companyMoneyBefore,//之前余额
            'change_value' => $orderInfo['order_amount'],//变动金额
            'remain'       => $companyMoneyNew,//剩余金额
            'table'        => 'pay_order',//数据来源
            'table_id'     => $orderInfo['id'],//数据来源ID
            'remark'       => '充值',//备注
            'createtime'   => $time, //创建时间
            'updatetime'   => $time, //更新时间
        ];
        $companyMoneyLogRes = Db::name('company_money_log')->insertGetId($companyMoneyLogData);
        if (!$companyMoneyLogRes) {
            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;
    }

    /**
     * 购买套餐
     * @return void
     * @throws \Exception
     */
    public function package()
    {
        Db::startTrans();
        try {
            $pay_type = input('pay_type','wechat');//支付类型:wallet=余额,wechat=微信
            $platform = input('platform','miniapp');
            $id = input('package_id','0');
            $carId = input('car_id','0');
            $uid = $this->auth->id;
            $companyId = $this->auth->company_id;
            $miniOpenId = $this->auth->mini_openid;
            if (empty($id)) {
                throw new Exception('请选择套餐');
            }
            if (empty($carId)) {
                throw new Exception('请选择车辆');
            }
            $orderService = new OrderService();
            $params = [
                'pay_type' => $pay_type,
                'platform' => $platform,
                'package_id' => $id,
                'car_id' => $carId,
                'user_id' => $uid,
                'company_id' => $companyId,
                'mini_openid' => $miniOpenId,
            ];
            $orderRes = $orderService->orderPay($params);
            if (!$orderRes['status']) {
                throw new Exception($orderRes['msg']);
            }
            $res = $orderRes['data'];
            Db::commit();
            $this->success('操作成功',$res);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 购买套餐回调
     * @param $out_trade_no
     * @return bool
     */
    private function package_do($out_trade_no)
    {
        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;
        }
        $orderService = new OrderService();
        $extData = json_decode($orderInfo['ext_data'], true);
        $carId = isset($extData['car_id']) ? $extData['car_id'] : 0;
        $params = [
            'package_id' => $orderInfo['table_id'],
            'company_id' => $orderInfo['company_id'],
            'user_id' => $orderInfo['user_id'],
            'car_id' => $carId,
            'pay_order_id' => $orderInfo['id'],
            'order_paytype' => 3,//支付方式:1=线下,2=余额,3=微信
        ];
        $orderRes = $orderService->addOrder($params);
        if (!$orderRes['status']) {
            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;
    }

}
