<?php

namespace App\Http\Controllers\WeChat;

use App\Models\CheckCard;
use App\Models\Content;
use App\Models\FormData;
use App\Models\FormSet;
use App\Models\Leave;
use App\Models\Order;
use App\Models\Remark;
use App\Models\RemarkDetail;
use App\Models\RemarkTitle;
use App\Models\Setting;
use App\Models\Student;
use App\Models\StudentCourse;
use App\Models\StudentCourseTeacher;
use App\Models\Teacher;
use App\Models\WeChatUser;
use Carbon\Carbon;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ApiController extends Controller
{
    public function login(Request $request)
    {
        if(empty($request->input('code'))) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $app = app('wechat.mini_program');
        $res = $app->auth->session($request->input('code'));

        if(!isset($res['session_key'])) {
            return response()->json(['status' => 'error', 'info' => '接口错误']);
        }
        $res = WeChatUser::updateOrCreate([
            'open_id' => $res['openid'],
        ], [
            'code' => $request->input('code'),
            'session_key' => $res['session_key'],
        ]);

        if(empty($res)) {
            return response()->json(['status' => 'error', 'info' => '数据库错误']);
        }

        return response()->json(['status' => 'success', 'id' => $res->id]);

//        if(empty($request->input('code')) || empty($request->input('iv')) || empty($request->input('encryptedData'))) {
//            return response()->json(['status' => 'error', 'info' => '参数错误']);
//        }
//        $code = $request->input('code');
//        $iv = $request->input('iv');
//        $encryptedData = $request->input('encryptedData');
//        $app = app('wechat.mini_program');
//        $res = $app->auth->session($code);
//
//        if(!isset($res['session_key'])) {
//            return response()->json(['status' => 'error', 'info' => '接口错误']);
//        }
//
//        $info = $app->encryptor->decryptData($res['session_key'], $iv, $encryptedData);
//
//        if(!isset($info['openId'])) {
//            return response()->json(['status' => 'error', 'info' => '接口错误']);
//        }
//
//        $student = Student::firstOrCreate([
//            'open_id' => $info['openId']
//        ], [
//            'nickname' => $info['nickName'],
//            'gender' => $info['gender'],
//            'city' => $info['city'],
//            'province' => $info['province'],
//            'country' => $info['country'],
//            'avatar_url' => $info['avatarUrl'],
//            'name' => $info['nickName'],
//            'short_leave_times' => 0,
//            'long_leave_times' => 0,
//        ]);
//
//        $data = ['id' => $student->id, 'nickname' => $student->nickname, 'avatar_url' => $student->avatar_url];
//        return response()->json(['status' => 'success', 'info' => '操作成功', 'data' => $data]);
    }

    public function updateUserInfo(Request $request)
    {
        if(empty($request->input('id')) || empty($we_chat_user = WeChatUser::find($request->input('id'))) || empty($we_chat_user->session_key)) {
            return response()->json(['status' => 'error', 'info' => '参数错误11']);
        }
        if(empty($request->input('iv')) || empty($request->input('encryptedData'))) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $iv = $request->input('iv');
        $encryptedData = $request->input('encryptedData');
        $session_key = $we_chat_user->session_key;
        $app = app('wechat.mini_program');


        $info = $app->encryptor->decryptData($session_key, $iv, $encryptedData);

        if(!isset($info['openId'])) {
            return response()->json(['status' => 'error', 'info' => '接口错误']);
        }

        $res = $we_chat_user->update([
            'nickname' => $info['nickName'],
            'gender' => $info['gender'],
            'city' => $info['city'],
            'province' => $info['province'],
            'country' => $info['country'],
            'avatar_url' => $info['avatarUrl']
        ]);

        if(empty($res)) {
            return response()->json(['status' => 'error', 'info' => '更新错误']);
        }

//        $student = Student::firstOrCreate([
//            'open_id' => $info['openId']
//        ], [
//            'nickname' => $info['nickName'],
//            'gender' => $info['gender'],
//            'city' => $info['city'],
//            'province' => $info['province'],
//            'country' => $info['country'],
//            'avatar_url' => $info['avatarUrl'],
//            'name' => $info['nickName'],
//            'short_leave_times' => 0,
//            'long_leave_times' => 0,
//        ]);

        $data = ['id' => $we_chat_user->id, 'nickname' => $we_chat_user->nickname, 'avatar_url' => $we_chat_user->avatar_url];
        return response()->json(['status' => 'success', 'info' => '操作成功', 'data' => $data]);
    }

    public function getPhone(Request $request)
    {
        if(empty($request->input('id')) || empty($we_chat_user = WeChatUser::find($request->input('id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户']);
        }
        if(empty($request->input('iv')) || empty($request->input('encryptedData'))) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $iv = $request->input('iv');
        $encryptedData = $request->input('encryptedData');
        $session_key = $we_chat_user->session_key;
        $app = app('wechat.mini_program');


        $info = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
        if(isset($info['purePhoneNumber'])) {
            return response()->json(['status' => 'success', 'info' => '操作成功', 'phone' => $info['purePhoneNumber']]);
        }
        return response()->json(['status' => 'fail', 'info' => '没有绑定手机']);
    }

    public function bindPhone(Request $request)
    {
        if(empty($request->input('id')) || empty($we_chat_user = WeChatUser::find($request->input('id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户']);
        }
        if(empty($request->input('phone')) || empty($student = Student::where('phone', $request->input('phone'))->first())) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }

        $res = $student->update([
            'open_id' => $we_chat_user->open_id,
            'nickname' => $we_chat_user->nickname,
            'gender' => $we_chat_user->gender,
            'city' => $we_chat_user->city,
            'province' => $we_chat_user->province,
            'country' => $we_chat_user->country,
            'avatar_url' => $we_chat_user->avatar_url,
            'bind_phone' => 2
        ]);
        if(empty($res)) {
            return response()->json(['status' => 'fail', 'info' => '数据更新失败']);
        }
        $data = ['id' => $student->id, 'nickname' => $student->nickname, 'avatar_url' => $student->avatar_url];
        return response()->json(['status' => 'success', 'info' => '操作成功', 'data' => $data]);
    }

    public function checkPosition(Request $request)
    {
        if(empty($request->input('latitude')) || empty($request->input('longitude'))) {
            return response()->json(['status' => 'fail', 'info' => '参数错误']);
        }

        $center_position = Setting::where('key', 'check_card_location')->first();
        if(empty($center_position) || empty($center_position->value) || count($tmp = explode(',', $center_position->value)) < 2) {
            $tmp = ['39.916527', '116.397128'];
        }

        $client = new Client();
        $from = $tmp[0] . ',' . $tmp[1];
        $to = $request->input('latitude') . ',' . $request->input('longitude');
        $url = 'https://apis.map.qq.com/ws/distance/v1/?from=' . $from . '&to=' . $to . '&key=' . env('TECENT_POSITION_KEY');
        $res = $client->get($url);
        $res = json_decode((string)$res->getBody());
        $result = 'no';
        if($res->status == 0) {
            $radius = Setting::where('key', 'check_card_radius')->first();
            $radius = empty($radius) ? 1000 : $radius->value;
            $distance = $res->result->elements[0]->distance;
            if($distance <= $radius) {
                $result = 'ok';
            }
        }
        $now = Carbon::today()->toDateTimeString();
        $checkCard = CheckCard::where([
            ['begin_date_time', '>', $now]
        ])->whereNull('end_date_time')->orderBy('begin_date_time', 'desc')->first();

        return response()->json(['status' => 'success', 'result' => $result, 'checkCard' => $checkCard]);
    }

    public function startCheckCard(Request $request)
    {
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }

        $student_course = StudentCourse::where('student_id', $student->id)->first();
        if(empty($student_course)) {
            return response()->json(['status' => 'fail', 'info' => '暂无课程']);
        }

        $res = CheckCard::create([
            'student_id' => $student_course->student_id,
            'course_id' => $student_course->course_id,
            'student_course_id' => $student_course->id,
            'begin_date_time' => Carbon::now()->toDateTimeString()
        ]);

        if(empty($res)) {
            return response()->json(['status' => 'fail', 'info' => '创建失败']);
        }
        return response()->json(['status' => 'success', 'check_card_id' => $res->id, 'info' => '操作成功']);
    }

    public function endCheckCard(Request $request)
    {
        if(empty($request->input('check_card_id')) || empty($item = CheckCard::find($request->input('check_card_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到打卡记录']);
        }

        $item->end_date_time = Carbon::now()->toDateTimeString();
        if(!$item->save()) {
            return response()->json(['status' => 'fail', 'info' => '打卡失败']);
        }

        return response()->json(['status' => 'success', 'info' => '打卡成功']);
    }

    public function getShareInfo(Request $request)
    {
        $share_image = Setting::where('key', 'share_image')->first();
        if(empty($share_image) || empty($share_image->value) || !Storage::disk('upload')->exists($share_image->value)) {
            return response()->json(['status' => 'fail', 'info' => '没有分享图片的信息！']);
        }
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户信息！']);
        }

        $image_url = url($share_image->value);
        $image = Image::make($image_url);
        $items = $student->getCheckCardDates();
        $share_text = Setting::where('key', 'share_text')->first();
        if(empty($share_text) || empty($share_text->value)) {
            return response()->json(['status' => 'fail', 'info' => '找不到分享的文字！']);
        }
        $now = Carbon::now()->toDateString();
        $count = $items->contains($now) ? $items->count() : $items->count() + 1;
        $text = str_replace_array('{days}', [$count], $share_text->value);
        $share_text_pos = Setting::where('key', 'share_text_pos')->first();
        if(empty($share_text_pos) || empty($share_text_pos->value) || count($pos = explode(',', $share_text_pos->value)) < 2) {
            return response()->json(['status' => 'fail', 'info' => '分享文字位置错误或未设置！']);
        }

        return response()->json(['status' => 'success', 'width' => $image->width(), 'height' => $image->height(), 'shareImage' => $image_url, 'shareText' => $text, 'shareTextPosX' => $pos[0], 'shareTextPosY' => $pos[1]]);
    }

    public function getMoreVideosAndArticles(Request $request)
    {
        $video_offset = $request->input('video_offset', 0);
        $article_offset = $request->input('article_offset', 0);
        if(empty($request->input('type')) || !in_array($request->input('type'), ['both', 'video', 'article'])) {
            return response()->json(['status' => 'fail', 'info' => '参数错误']);
        }
        if($request->input('type') == 'both') {
            $video_list = Content::where('type', 3)->orderBy('sort')->offset($video_offset)->limit(15)->get();
            foreach($video_list as $item) {
                if(empty($item->pic_url)) {
                    $item->pic_url = 'https://u5.9026.com/addons/swdz_mall/core/web/uploads/image/f0/f0734ad93d46497483344846864596a4.jpg';
                } else {
                    $item->pic_url = url($item->pic_url);
                }
                $item->url = url($item->content);
            }
            $article_list = Content::where('type', 4)->orderBy('sort')->offset($article_offset)->limit(15)->get();
            foreach($article_list as $item) {
                $item->publish_date = substr($item->updated_at, 0, 10);
            }
            return response()->json(['status' => 'success', 'video_list' => $video_list, 'article_list' => $article_list, 'type' => $request->input('type')]);
        } else if($request->input('type') == 'video') {
            $list = Content::where('type', 3)->orderBy('sort')->offset($video_offset)->limit(15)->get();
            foreach($list as $item) {
                if(empty($item->pic_url)) {
                    $item->pic_url = 'https://u5.9026.com/addons/swdz_mall/core/web/uploads/image/f0/f0734ad93d46497483344846864596a4.jpg';
                } else {
                    $item->pic_url = url($item->pic_url);
                }
                $item->url = url($item->content);
            }
        } else {
            $list = Content::where('type', 4)->orderBy('sort')->offset($article_offset)->limit(15)->get();
            foreach($list as $item) {
                $item->publish_date = substr($item->updated_at, 0, 10);
            }
        }

        return response()->json(['status' => 'success', 'list' => $list, 'type' => $request->input('type')]);
    }

    public function getAnnounces(Request $request)
    {
        $offset = $request->input('offset', 0);
        $list = Content::whereIn('type', [1])->orderBy('sort')->offset($offset)->limit(15)->get();
        foreach($list as $item) {
            $item->publish_date = substr($item->created_at, 0, 10);
        }
        return response()->json(['status' => 'success', 'list' => $list]);
    }

    public function getCourseInfo(Request $request)
    {
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户信息！']);
        }
        $student_course = StudentCourse::where('student_id', $student->id)->first();
        if(empty($student_course)) {
            return response()->json(['status' => 'fail', 'info' => '找不到课程！']);
        }

        $student_course->course_name = $student_course->course->name;
        $student_course->teacher_names = $student_course->getTeacherNames();
        $student_course->end_date = Carbon::createFromTimestamp(strtotime($student_course->apply_date))->addDays($student_course->duration)->toDateString();
        $student_course->short_leave_times = $student->short_leave_times;
        $student_course->long_leave_times = $student->long_leave_times;

        $is_new = $student->getIsNew();

        return response()->json(['status' => 'success', 'courseInfo' => $student_course, 'is_new' => $is_new]);
    }

    public function getMyLearnInfo(Request $request)
    {
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户信息！']);
        }

        if(empty($request->input('year')) || empty($request->input('month'))) {
            return response()->json(['status' => 'fail', 'info' => '参数错误！']);
        }

        $year = $request->input('year');
        $month = $request->input('month');
        $begin_date_time = Carbon::create($year, $month, 1)->toDateTimeString();
        $end_date_time = Carbon::create($year, $month, 1)->addMonth(1)->toDateTimeString();
        $thisMonthLearnTime = 0;
        $totalLearnTime = 0;
        $checkCardList = collect();
        $items = CheckCard::where('student_id', $student->id)->whereNotNull('begin_date_time')->whereNotNull('end_date_time')->get();
        foreach($items as $item) {
            $duration = strtotime($item->end_date_time) - strtotime($item->begin_date_time);
            $totalLearnTime += $duration;
            if($item->begin_date_time >= $begin_date_time && $item->begin_date_time < $end_date_time) {
                $thisMonthLearnTime += $duration;
                $day = Carbon::createFromTimestamp(strtotime($item->end_date_time))->day;
                $tmp = $checkCardList->where('day', $day);
                if($tmp->count() == 0) {
                    $checkCardList->push(collect(['month' => 'current', 'day' => $day, 'background' => '#fb534b', 'color' => '#ffffff']));
                }
            }
        }
//        $today = $now->day;
//        for($i = 1; $i <= $today; ++$i) {
//            $tmp = $checkCardList->where('day', $i);
//            if($tmp->count() == 0) {
//                $checkCardList->push(collect(['month' => 'current', 'day' => $i, 'color' => '#f65556']));
//            }
//        }

        $thisMonthLearnTime = $this->getHumanTime($thisMonthLearnTime);
        $totalLearnTime = $this->getHumanTime($totalLearnTime);

        $checkCardDays = $student->getCheckCardDates()->count();
        return response()->json(['status' => 'success', 'checkCardList' => $checkCardList, 'thisMonthLearnTime' => $thisMonthLearnTime, 'totalLearnTime' => $totalLearnTime, 'checkCardDays' => $checkCardDays]);
    }

    public function getHumanTime($seconds)
    {
        $res = '';
        $tmp = floor($seconds / 3600);
        $diff_time = $seconds % 3600;
        if(!empty($tmp)) {
            $res .= $tmp . '小时';
        }
        $tmp = floor($diff_time / 3600);
        $diff_time = $diff_time % 60;
        if(!empty($tmp)) {
            $res .= $tmp . '分钟';
        }
        if(!empty($diff_time)) {
            $res .= $diff_time . '秒';
        }
        return $res;
    }

    public function applyLeave(Request $request)
    {
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }
        if(empty($request->input('type')) || !in_array($request->input('type'), [1, 2])) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }
        $student_course = StudentCourse::where('student_id', $student->id)->first();
        if(empty($student_course)) {
            return response()->json(['status' => 'fail', 'info' => '暂无课程']);
        }
        $res = Leave::create([
            'student_id' => $student->id,
            'course_id' => $student_course->course_id,
            'student_course_id' => $student_course->id,
            'type' => $request->input('type'),
            'date' => $request->input('date'),
            'days' => $request->input('days'),
            'remark' => $request->input('remark')
        ]);
        if(!$res) {
            return response()->json(['status' => 'fail', 'info' => '保存失败']);
        }
        return response()->json(['status' => 'success', 'info' => '请假成功']);
    }

    public function getRemarkTitles(Request $request)
    {
        if(empty($request->input('id')) || empty($student = Student::find($request->input('id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }

        if(empty($student_course = StudentCourse::where('student_id', $student->id)->first())) {
            return response()->json(['status' => 'fail', 'info' => '找不到课程']);
        }
        if($student_course->assign_teacher == 1) {
            $teachers = Teacher::all();
        } else {
            $teacher_ids = StudentCourseTeacher::where('student_course_id', $student_course->id)->get()->pluck('teacher_id')->unique();
            $teachers = Teacher::whereIn('id', $teacher_ids)->get();
        }

        $is_new = $student->getIsNew();
        if($is_new) {
            $titles = RemarkTitle::where('status', 2)->get();
            return response()->json(['status' => 'success', 'titles' => $titles, 'teachers' => $teachers, 'is_new' => $is_new]);
        }

        foreach($teachers as $teacher) {
            $remark = Remark::where([
                ['student_id', '=', $student->id],
                ['teacher_id', '=', $teacher->id],
            ])->first();
            if(!empty($remark)) {
                $remark_time = RemarkDetail::where([
                    ['remark_id', '=', $remark->id],
                    ['teacher_id', '=', $teacher->id],
                ])->orderBy('updated_at', 'desc')->first();
                $teacher->remark_time = empty($remark_time) ? '' : substr($remark_time->updated_at, 0, 10);
                $teacher->average_score = $student->getThisWeekAverageScore($remark);
            } else {
                $teacher->remark_time = '';
                $teacher->average_score = 0;
            }
        }

        return response()->json(['status' => 'success', 'titles' => [], 'teachers' => $teachers, 'is_new' => $is_new]);
    }

    public function remarkTeacher(Request $request)
    {
        if(empty($request->input('student_id')) || empty($student = Student::find($request->input('student_id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到学员']);
        }

        $student_course = $student->getStudentCourse();
        if(empty($student_course)) {
            return response()->json(['status' => 'fail', 'info' => '找不到课程']);
        }
//        $student_course_teacher = StudentCourseTeacher::where('student_id', $student->id)->first();
//        if(empty($student_course_teacher)) {
//            return response()->json(['status' => 'fail', 'info' => '找不到讲师']);
//        }
//        $remarks = $request->except(['student_id']);
        $data = $request->input('data');
        if(!is_array($data)) {
            return response()->json(['status' => 'fail', 'info' => '参数错误']);
        }

        foreach($data as $teacher_key => $teacher_value) {
            $teacher = Teacher::find($teacher_key);
            if(empty($teacher) || !is_array($teacher_value)) {
                continue;
            }
            $remark = Remark::firstOrCreate([
                'teacher_id' => $teacher->id,
                'student_id' => $student->id
            ], [
                'course_id' => $student_course->course_id
            ]);
            $remark->updated_at = Carbon::now()->toDateTimeString();
            $remark->save();
            foreach($teacher_value as $title_key => $title_value) {
                $remark_title = RemarkTitle::find($title_key);
                if(!empty($remark_title)) {
                    RemarkDetail::create([
                        'remark_id' => $remark->id,
                        'teacher_id' => $teacher->id,
                        'question' => $remark_title->name,
                        'score' => $title_value,
                    ]);
                }
            }
        }

        return response()->json(['status' => 'success']);
    }

    public function getArticleContent(Request $request)
    {
        if(empty($request->input('id')) || empty($item = Content::find($request->input('id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到文章']);
        }
        $item->content = $this->replaceImageSrc($item->content);
        $item->publish_date = substr($item->created_at, 0, 10);
        return response()->json(['status' => 'success', 'article' => $item]);
    }

    public function replaceImageSrc($img_tag)
    {
        $doc = new \DOMDocument();
        $img_tag = '<meta http-equiv="Content-Type" content="text/html;charset=utf-8">' . $img_tag;
        $doc->loadHTML($img_tag);
        $tags = $doc->getElementsByTagName('img');
        foreach ($tags as $tag) {
            $old_src = $tag->getAttribute('src');
            $new_src_url = url($old_src);
            $tag->setAttribute('src', $new_src_url);
        }
        return $doc->saveHTML();
    }

    public function getFormSet(Request $request)
    {
        $form_set = FormSet::first();
        if(empty($form_set)) {
            return response()->json(['status' => 'fail', 'info' => '找不到数据']);
        }
        if(!empty($form_set->top_image)) {
            $form_set->top_image = url($form_set->top_image);
        }
        if(!empty($form_set->radio_value)) {
            $form_set->radio_value = explode(',', $form_set->radio_value);
        }
        if(!empty($form_set->checkbox_value)) {
            $form_set->checkbox_value = explode(',', $form_set->checkbox_value);
        }
        return response()->json(['status' => 'success', 'data' => $form_set]);
    }

    public function submitForm(Request $request)
    {
        if(empty($request->input('data')) || !is_array($request->input('data'))) {
            return response()->json(['status' => 'fail', 'info' => '参数错误11']);
        }

        $form_set = FormSet::first();
        if(empty($form_set)) {
            return response()->json(['status' => 'fail', 'info' => '参数错误']);
        }

        $data = $request->input('data');
        if(!isset($data['type']) || !in_array($data['type'], ['pay', 'form'])) {
            return response()->json(['status' => 'fail', 'info' => '参数错误']);
        }

        $type = $data['type'];

        $items = ['text_1', 'text_2', 'text_3', 'text_4', 'multi_text', 'radio'];
        foreach($items as $item) {
            if(isset($data[$item])) {
                $data[$item] = $form_set[$item] . ':' . $data[$item];
            }
        }

        if(isset($data['checkbox']) && is_array($data['checkbox'])) {
            $data['checkbox'] = implode(',', $data['checkbox']);
            $data['checkbox'] = $form_set['checkbox'] . ':' . $data['checkbox'];
        }
        unset($data['type']);
        $res = FormData::create($data);
        if(empty($res)) {
            return response()->json(['status' => 'fail', 'info' => '保存失败']);
        }

        $money = $form_set->money;

        if($type == 'pay' && !empty($money)) {
            return $this->makeOrder($request, $money, $res->id);
        }
        return response()->json(['status' => 'success', 'info' => '提交成功']);
    }

    public function makeOrder(Request $request, $money, $form_data_id)
    {
        if(empty($request->input('id')) || empty($we_chat_user = WeChatUser::find($request->input('id')))) {
            return response()->json(['status' => 'fail', 'info' => '找不到用户']);
        }
//        $student = Student::where('open_id', $we_chat_user->open_id);
        $app = app('wechat.payment');

        $out_trade_no = (new Order())->getOutTradeNo();

        $order = Order::create([
            'out_trade_no' => $out_trade_no,
            'pay_position' => $request->input('mode', 1),
            'pay_status' => 1,
            'pay_method' => 1,
            'money' => $money,
            'form_data_id' => $form_data_id
        ]);

        if(empty($order)) {
            return response()->json(['status' => 'fail', 'info' => '订单创建失败']);
        }

        $result = $app->order->unify([
            'body' => '钢琴时间',
            'out_trade_no' => $out_trade_no,
//            'total_fee' => $request->input('money'),
            'notify_url' => url('/wechat/payNotify'),
            'total_fee' => $money,
            'trade_type' => 'JSAPI',
            'openid' => $we_chat_user->open_id,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $prepayId = $result['prepay_id'];
            $config = [
                // 前面的appid什么的也得保留哦
                'app_id'             => $result['appid'],
                'mch_id'             => $result['mch_id'],
                'key'                => env('WECHAT_PAYMENT_KEY', 'key-for-signature'),
                // 'device_info'     => '013467007045764',
                // 'sub_app_id'      => '',
                // 'sub_merchant_id' => '',
                // ...
            ];
            $payment = Factory::payment($config);
            $jssdk = $payment->jssdk;
            $json = $jssdk->bridgeConfig($prepayId);
        } else {
            return response()->json(['status' => 'fail', 'info' => '支付失败']);
        }
        return response()->json(['status' => 'success', 'data' => $json]);
    }

    public function payNotify(Request $request)
    {
        $app = app('wechat.payment');

        $response = $app->handlePaidNotify(function ($message, $fail) {
//            Log::info($message);
            if($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS' ) {
                $order = Order::where('out_trade_no', $message['out_trade_no'])->first();
                if(!empty($order) && $order->money  == $message['total_fee']) {
                    $order->pay_status = 2;
                    $order->save();
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });

        return $response;
    }
}
