<?php

namespace App\Http\Controllers\Admin;

use App\Exports\ActivityApplyExport;
use App\Exports\ActivityExport;
use App\Exports\ActivityMemberExport;
use App\Exports\ActivityMemberLogExport;
use App\Exports\ActivityOrderExport;
use App\Exports\ActivityRefundExport;
use App\Facades\CommonService;
use App\Facades\UploadService;
use App\Facades\WechatService;
use App\Http\Response\ResponseJson;
use App\Http\Controllers\Controller;
use App\Imports\ApplyUserImport;
use App\Jobs\AddErrorLog;
use App\Jobs\SendEasySms;
use App\Jobs\SendTemplateNotice;
use App\Models\Activity;
use App\Models\ActivityIntroduceLog;
use App\Models\ActivityMeeting;
use App\Models\ActivityMeetingApply;
use App\Models\ActivityMember;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderLog;
use App\Models\ActivityShareRefund;
use App\Models\AgentUser;
use App\Models\ImportApplyUser;
use App\Models\Lottery;
use App\Models\Payment;
use App\Models\ShareLog;
use App\Models\User;
use App\Models\Wechat;
use Faker\Provider\UserAgent;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class ActivityController extends Controller
{
    use ResponseJson;

    public function addActivity(Request $request){
        DB::beginTransaction();
        try {
            $data = $request->only(['title','sub_title','pic','share_pic','start_time','end_time','apply_end_time','status','is_free','is_online','sku','longitude','latitude','address','describe','price', 'payment_id','is_open_policy','policy','policy_title','describe','is_provide_food','is_need_hand']);

            $validated = Validator::make($data, [
                'title' => 'required',
                'start_time' => 'required',
                'end_time' => 'required',
                'pic' => 'required',
                'is_provide_food' => 'required',
                'is_need_hand' => 'required',
            ], [
                'title.required' => '请填写标题',
                'start_time.required' => '请选择开始时间',
                'end_time.required' => '请选择结束时间',
                'pic.required' => '请上传活动图片',
                'is_provide_food.required' => '请选择是否提供餐饮',
                'is_need_hand.required' => '请选择是否需要手动报名',
            ]);

            if ($validated->fails()) {
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                return $this->failure($error);
            }

            $model = Activity::create($data);

            $url = config('app.url')."/h5/#/activityDetail?id=".$model->id;
            $qrcode = CommonService::makeqrcode($url);
            Activity::where('id',$model->id)->update(['qr_code_url'=>$url,'qr_code'=>$qrcode]);
            //绑定抽奖活动
            $this->addActivityLottery($model);
            //创建用户签到池
            $this->addMembers($model);
            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            AddErrorLog::dispatch('addActivity file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function addMembers($activity)
    {
        //过去订单是否含余额
        $user_ids1 = ActivityOrder::paid()->residue()->distinct('user_id')->pluck('user_id')->toArray();
        //当前活动时候报名
        $user_ids2 = ActivityOrder::paid()->activity($activity->id)->distinct('user_id')->pluck('user_id')->toArray();
        $user_ids = array_merge($user_ids1, $user_ids2);
        $items = [];
        foreach ($user_ids as $user_id) {
            $items[] = ['activity_id'=>$activity->id,'user_id'=>$user_id, 'status'=>0];
        }
        ActivityMember::upsert($items, ['activity_id','user_id'], ['activity_id','user_id']);
    }

    public function addActivityLottery($activity)
    {
        //创建抽奖活动
        $lottery = Lottery::create(['title'=>$activity->title, 'repeat'=>0]);
        //绑定活动和抽奖
        $lottery->addLotteryable($activity);
        //新版抽奖信息
        $lottery->path = config('app.url').'/award/#/luckyDraw?id='.$lottery->id;
        $lottery->new_path = config('app.url').'/award/#/newLuckyDraw?id='.$lottery->id;
        //生成二维码
        $lottery->qrcode = CommonService::makeQrcode($lottery->path);
        $lottery->new_qrcode = CommonService::makeQrcode($lottery->new_path);
        //报名链接
        $apply_path = config('app.url').'/h5/#/luckyDrawData?id='.$lottery->id;
        $lottery->apply_qrcode = CommonService::makeQrcode($apply_path);;
        $lottery->update(['path'=>$lottery->path, 'qrcode'=>$lottery->qrcode, 'apply_qrcode'=>$lottery->apply_qrcode]);
        return $lottery;
    }


    public function getActivity(Request $request){
        try {
            $keyword = $request->get('keyword');
            $is_export = $request->get('is_export');

            $query = Activity::query();

            $query->when($keyword,function ($query) use ($keyword){
                $query->where('title','like','%'.$keyword.'%');
            });

            $query->orderByDesc('status')->orderByDesc('id');
            if($is_export){
                $list = $query->get();
                return Excel::download(new ActivityExport($list), 'activity.xlsx');
            }
            $nopage = $request->input('nopage');
            if ($nopage) {
                $list = $query->get();
                return $this->success('ok',$list);
            }
            $list = $query->paginate();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getActivity file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function deleteActivity($id){
        try {
            Activity::where('id',$id)->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('deleteActivity file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function members(Request $request, Activity $activity)
    {
        $members = $activity->members()->where(function($sql) use($activity){
            $sql->whereHas("orders", function($sql) use($activity) {
                $sql->where('activity_id', $activity->id)->where("is_pay",1);
            })->orWhereHas("agentUser", function($sql) {
                $sql->where("level", AgentUser::AgentLevelBeing)->orWhere("level", AgentUser::AgentVIP);
            });
        })->keyword()->with("user:id,name,mobile,avatar", "user.officialWechat")->orderByDesc("updated_at");
        $export = $request->input('export');
        if ($export) {
            $members = $members->get();
            foreach ($members as $member) {
                $member->level = $member->agentUser?$member->agentUser->level:0;
            }
            return Excel::download(new ActivityMemberExport($members), 'members.xlsx');
        }
        $members = $members->paginate();
        foreach ($members as $member) {
            $member->level = $member->agentUser?$member->agentUser->level:0;
        }
        return $this->success('ok', $members);
    }

    public function membersLogs(Request $request, Activity $activity)
    {
        $members = $activity->membersLogs()->keyword()->with("user:id,name,mobile,avatar", "user.officialWechat")->orderByDesc("updated_at");
        $export = $request->input('export');
        if ($export) {
            $members = $members->get();
            foreach ($members as $member) {
                $member->level = $member->agentUser?$member->agentUser->level:0;
            }
            return Excel::download(new ActivityMemberLogExport($members), 'members.xlsx');
        }
        $members = $members->paginate();
        foreach ($members as $member) {
            $member->level = $member->agentUser?$member->agentUser->level:0;
        }
        return $this->success('ok', $members);
    }


    public function getActivityDetail($id){
        try {
            $detail = Activity::find($id);

            if (!$detail->sign_qrcode1) {
                $sign_url = config("app.url")."/api/temp/oa/code/v2?id={$id}";
                $data['sign_qrcode1'] = CommonService::makeqrcode($sign_url);
                $sign_url = config("app.url")."/go_html/store_agent#/activitiesNewSignV2?id={$id}";
                $data['sign_qrcode2'] = CommonService::makeqrcode($sign_url);
                $sign_url = config("app.url")."/go_html/store_agent#/activitiesNewSign?id={$id}";
                $data['sign_qrcode3'] = CommonService::makeqrcode($sign_url);
                $detail->update($data);
            }
            return $this->success('ok',$detail);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getActivityDetail file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function updateActivity(Request $request,$id){
        try {
            $data = $request->only(['title','sub_title','pic','share_pic','start_time','end_time','apply_end_time','status','is_free','is_online','sku','longitude','latitude','address','describe','price','payment_id','is_open_policy','policy','policy_title','is_provide_food','is_need_hand']);
            $activity = Activity::find($id);
            $activity->update($data);
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('updateActivity file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function getActivityOrder(Request $request){
            $keyword = $request->get('keyword');
            $is_export = $request->get('is_export');
            $activity = $request->get('activity_id');
            $title = $request->get('title');
            $user_id = $request->get('user_id');
            $introduce_user_id = $request->get('introduce_user_id');
            $query = ActivityOrder::query()->with(['activity','user','introduceUser', 'recommendUser','unusualOrder']);

            $status = $request->input('status');
            $query->when($status, function ($query) use($status) {
                if ($status == ActivityOrder::PAID_STATUS) {
                    $query->paid();
                }elseif ($status == ActivityOrder::UNPAID_STATUS) {
                    $query->unpaid();
                }elseif ($status == ActivityOrder::ADMIN_REFUND_STATUS) {
                    $query->whereHas("refunds", function ($sql) {
                        $sql->where("status", ActivityShareRefund::AGREESTATUS)->where('type', ActivityShareRefund::ADMINTYPE);
                    });
                }elseif ($status == ActivityOrder::SHARE_REFUND_STATUS) {
                    $query->whereHas("refunds", function ($sql) {
                        $sql->where("status", ActivityShareRefund::AGREESTATUS)->where('type', ActivityShareRefund::SHARETYPE);
                    });
                }elseif ($status == ActivityOrder::UNUSUAL_STATUS) {
                    $query->unusual();
                }else {
                    $query->where("is_pay","<>", 0);
                }
            });

            $query->when($activity,function ($query) use ($activity){
               $query->where('activity_id',$activity);
            });

            $query->when($keyword, function ($query) use ($keyword, $activity) {
                $query->where(function ($query) use ($activity) {
                    if ($activity) {
                        $query->where('activity_id', $activity);
                    }
                })
                    ->where(function ($query) use ($keyword) {
                        $query->where('trade_no', 'like', '%' . $keyword . '%')
                            ->orWhere('name', 'like', '%' . $keyword . '%')
                            ->orWhere('mobile', 'like', '%' . $keyword . '%')
                            ->orWhereHas("introduceUser", function ($sql) use ($keyword) {
                                $sql->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
                            });
                    });
            });

            $query->whereHas("activity", function ($sql) use ($title) {
                $sql->where('title', 'like', '%' . $title . '%');
            });


            $query->when($user_id, function ($query) use ($user_id){
                $query->owner($user_id);
            });

            $query->when($introduce_user_id, function ($query) use ($introduce_user_id){
                $query->introduce($introduce_user_id);
            });

            $query->orderByDesc('id');

//            $sql = $query->toSql();
//            dd($sql);
            if($is_export){
                $list = $query->get();
            }else{
                $list = $query->paginate();
            }

            foreach ($list as $item){
                $sign = ActivityMeetingApply::where('activity_id',$activity)->where('user_id',$item->user_id)->first();
                $item->is_sign = false;
                $item->sign_time = '';
                if(!empty($sign)){
                    $item->is_sign = true;
                    $item->sign_time = $sign->created_at->toDateTimeString();
                    $item->desk_number = $sign->desk_number;
                    $item->apply_id = $sign->id;
                }
                $item->agent_level = 0;
                $agent_level = AgentUser::where('user_id',$item->user_id)->value('level');
                if($agent_level > 0){
                    $item->agent_level = $agent_level;
                }
            }

            if($is_export){
                return Excel::download(new ActivityOrderExport($list), 'activity_order.xlsx');
            }
            return $this->success('ok',$list);

    }

    public function storeActivityOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $user = User::find($user_id);
        if (empty($user)) return $this->failure("用户不存在");
        $data = $request->all();
        $activity = Activity::find($data['activity_id']);
        $sku = collect($activity->sku)->firstWhere('sku_id', $data['sku_id']);
        $data['sku'] = $sku['name'];
        $price = $sku['price'];
        $data['num'] = 1;
        $data['is_pay'] = 1;
        $data['amount'] = $data['residue_amount'] = $price;
        $data['trade_no'] = CommonService::getTradeNo();
        $order = ActivityOrder::create($data);
        $order->markActivityOrder($order);
        return $this->success('ok', $order);
    }


    public function order(Request $request, ActivityOrder $order)
    {
        $order->activity;
        $order->introduceUser;
        return $this->success('ok', $order);
    }

    public function addActivityMeeting(Request $request,$activity_id){
        try {
            $activity = Activity::where('id',$activity_id)->first();
            if(empty($activity)){
                return $this->failure('活动不存在');
            }
            $data = $request->only(['total_desk','menu','back_images','desk_images','start_desk','user_number','sign_images','desk_back_images']);
            $validator = Validator::make($request->all(), [
                'total_desk' => 'required',
                'back_images' => 'required',
                'desk_images' => 'required',
                'start_desk' => 'required',
                'user_number' => 'required',
                'sign_images' => 'required',
            ], [
                'total_desk.required' => '请填写总桌数',
                'back_images.required' => '请上传背景图',
                'desk_images.required' => '请上传座位图',
                'start_desk.required' => '请填写开始桌号',
                'user_number.required' => '请填写每桌人数',
                'sign_images.required' => '请上传签到背景图'
            ]);

            $error = $validator->errors()->first();
            if ($error) {
                return $this->failure($error);
            }
            $menus = $data['menu'];

            $meeting = ActivityMeeting::where('activity_id',$activity_id)->first();

            array_push($menus,['name'=>"座位查询",'images'=>$data['desk_back_images']]);

            unset($data['desk_back_images']);

            if(empty($meeting)){
                $data['activity_id'] = $activity_id;
            }
            $data['menu'] = json_encode($menus);

            if($meeting){
                ActivityMeeting::where('activity_id',$activity_id)->update($data);
            }else{
                $url = config('app.url')."/h5/#/activitiesSignDetail?id=".$activity_id.'&type='.urlencode("入场签到");
//                $url = config('app.url')."/api/h5/wechat/user/auth?target_path=activitiesSign?id=".$activity_id;
//                $qrcode = get_qrcode("activity_meeting_",$url,$activity_id);
                $qrcode = CommonService::makeqrcode($url);
                $data['qr_code'] = $qrcode;
                $data['qr_code_url'] = $url;
                ActivityMeeting::create($data);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('addActivityMenu file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }


    public function getActivityMeeting(Request $request,$activity_id){
        try {
            $meeting = ActivityMeeting::where('activity_id',$activity_id)->first();
            if($meeting){
                $temp_menu = json_decode($meeting->menu,true);
                foreach ($temp_menu as $index => $menu){
                    if($menu['name'] == "座位查询"){
                        $meeting->desk_back_images = $menu['images'];
                        unset($temp_menu[$index]);
                    }
                }
                sort($temp_menu);
                $meeting->menu = $temp_menu;
            }
            return $this->success('ok',$meeting);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getActivityMenu file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function getMeetingApply(Request $request){
        try {
            $activity_id = $request->get('id');
            $keyword = $request->get('keyword');
            $is_export = $request->get('is_export');
            $no_page = $request->get('no_page');
            if($is_export){
                $no_page = true;
            }

            $is_all = $request->get('is_all');
            if(in_array($activity_id,[13,17]) && $is_all){
                $query = ImportApplyUser::query();
                $query->when($keyword, function ($query) use ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
                });
                $query->where('activity_id',$activity_id);
            }else{
                $query = ActivityMeetingApply::query();
                $query->when($keyword, function ($query) use ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
                });
                $query->where('activity_id',$activity_id);
                $query->orderBy('desk_number',"asc");
            }
            if($no_page){
                $apply_user = $query->get();
            }else{
                $apply_user = $query->paginate();
            }

            if(in_array($activity_id,[13,17]) && $is_all){
                foreach ($apply_user as $item){
                    $item->desk_number = ActivityMeetingApply::where('mobile',$item->mobile)->where('activity_id',$item->activity_id)->value('desk_number');
                }
            }

            foreach ($apply_user as $item){
                $item->status = ActivityMeetingApply::STATUS_NORMAL;
                $amount = ActivityOrder::where('user_id',$item->user_id)->sum("residue_amount");
                if($amount > 0){
                    continue;
                }
                $order_ids = ActivityOrder::where('introduce_user_id',$item->user_id)
                    ->where('activity_id',$activity_id)
                    ->where("residue_amount",0)
                    ->pluck("id");
                $count = count($order_ids);
                if($count <= 0){
                    continue;
                }
                $refund_orders = ActivityShareRefund::whereIn("order_id",$order_ids)->where('status',1)->pluck("id");
                if(!(count($order_ids) == count($refund_orders))){
                    continue;
                }
                $item->status = ActivityMeetingApply::STATUS_ABNORMAL;
            }
            if($is_export){
                return Excel::download(new ActivityApplyExport($apply_user), 'activity_apply.xlsx');
            }
            return $this->success('ok',$apply_user);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getMeetingApply file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function getActivityOrderUse($id){
        try {
            $list = ActivityIntroduceLog::with('activityOrder.activity')->introduceOrder($id)->orderByDesc('id')->get();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getOrderUse file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function importMember(Request $request, $activity_id)
    {
//        $path = $request->input('path');
        $file =$request->file('file');
        Excel::import(new ApplyUserImport($activity_id), $file);
        return $this->success('ok');
    }

    public function updateUserDesk(Request $request,$id){
        try {
            $desk_number = $request->input('desk_number');
            $activity_id = $request->input('activity_id');
            $is_all = $request->input('is_all');
            $count = ActivityMeetingApply::where('activity_id',$activity_id)->where('desk_number',$desk_number)->count();
            $activity = ActivityMeeting::where('activity_id',$activity_id)->first();
            if($desk_number > $activity->total_desk){
                return $this->failure('超过当次活动总桌号');
            }
            if($count >= $activity->user_number){
                return $this->failure('座位人已满');
            }
            if(in_array($activity_id,[13,17]) && $is_all){
                $import_user = ImportApplyUser::where('id',$id)->find($id);
                $detail = ActivityMeetingApply::where('activity_id',$import_user->activity_id)->where('mobile',$import_user->mobile)->first();
                if(empty($detail)){
                    ActivityMeetingApply::create(['user_id'=>0,'activity_id'=>$activity_id,'desk_number'=>$desk_number,'name'=>$import_user->name,'mobile'=>$import_user->mobile]);
                }else{
                    $detail->desk_number = $desk_number;
                    $detail->save();
                }
            }else{
                $detail = ActivityMeetingApply::find($id);
                $detail->desk_number = $desk_number;
                $detail->save();
            }
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('updateUserDesk file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    public function payments()
    {
        $payments = Payment::query();
        $nopage = request()->nopage;
        if ($nopage) {
            $payments = $payments->get();
        }else {
            $payments = $payments->paginate();
        }
        return $this->success('ok', $payments);
    }

    public function shareLogs(Request $request, User $user)
    {
        $type = $request->input('type', 'owner');
        if ($type == 'owner') {
            $logs = ShareLog::with('fromUser')->owner($user->id)->orderByDesc('id')->paginate();
        }else {
            $logs = ShareLog::with('user')->fromOwner($user->id)->orderByDesc('id')->paginate();
        }
        return $this->success('ok', $logs);
    }

    public function refundOrders(Request $request)
    {
        $logs = ActivityShareRefund::with('user:id,name,mobile,avatar', 'order.activity', 'targetOrder')
            ->keyword()
            ->status()->orderByDesc('id');
        $export = $request->input('export');
        if ($export) {
            $logs = $logs->get();
            return Excel::download(new ActivityRefundExport($logs), '渠道商.xlsx');
        }
        $logs = $logs->paginate();
        return $this->success('ok', $logs);
    }

    public function auditRefundOrders(Request $request, ActivityShareRefund $order)
    {
        DB::beginTransaction();
        if ($order->is_hook) return $this->success("ok");
        if ($order->status != 0) return $this->failure("退款订单已审核");
        $data = $request->all();
        if ($data['status'] == 1) {
            $callback = config('app.url')."/api/h5/activity/refund/order/{$order->refund_trade_no}/callback";
            $result = WechatService::refund($order->trade_no, $order->refund_trade_no, $order->total_amount, $order->amount, $callback,$order->sub_mch_id);
            if (!$result['status']) return $this->failure($result['msg']);
            if ($result["status"]) {
                $this->markRefundOrder($order);
            }
        }elseif ($data['status'] == -1) {
            $activity_order = ActivityOrder::find($order->order_id);
            ActivityIntroduceLog::where(['order_id'=>$activity_order->id, 'amount'=>$order->amount, 'type'=>ActivityIntroduceLog::REFUNDTYPE])->delete();
            $activity_order->increment('residue_amount', $order->amount);
            $admin = auth('admin')->user();
            ActivityOrderLog::addActivityOrderLog($order->user_id,$order->order_id,$order->amount,"退款申请驳回", $admin->id, $admin->name, ActivityOrderLog::NOREFUND_TYPE);
        }
        $order->update($data);
        DB::commit();
        if($data['status'] == 1){
            $this->sendCheckSuccessMsg($order);
        }
        return $this->success('ok');
    }

    public function markRefundOrder($order)
    {
        //直接退款 取消用户批发商资格
        $remark = "介绍人退款";
        if ($order->type == ActivityShareRefund::ADMINTYPE) {
            $remark = "直接退款";
            //增加身份修改记录
            $desc = "活动订单直接退款";
            AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelNot, $desc);
            //订单修改为已退款
            $activity_order = $order->order;
            if ($activity_order && $activity_order->residue_amount == 0) {
                ActivityOrder::where('id',$order->order_id)->update(['is_pay'=>2]);
            }
        }
        //修改订单异常状态
        ActivityOrder::where('id',$order->order_id)->update(['introduce_unusual'=>0]);
    }

    public function sendCheckSuccessMsg($order){
        $activityOrder = ActivityOrder::where('id',$order->order_id)->first();
        $message = "您的回款申请已通过,已原路返回您的支付账户。祝您身心健康,友福同享!【友福同享】";
        //发送短信通知
        $data = [
            'message'=>$message,
        ];
        SendEasySms::dispatch($activityOrder->mobile, $data)->onQueue('health');

        $activity_title = Activity::where('id',$activityOrder->activity_id)->value('title');

        $open_id = Wechat::where('user_id',$activityOrder->user_id)->where('type',Wechat::TYPE_OFFICIAL)->value('openid');
        $params = [
            'touser'=> $open_id,
            'template_id'=>config('wechat.tpls.check_refund'),
            'data'=>[
                'phrase3' => ['value'=>"已审核"],
                'time4' => ['value'=>date("Y-m-d H:i:s")],
                'thing12' => ['value'=>$activityOrder->name],
                'thing9' => ['value'=>$activity_title],
                'amount8' => ['value'=>$order->amount],
            ]
        ];
        Log::info('auditRefundOrders:'.json_encode($params));
        SendTemplateNotice::dispatch($params)->onQueue('health');
    }

    public function callbackRefundOrder(Request $request, $refund_trade_no)
    {
        $refund_order = ActivityShareRefund::where('refund_trade_no', $refund_trade_no)->first();
        if ($refund_order->is_hook) return;
        $res = WechatService::orderRefunded($refund_trade_no, $refund_order->sub_mch_id);
        if ($res['status']) {
            $refund_order->update(['is_hook'=>1]);
        }
        return ;
    }

    public function applyRefund(Request $request, ActivityOrder $order)
    {
        DB::beginTransaction();
        if (!$order->is_pay) return $this->failure("订单未支付");
        $amount = $request->input('amount');
        //剩余金额是否充足
        $remain_amount = $order->residue_amount;
        if ($amount > $remain_amount) return $this->failure("剩余可退款金额不足");
        $type = $request->input('type', ActivityShareRefund::ADMINTYPE);
        if (empty($type)) return $this->failure("请选择退款类型");
        $target_order_id = $order->id;
        if ($type == ActivityShareRefund::SHARETYPE) {
            $target_order_id = $request->input('target_order_id');
            if (empty($target_order_id)) return $this->failure("请选择分享来源订单");
        }
        $status = ActivityShareRefund::AUDITSTATUS;
        $check = $request->input('check',ActivityShareRefund::CHECK_TRUE);

        if($check == ActivityShareRefund::CHECK_FALSE){
            $status = ActivityShareRefund::AGREESTATUS;
        }
        ActivityIntroduceLog::create(['order_id'=>$order->id, 'amount'=>$amount, 'introduce_order_id'=>$order->id, 'type'=>ActivityIntroduceLog::REFUNDTYPE]);
        $admin = auth('admin')->user();
        $log = ActivityOrderLog::addActivityOrderLog($order->user_id,$order->id,-$amount, "申请退款", $admin->id, $admin->name, ActivityOrderLog::REFUND_TYPE);
        $order->decrement('residue_amount', $amount);
        $refund_order = ActivityShareRefund::create([
            'user_id'=>$order->user_id,
            'order_id'=>$order->id,
            'target_order_id'=>$target_order_id,
            'trade_no'=>$order->trade_no,
            'refund_trade_no'=>CommonService::getTradeNO(),
            'total_amount'=>$order->amount,
            'amount'=>$amount,
            'status'=>$status,
            'sub_mch_id'=>$order->sub_mch_id,
            'type'=>$type,
            'admin_id'=>auth()->id(),
            'check' => $check,
            'log_id'=>$log->id,
        ]);
        if ($status == ActivityShareRefund::AGREESTATUS && $check == ActivityShareRefund::CHECK_FALSE) {
            $this->markRefundOrder($refund_order);
        }
        DB::commit();
        return $this->success('ok');
    }

    public function refunds(Request $request, ActivityOrder $order)
    {
        $refunds = ActivityShareRefund::with('admin', 'order', 'targetOrder')->where("order_id", $order->id)->orderByDesc("id")->paginate();
        return $this->success('ok', $refunds);
    }

    public function operateAmount(Request $request){
        $real_amount = $amount = $request->input('amount');
        $type = $request->input('type');
        $remark = $request->input('remark');
        if($type == 1){
            $real_amount = -$amount;
        }
        $user_id = $request->input('user_id');
        $order_id = $request->input('order_id');
        $order = ActivityOrder::find($order_id);
        if($user_id != $order->user_id){
            return $this->failure('批发商和订单用户不对应');
        }
        if($order->residue_amount < $amount){
            return $this->failure('余额不足');
        }
//        if($type == 1){
//            $order->decrement('residue_amount', $amount);
//        }else {
//            $order->increment('residue_amount', $amount);
//        }
        //插入余额记录
//        $admin = auth()->user();
//        ActivityOrderLog::addActivityOrderLog($order->user_id,$order_id,$real_amount,$remark,$admin->id,$admin->name);
        return $this->success('ok');
    }

    public function getAmountLog($id){
        $list = ActivityOrderLog::with('activityOrder')->where('user_id',$id)->orderByDesc('id')->paginate();
        return $this->success('ok',$list);
    }
}
