<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/13
 * Time: 11:31
 */

namespace app\api\controller;


use app\common\controller\Api;
use EasyWeChat\Foundation\Application;
use RongCloud\RongCloud;
use think\Db;
use EasyWeChat\Payment\Order;
use think\Log;

/**
 * 支付回调(无需调用)
 */
class Pay extends Api
{
    protected $options;
    function _initialize()
    {
        parent::_initialize();
        $this->options = [
            'app_id'  => config('app_id'),
            'secret'  => config('app_secrets'),
            'payment' => [
                'merchant_id'        => config('wx_mch_id'),
                'key'                => config('wx_pay_key'),
                'cert_path'          => config('cert_path'),
                'key_path'           => config('key_path'),
            ],
        ];
    }

    /**
     * 支付回调
     * @throws \EasyWeChat\Core\Exceptions\FaultException
     */
    public function notify(){
        $app = new Application($this->options);
        $response = $app->payment->handleNotify(function($notify, $successful){

            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no=$notify->out_trade_no;
            $order = Db::name('order')->where(['num'=>$out_trade_no])->find();
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order['status'] != 1) { // 判断是否已经支付
                return true; // 已经支付成功了就不再更新了
            }

            $update['transaction_id'] = $notify->transaction_id;
            //判断用户是否有邀请人
            $invite = Db::name('user')->where('id',$order['user_id'])->find();
            if(empty($invite['invite_id'])){
                // 用户是否支付成功
                if ($successful) {
                    Db::startTrans();
                    $update['status'] = 2;
                    $update['paytime'] = time();
                    $update['expirationtime'] = $update['paytime'] + 86400*7;
                    $update['finish_status'] = 1;
                    Db::name('teacher')->where('id',$order['teacher_id'])->setInc('help_num');
                    // 创建融云用户、群组
                    $teacher_id = Db::name('teacher')->where('id',$order['teacher_id'])->value('user_id');
                    $rongyun_chat = $this->rongyun_handle($order['user_id'].','.$teacher_id);
                    if($rongyun_chat) {
                        $update['chat_id'] = $rongyun_chat['chat_id'];
                        $update['chat_name'] = $rongyun_chat['chat_name'];
                    }
                } else { // 用户支付失败
                    $update['status']=1;
                }
                Db::name('order')->where('num',$out_trade_no)->update($update);
                Db::commit();
                return true; // 返回处理完成
            }else{

                //判断邀请的用户是否第一次购买
                $is_one = Db::name('order')->where('user_id',$order['user_id'])->where('status',2)->find();

                if(empty($is_one)){
                    // 用户是否支付成功
                    if ($successful) {
                        Db::startTrans();
                        $update['status'] = 2;
                        $update['paytime'] = time();
                        $update['expirationtime'] = $update['paytime'] + 86400*7;
                        $update['finish_status'] = 1;
                        //查询优惠劵金额
                        $you = Db::name('setvalid')->where('id',1)->find();
                        $coupon['user_id'] = $invite['invite_id'];
                        $coupon['money'] = $you['money'];
                        $coupon['createtime'] = time();
                        $coupon['expirationtime'] = $coupon['createtime']+7*86400;
                        Db::name('coupon')->insertGetId($coupon);
                        Db::name('teacher')->where('id',$order['teacher_id'])->setInc('help_num');
                        // 创建融云用户、群组
                        $teacher_id = Db::name('teacher')->where('id',$order['teacher_id'])->value('user_id');
                        $rongyun_chat = $this->rongyun_handle($order['user_id'].','.$teacher_id);
                        if($rongyun_chat) {
                            $update['chat_id'] = $rongyun_chat['chat_id'];
                            $update['chat_name'] = $rongyun_chat['chat_name'];
                        }
                    } else { // 用户支付失败
                        $update['status']=1;
                    }
                    Db::name('order')->where('num',$out_trade_no)->update($update);
                    Db::commit();
                    return true; // 返回处理完成
                }else{
                    // 用户是否支付成功
                    if ($successful) {
                        Db::startTrans();
                        $update['status'] = 2;
                        $update['paytime'] = time();
                        $update['expirationtime'] = $update['paytime'] + 86400*7;
                        $update['finish_status'] = 1;
                        Db::name('teacher')->where('id',$order['teacher_id'])->setInc('help_num');
                        // 创建融云用户、群组
                        $teacher_id = Db::name('teacher')->where('id',$order['teacher_id'])->value('user_id');
                        Log::write(date('Y-m-d H:i') . '用户注册成功,返回结果111:' . json_encode($order, JSON_UNESCAPED_UNICODE), 'rongyun_log');

                        $rongyun_chat = $this->rongyun_handle($order['user_id'].','.$teacher_id,$order['id']);
                        if($rongyun_chat) {
                            $update['chat_id'] = $rongyun_chat['chat_id'];
                            $update['chat_name'] = $rongyun_chat['chat_name'];
                        }
                    } else { // 用户支付失败
                        $update['status']=1;
                    }
                    Db::name('order')->where('num',$out_trade_no)->update($update);
                    Db::commit();
                    return true; // 返回处理完成
                }
            }
        });
        $response->send();
    }

    /**
     * 子订单支付回调
     * @throws \EasyWeChat\Core\Exceptions\FaultException
     */
    public function sonnotify(){
        $app = new Application($this->options);
        $response = $app->payment->handleNotify(function($notify, $successful){

            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no=$notify->out_trade_no;
            $order = Db::name('sonorder')->where(['num'=>$out_trade_no])->find();
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order['status'] != 1) { // 判断是否已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                Db::startTrans();
                $update['status'] = 2;
                $update['paytime'] = time();

                //查出父订单信息
                $info = Db::name('order')
                    ->where('id',$order['order_id'])
                    ->find();
                if($info['expirationtime'] > time()){
                    //未到过期时间
                    Db::name('order')
                        ->where('id',$order['order_id'])
                        ->update(['expirationtime'=>$info['expirationtime']+86400*7,'finish_status'=>1]);
                }else{
                    Db::name('order')
                        ->where('id',$order['order_id'])
                        ->update(['expirationtime'=>$update['paytime'] + 86400*7,'finish_status'=>1]);
                }
            } else { // 用户支付失败
                $update['status']=1;
            }
            Db::name('sonorder')->where('num',$out_trade_no)->update($update);
            Db::commit();
            return true; // 返回处理完成
        });
        $response->send();
    }


    // 融云创建用户、群组
    public function rongyun_handle($user_ids,$order_id) {
        $config = config('rongyun.config'); // 应用配置参数
        $RongSDK = new RongCloud($config['appkey'],$config['appsecret']);
        $users = Db::name('user')->whereIn('id',$user_ids)->column('id,nickname,avatar,rongyun_id,is_create'); // 获取用户信息
        if($users) {
            $user_rongyun_ids = [];
            $User = $RongSDK->getUser();
            foreach ($users as $k=>$v) {
                $user_rongyun_ids[] = [
                    'id' => $v['rongyun_id']
                ];
                if($v['is_create'] == 0) {
                    // 创建新用户
                    $portrait = $v['avatar']; // 头像
                    $user_params = [
                        'id'=> $v['rongyun_id'],//用户id
                        'name'=> $v['nickname'],//用户名称
                        'portrait'=> $portrait //用户头像
                    ];
                    $user_return = $User->register($user_params);
                    if($user_return['code'] == 200) {
                        Db::name('user')->where('id',$v['id'])->update(['is_create'=>1,'rongyun_token'=>$user_return['token']]); // 融云账号状态更新为已创建
                    }
                    Log::write(date('Y-m-d H:i') . '用户注册成功,返回结果:' . json_encode($user_return, JSON_UNESCAPED_UNICODE), 'rongyun_log');
                }
            }
            // 创建群组
            $chat_id = 'xiaowei_teacher'.$order_id;
            $chat_name = '小微问问房间'.$order_id;
            $Group = $RongSDK->getGroup();
            $group_params = [
                'id'=> $chat_id,//群组 id
                'name'=> $chat_name,//群组名称
                'members'=> $user_rongyun_ids //群成员 列表
            ];
            $group_return = $Group->create($group_params);
            Log::write(date('Y-m-d H:i') . '创建群组成功,返回结果:' . json_encode($group_return, JSON_UNESCAPED_UNICODE), 'rongyun_log');
            return [
                'chat_id' => $chat_id,
                'chat_name' => $chat_name
            ];
        }
        return [];
    }
}