<?php

namespace App\Http\Controllers\H5;

use App\Exports\AgentStocksExport;
use App\Facades\CommonService;
use App\Facades\HttpService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Jobs\AddShareLog;
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\ActivityOrder;
use App\Models\ActivityOrderLog;
use App\Models\ActivityShareRefund;
use App\Models\AgentUser;
use App\Models\Band;
use App\Models\ImportApplyUser;
use App\Models\Message;
use App\Models\PartnerCommission;
use App\Models\RecommendUser;
use App\Models\RegularActivity;
use App\Models\RegularActivityOrder;
use App\Models\S2ShopOrder;
use App\Models\User;
use App\Models\UrlLink;
use App\Models\UserIntroduceLog;
use App\Models\Wechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ActivityController extends Controller
{
    use ResponseJson;

    public function activityOrders(Request $request, $activity_id)
    {
        $params = $request->all();
        $param = http_build_query($params);
        $url = config('app.shop_url') . "activities/{$activity_id}/orders?$param";
        $res = HttpService::getData($url);
        if ($res['code'] == 1)
            return $this->failure($res['message']);
        $data = $res['data'];
        if (isset($params['export']) && $params['export']) {

            return Excel::download(new AgentStocksExport($data), '提取记录.xlsx');
        }
        return $this->success('ok', $data);
    }

    public function activities()
    {
        $list = Activity::valid()->select('id', 'price', 'pic', 'title')->orderByDesc("id")->paginate();
        return $this->success('ok', $list);
    }

    public function activitiesV2()
    {
        $activities = [];
        $list1 = Activity::valid()->select('id', 'price', 'pic', 'title', 'start_time', 'end_time')->orderBy("start_time")->limit(2)->get();
        foreach ($list1 as $activity) {
            $activity_array = $activity->toArray();
            $activity_array['type'] = "activity";
            $activities[] = $activity_array;
        }
        //        $list2 = RegularActivity::valid()->select("id", 'title', 'pic', 'start_time', 'end_time')->orderBy("start_time")->limit(2)->get();
//        foreach ($list2 as $activity) {
//            $activity_array = $activity->toArray();
//            $activity_array['type'] = "regular";
//            $activity_array['price'] = 0;
////            $activity_array['pic'] = RegularActivity::DEFAULT_PIC;
//            $activities[] = $activity_array;
//        }
        return $this->success('ok', $activities);
    }

    public function regularActivity(RegularActivity $activity)
    {
        $user = auth()->user();
        //是否已报名
        $activity->is_paid = RegularActivityOrder::where(["user_id" => $user->id, 'activity_id' => $activity->id])->exists() ? 1 : 0;
        //大会id
        $activity_id = Activity::valid()->orderBy("start_time", 'desc')->value("id");
        $activity->activity_id = $activity_id;
        //        $activity->pic = RegularActivity::DEFAULT_PIC;
        $activity->background = $activity->background ?: "https://images.health.ufutx.com/202403/29/0af4b5799b15e24d6442d4148f694f80.jpeg";
        //分享二维码
        $qrcode = $activity->activityQrcodes()->where('user_id', $user->id)->where('type', 'H5')->value('qrcode');
        if (!$qrcode) {
            $url = config("app.url") . "/h5/#/smallConferenceApply?id={$activity->id}&from_user_id={$user->id}&from_type=activity";
            $qrcode = CommonService::makeQrcode($url);
            $activity->activityQrcodes()->create(['user_id' => $user->id, 'type' => "H5", 'qrcode' => $qrcode]);
        }
        $activity->share_qrcode = $qrcode;
        return $this->success('ok', $activity);
    }

    public function applyRegularActivity(Request $request, RegularActivity $activity)
    {
        //报名状态
        $status = 1;
        $user = auth()->user();
        //是否批发商
        if (!$user->agentUser || $user->agentUser->level == 0) {
            $status = 0;
        }
        if ($status) {
            //生成订单
            RegularActivityOrder::firstOrCreate(["user_id" => $user->id, 'activity_id' => $activity->id, 'name' => $request->name, 'mobile' => $request->mobile, 'is_apply_food' => $request->is_apply_food]);
            //todo 接龙通知
        }
        return $this->success('ok', compact('status'));
    }

    public function activity(Activity $activity)
    {
        $user = auth()->user();
        //是否已下单
        $activity->is_paid = ActivityOrder::owner($user->id)->activity($activity->id)->paid()->exists() ? 1 : 0;
        //分享二维码
        $qrcode = $user->activityQrcodes()->where('activity_id', $activity->id)->where('type', 'H5')->value('qrcode');
        if (!$qrcode) {
            $url = config("app.url") . "/h5/#/activityDetail?id={$activity->id}&from_user_id={$user->id}&from_type=activity";
            $qrcode = CommonService::makeQrcode($url);
            $user->activityQrcodes()->create(['activity_id' => $activity->id, 'type' => "H5", 'qrcode' => $qrcode]);
        }
        $activity->share_qrcode = $qrcode;


        return $this->success('ok', $activity);
    }

    // 活动报名条件限制
    public function checkPayActivityCondition($activity): bool
    {
        if ($activity->id == 30) {
            $user = auth()->user();
            //八月份活动报名人员 VIP、批发商、手环订单（不包括租赁）、有正在绑定手环
            $agent_user = $user->agentUser;
            // 批发商或VIP
            $res = ($agent_user && ($agent_user->level == AgentUser::AgentLevelBeing || $agent_user->level == AgentUser::AgentVIP));
            if ($res)
                return true;
            // 正在绑定的手环
            $res = Band::owner($user->id)->status(Band::SHOW_STATUS)->exists();
            if ($res)
                return true;
            // 含手环订单
            $res = S2ShopOrder::whereIn("shop_type", [11, 12])->where("user_id", $user->id)->where("sku_id", 86)->where("status", "!=", 1)->whereHas("lottoCode")->exists();
            if ($res)
                return true;
            // 不满足上面条件
            return false;
        }

        return true;
    }

    public function payActivity(Request $request, Activity $activity)
    {
        $user = auth()->user();
        //是否截止报名
        if ($activity->apply_end_time && date("Y-m-d H:i:s") > $activity->apply_end_time)
            return $this->failure("活动已停止报名");
        //        $is_paid = ActivityOrder::owner($user->id)->activity($activity->id)->paid()->exists();
//        if ($is_paid) return $this->failure("活动已报名");
        // 特定活动条件限制
        $res = $this->checkPayActivityCondition($activity);
        if (!$res)
            return $this->failure("没有权限报名此次活动");
        $data = $request->only(['name', 'mobile', 'sex', 'sku_id', 'from_user_id', 'area_code', 'is_apply_food']);
        if ($activity->is_free) {
            if (empty($data['sku_id']))
                throw new \Exception("缺少活动规格id");
            $sku = collect($activity->sku)->firstWhere('sku_id', $data['sku_id']);
            if (empty($sku))
                throw new \Exception("未查询到相应规格");
            $sku_name = $sku['name'];
            $price = $sku['price'];
        } else {
            $sku_name = '';
            $price = 0;
        }

        $data['activity_id'] = $activity->id;
        $data['user_id'] = $user->id;
        $data['trade_no'] = "activity_" . CommonService::getTradeNO();
        $data['is_pay'] = 0;
        $data['sku'] = $sku_name;
        $data['num'] = 1;
        $data['amount'] = $data['residue_amount'] = $price;
        $data['introduce_user_id'] = $data['from_user_id'] ?? null;
        $sub_mchid = $activity->payment ? $activity->payment->sub_mch_id : '1626601973';
        $data['sub_mch_id'] = $sub_mchid;
        //下单
        $order = ActivityOrder::create($data);
        $config = [];
        if ($data['amount']) {
            //微信支付
            $openid = $user->officialWechat->openid;
            $desc = $activity->title . "-" . $sku_name;
            $callback = config("app.url") . "/api/h5/activity/order/{$data['trade_no']}/callback";
            $appId = config('wechat.official_account.default.app_id') ?: 'wx5174eb5ba45228a4';
            $config = WechatService::mpPay($data['trade_no'], $openid, $data['amount'], $desc, $callback, $appId, $sub_mchid);
        } else {
            //回调
            $this->markActivityOrder($order);
        }
        return $this->success('ok', compact('order', 'config'));
    }

    /**
     * 订单回调
     * @param $trade_no
     */
    public function callbackOrder($trade_no)
    {
        $order = ActivityOrder::where('trade_no', $trade_no)->first();
        if ($order->is_pay)
            return true;
        //是否支付成功
        $sub_mch_id = $order->sub_mch_id;
        $res = WechatService::mpPaid($trade_no, $sub_mch_id);
        if ($res)
            return false;
        $this->markActivityOrder($order);
        $this->sendSuccessMsg($order);
        return true;
    }

    public function sendActivityMsg(Request $request)
    {
        $data = $request->all();
        if (!empty($data['open_id'])) {
            $params = [
                'touser' => $data['open_id'],
                'template_id' => config('wechat.tpls.buy_good_success'),
                'data' => [
                    'thing1' => ['value' => $data['title'] ?? ''],
                    'character_string10' => ['value' => 1],
                    'amount14' => ['value' => $data['amount']],
                    'character_string5' => ['value' => $data['trade_no']],
                    'time4' => ['value' => $data['created_at']],
                ]
            ];
            Log::info("sendSuccessMsg1 open_id:{$data['open_id']} params:" . json_encode($params));
            SendTemplateNotice::dispatch($params)->onQueue('health');
        }

        if (!empty($data['introduce_open_id'])) {
            $params = [
                'touser' => $data['introduce_open_id'],
                'template_id' => config('wechat.tpls.success_to_introduce'),
                'data' => [
                    'thing27' => ['value' => $data['title']],
                    'thing7' => ['value' => $data['name']],
                    'phone_number8' => ['value' => $data['mobile']],
                    'amount24' => ['value' => $data['amount']]
                ]
            ];
            SendTemplateNotice::dispatch($params)->onQueue('health');

            $params = [
                'touser' => $data['introduce_open_id'],
                'template_id' => config('wechat.tpls.introduce_refund_msg'),
                'data' => [
                    'thing2' => ['value' => $data['title']],
                    'thing7' => ['value' => $data['introduce_user_name']],
                    'const5' => ['value' => "推荐用户下单成功，已为您自动申请退款！"],
                    'amount1' => ['value' => $data['amount']],
                    'const12' => ['value' => "审核中"],
                ]
            ];
            // SendTemplateNotice::dispatch($params)->onQueue('health');

            if (!empty($data['introduce_user_mobile'])) {
                $introduce_message = "您推荐的用户已报名成功，已为您自动申请回款，待管理员审核通过后将原路返回至您的支付账户。祝您身心健康，友福同享！【友福同享】";
                //发送短信通知
                $introduce_data = [
                    'message' => $introduce_message,
                ];
                // SendEasySms::dispatch($data['introduce_user_mobile'], $introduce_data)->onQueue('health');
            }
        }
        $message = "恭喜{$data['name']}获得[友福同享]公司全球准批发商资格！请关注友福同享公众号，即时接收分享订单信息!祝您身心健康，友福同享!【友福同享】";
        //发送短信通知
        $messageData = [
            'message' => $message,
        ];
        SendEasySms::dispatch($data['mobile'], $messageData)->onQueue('health');

        //发送企业微信群通知
        $orders = ActivityOrder::paid()->where('activity_id', $data['activity_id'])->orderByDesc('id')->limit(3)->get();
        if (!$orders->isEmpty()) {
            $count = ActivityOrder::paid()->where('activity_id', $data['activity_id'])->count();
            //正式群
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
            //测试群
            if (!(config('app.env') == 'production') || strpos($data['title'], "测试") !== false) {
                $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
            }

            $header = $data['title'] . "\r\n";
            $line = "-----------------------\r\n";
            $omit = "...\r\n";
            $index = 0;
            foreach ($orders as $item) {
                $introduce_user_name = User::where('id', $item->introduce_user_id)->value('name');
                if (empty($introduce_user_name)) {
                    $introduce_user_name = "无";
                }
                $num = $count - $index;
                $name_arr[] = "{$num}:{$item->name}  {$item->sku} 介绍人 {$introduce_user_name}\r\n";
                $index++;
            }
            $name_arr = array_reverse($name_arr);
            $name_str = implode('', $name_arr);

            $qr_code = CommonService::makeqrcode(config('app.url') . "/h5/#/activityDetail?id={$data['activity_id']}");
            $img = "[扫码报名]({$qr_code})\r\n";
            $page_url = "[查看订单列表](" . config('app.url') . "/work/#/h5/activityOrderV2?id={$data['activity_id']})\r\n";
            $send_data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $header . $line . $omit . $omit . $omit . $name_str . $line . $img . $page_url,
                ]
            ];
            Http::post($url, $send_data);
        }
        return $this->success('ok');
    }

    public function sendSuccessMsg($order)
    {
        //发送公众号消息通知
        $activity = Activity::where('id', $order->activity_id)->first();
        $open_id = Wechat::where('user_id', $order->user_id)->where('type', 'official')->value('openid');
        Log::info("sendSuccessMsg open_id:{$open_id}");
        if (!empty($open_id)) {
            $params = [
                'touser' => $open_id,
                'template_id' => config('wechat.tpls.buy_good_success'),
                'data' => [
                    'thing1' => ['value' => $activity->title],
                    'character_string10' => ['value' => $order->num],
                    'amount14' => ['value' => $order->amount],
                    'character_string5' => ['value' => $order->trade_no],
                    'time4' => ['value' => $order->created_at->toDatetimeString()],
                ]
            ];
            Log::info("sendSuccessMsg1 open_id:{$open_id} params:" . json_encode($params));
            SendTemplateNotice::dispatch($params)->onQueue('health');
        }
        //发送消息给推荐人
        $introduce_open_id = Wechat::where('user_id', $order->introduce_user_id)->where('type', 'official')->value('openid');
        if (!empty($introduce_open_id) && $order->introduce_user_id != $order->user_id) {
            $introduce_user_info = User::where('id', $order->introduce_user_id)->first();
            //查看是否购买订单
            $introduce_order = ActivityOrder::where('user_id', $order->introduce_user_id)->sum("residue_amount");

            if ($introduce_order > 0) {
                $params = [
                    'touser' => $introduce_open_id,
                    'template_id' => config('wechat.tpls.success_to_introduce'),
                    'data' => [
                        'thing27' => ['value' => $activity->title],
                        'thing7' => ['value' => $order->name],
                        'phone_number8' => ['value' => $order->mobile],
                        'amount24' => ['value' => $order->amount]
                    ]
                ];
                SendTemplateNotice::dispatch($params)->onQueue('health');

                //                $params = [
//                    'touser'=> $introduce_open_id,
//                    'template_id'=>config('wechat.tpls.introduce_refund_msg'),
//                    'data'=>[
//                        'thing2' => ['value'=>$activity->title??''],
//                        'thing7' => ['value'=>$introduce_user_info->name],
//                        'const5' => ['value'=>"推荐用户下单成功，已为您自动申请退款！"],
//                        'amount1' => ['value'=>$order->amount],
//                        'const12' => ['value'=>"审核中"],
//                    ]
//                ];
//                SendTemplateNotice::dispatch($params)->onQueue('health');
                $params = [
                    'touser' => $introduce_open_id,
                    'template_id' => config('wechat.tpls.introduce_refund_msg_v1'),
                    'data' => [
                        'character_string1' => ['value' => $order->trade_no],
                        'thing6' => ['value' => $activity->title],
                        'thing2' => ['value' => $order->name],
                        'amount8' => ['value' => $order->amount],
                        'thing5' => ['value' => "推荐用户下单成功，已为您自动申请退款！"],
                    ]
                ];
                // SendTemplateNotice::dispatch($params)->onQueue('health');

                if (!empty($introduce_user_info->mobile)) {
                    $introduce_message = "您推荐的用户已报名成功，已为您自动申请退款，待管理员审核通过后将原路返回至您的支付账户。祝您身心健康，友福同享！【友福同享】";
                    //发送短信通知
                    $introduce_data = [
                        'message' => $introduce_message,
                    ];
                    // SendEasySms::dispatch($introduce_user_info->mobile, $introduce_data)->onQueue('health');
                }
            }
        }
        //发送短信通知
        $count = ActivityOrder::paid()->distinct('user_id')->count();
        // pages/sub_page/officialAccounts
//        $wechatLink = WechatService::getMpUrlLink("pages/tabBar/home",null);
//        //获取短链接
//        $shortUrl = CommonService::getShortUrl(env('APP_URL').'/h5/#/jumpUrl?url='.$wechatLink);

        $message = "恭喜{$order->name}获得[友福同享]公司全球准批发商资格！请关注友福同享公众号，即时接收分享订单信息!祝您身心健康，友福同享!【友福同享】";
        //发送短信通知
        $data = [
            'message' => $message,
        ];
        SendEasySms::dispatch($order->mobile, $data)->onQueue('health');

        //发送企业微信群通知
        $orders = ActivityOrder::paid()->where('activity_id', $order->activity_id)->orderByDesc('id')->limit(3)->get();
        if (!$orders->isEmpty()) {
            $count = ActivityOrder::paid()->where('activity_id', $order->activity_id)->count();
            //正式群
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
            //测试群
            if (!(config('app.env') == 'production') || strpos($activity->title, "测试") !== false) {
                $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
            }

            $header = $activity->title . "\r\n";
            $line = "-----------------------\r\n";
            $omit = "...\r\n";
            $index = 0;
            foreach ($orders as $item) {
                $introduce_user_name = User::where('id', $item->introduce_user_id)->value('name');
                if (empty($introduce_user_name)) {
                    $introduce_user_name = "无";
                }
                $num = $count - $index;
                $name_arr[] = "{$num}:{$item->name}  {$item->sku} 介绍人 {$introduce_user_name}\r\n";
                $index++;
            }
            $name_arr = array_reverse($name_arr);
            $name_str = implode('', $name_arr);

            $qr_code = CommonService::makeqrcode(config('app.url') . "/h5/#/activityDetail?id={$order->activity_id}");
            $img = "[扫码报名]({$qr_code})\r\n";
            $page_url = "[查看订单列表](" . config('app.url') . "/work/#/h5/activityOrderV2?id={$order->activity_id})\r\n";
            $send_data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $header . $line . $omit . $omit . $omit . $name_str . $line . $img . $page_url,
                ]
            ];
            Http::post($url, $send_data);
        }
    }
    public function markActivityOrder($order)
    {
        DB::beginTransaction();
        //修改订单状态
        $order->update(['is_pay' => 1]);
        //增加介绍人
        if ($order->introduce_user_id) {
            $this->addRecommendUser($order);
        }
        //用户介绍人
        $introduce_user_id = $order->user->recommendUser ? $order->user->recommendUser->id : null;
        //        //通过介绍人购买，减扣介绍人订单金额
//        if ($order->introduce_user_id && $order->amount && $order->introduce_user_id == $introduce_user_id && $order->introduce_user_id != $order->user_id) {
//            $this->decrementAmount($order->introduce_user_id , $order->amount, $type="INTRODUCE", $order);
//        }
        //通过其他人分享购买，其他人含有余额生成退款记录, 退款金额小于等于当前用户支付金额
//        if ($order->introduce_user_id && $order->amount && $order->introduce_user_id != $order->user_id && $introduce_user_id == $order->introduce_user_id) {
//            $this->refundAmount($order->introduce_user_id, $order->amount, $type="INTRODUCE", $order);
//        }
        //注册准批发商(批发商)
//        $this->registerAgentUser($order);
        AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelBeing, "购买活动门票");

        $activity = $order->activity;
        //插入余额记录
        ActivityOrderLog::addActivityOrderLog($order->user_id, $order->id, $order->amount, "购买活动【{$activity->title}】门票", null, null, ActivityOrderLog::ORDER_TYPE);
        //记录问题介绍人分享  介绍人并且分享的订单并且没有退款绑定订单
        $this->markOrderUnusual($order);
        //加入当前小会抽奖
//        $this->joinRegularActivityLottery($order);
        //加入当前大会抽奖池
        $this->joinActivityLottery($order);
        //加入当前大会签到池
//        $this->joinActivityMember($order);
        DB::commit();
    }

    //加入当前大会签到池
    public function joinActivityMember($order)
    {
        $activity = $order->activity;
        //签到状态  购买时间在活动期间
        $status = 0;
        //        $now = date("Y-m-d H:i:s");
//        if ($activity->start_time <= $now && $activity->end_time >= $now) {
//            $status = 1;
//            //扣除参加费用 200
//            if ($order->amount >= Activity::SIGN_FEE) {
//                $this->decrementOrderAmount($order, Activity::SIGN_FEE, $activity);
//            }
//        }
        $activity->members()->updateOrCreate(['user_id' => $order->user_id, 'activity_id' => $activity->id], ['status' => $status]);
    }

    /**
     * 减扣指定订单的余额
     * @param $order  当前扣费订单
     * @param $amount 扣费金额
     */
    public function decrementOrderAmount($order, float $amount, $activity)
    {
        //判断订单余额是否充足
        if ($order->residue_amount < $amount)
            return false;
        $order->decrement('residue_amount', $amount);
        //插入余额记录
        ActivityOrderLog::addActivityOrderLog($order->user_id, $order->id, number_format($amount * -1, 2, '.', ''), "【{$activity->title}】活动期间下单并签到", null, null, ActivityOrderLog::SIGNIN_TYPE);
        return true;
    }


    //加入当前大会抽奖池
    public function joinActivityLottery($order)
    {
        $activity = $order->activity;
        if ($activity && $activity->lottery) {
            $activity->lottery->members()->updateOrCreate(['user_id' => $order->user_id, 'lottery_id' => $activity->lottery->id], ['name' => $order->user->name, 'mobile' => $order->user->mobile]);
        }
    }

    /**
     * 用户签到了当前 active 或者 ongoing 小会，
     * @param $order
     */
    public function joinRegularActivityLottery($order)
    {
        Log::info("加入小会抽奖名单");
        $activity = RegularActivity::whereIn("status", [RegularActivity::ACTIVE_STATUS, RegularActivity::ONGOING_STATUS])->orderBy("start_time", "ASC")->first();
        if ($activity) {
            Log::info("小会信息  id：{$activity->id}  title:{$activity->title}");
            $member = $activity->members()->where("user_id", $order->user_id)->first();
            if ($member && $activity->lottery) {
                $activity->lottery->members()->updateOrCreate(['user_id' => $order->user_id, 'lottery_id' => $activity->lottery->id], ['name' => $order->user->name, 'mobile' => $order->user->mobile]);
            }
        }
    }

    /**
     * 推荐的订单 没有作为退款目标订单记录
     * @param $order
     */
    public function markOrderUnusual($order)
    {
        Log::info("检查异常分享订单");
        $target_order = ActivityOrder::whereDoesntHave("targetRefunds")->whereHas("recommendUser", function ($sql) use ($order) {
            $sql->where('recommend_user_id', $order->user_id);
        })->paid()->where('introduce_user_id', $order->user_id)->first();
        if ($target_order) {
            $order->update(['introduce_unusual' => 1, 'unusual_target_id' => $target_order->id]);
        }

    }

    public function addRecommendUser($order)
    {
        $recommend_user_id = $order->introduce_user_id;
        //第一次分享成为介绍人
        $user = $order->user;
        if (!$user->recommendUserLog && $order->user_id != $recommend_user_id) {
            $user->recommendUserLog()->create(['recommend_user_id' => $recommend_user_id]);
        }
    }

    public function registerAgentUser($order)
    {
        //        $form_accid = null;
//        if ($order->introduce_user_id && $order->introduce_user_id != $order->user_id) {
//            $form_accid = User::SAAS_PREFIX.$order->introduce_user_id;
//        }
//        $user = $order->user;
//        $url = config('app.shop_url').'agent/users';
//        $param = ['accid'=>$user->accid(), 'nickname'=>$user->name, 'mobile'=>$user->mobile, 'pic'=>$user->avatar, 'from_accid'=>$form_accid, 'level'=>2];
//        $res = HttpService::postData($url, $param);
        $agent_user = AgentUser::where(['user_id' => $order->user_id])->first();
        if (empty($agent_user) || $agent_user->level == 0) {
            AgentUser::create(['user_id' => $order->user_id, 'level' => 2]);
        }
    }

    public function refundAmount($user_id, $amount, $type, $order = null)
    {
        //介绍人订单
        $introduce_orders = ActivityOrder::owner($user_id)->paid()->residue()->get();
        if ($introduce_orders) {
            $sum = $amount;
            foreach ($introduce_orders as $introduce_order) {
                if ($sum == 0)
                    break;
                if ($introduce_order->residue_amount >= $sum) {
                    $value = $sum;
                } else {
                    $value = $introduce_order->residue_amount;
                }
                $introduce_order->decrement('residue_amount', $value);

                $target_order = $order ?: $introduce_order;
                ActivityIntroduceLog::create(['order_id' => $target_order->id, 'amount' => $value, 'introduce_order_id' => $introduce_order->id, 'type' => $type]);
                //todo 生成退款记录
                if ($type == ActivityIntroduceLog::INTRODUCETYPE) {
                    ActivityShareRefund::create([
                        'user_id' => $introduce_order->user_id,
                        'order_id' => $introduce_order->id,
                        'target_order_id' => $order->id,
                        'trade_no' => $introduce_order->trade_no,
                        'refund_trade_no' => CommonService::getTradeNO(),
                        'total_amount' => $introduce_order->amount,
                        'amount' => $value,
                        'status' => 0,
                        'sub_mch_id' => $introduce_order->sub_mch_id,
                        'type' => ActivityShareRefund::SHARETYPE,
                    ]);
                }

                $sum -= $value;
            }
        }
    }


    /**
     * 扣除余额
     * @param $user_id
     * @param $activity_id
     */
    public function decrementAmount($user_id, $amount, $type, $order = null)
    {
        //介绍人订单
        $introduce_orders = ActivityOrder::owner($user_id)->paid()->residue()->get();
        if ($introduce_orders) {
            $sum = $amount;
            foreach ($introduce_orders as $introduce_order) {
                if ($sum == 0)
                    break;
                if ($introduce_order->residue_amount >= $sum) {
                    $value = $sum;
                } else {
                    $value = $introduce_order->residue_amount;
                }
                $introduce_order->decrement('residue_amount', $value);

                $target_order = $order ?: $introduce_order;
                ActivityIntroduceLog::create(['order_id' => $target_order->id, 'amount' => $value, 'introduce_order_id' => $introduce_order->id, 'type' => $type]);
                //todo 增加收益
                PartnerCommission::create([
                    'order_id' => $target_order->id,
                    'order_no' => $target_order->trade_no,
                    'order_commission_id' => $target_order->id . $target_order->trade_no,
                    'user_id' => $user_id,
                    'role' => 1,
                    'status' => 0,
                    'amount' => $value,
                    'type' => 1,
                ]);
                $sum -= $value;
            }
            //插入余额记录
            ActivityOrderLog::addActivityOrderLog($user_id, $target_order->id, -$amount, "活动签到", null, null, ActivityOrderLog::SIGNIN_TYPE);
        }
    }

    /**
     * 用户订单列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function orders()
    {
        $user_id = auth()->id();
        $orders = ActivityOrder::with('activity:id,title,pic')->owner($user_id)->paid()->orderByDesc('id')->paginate();
        return $this->success('ok', $orders);
    }

    public function order(ActivityOrder $order)
    {
        $order->activity;
        //消耗记录
        $logs = ActivityIntroduceLog::with('order:id,name,mobile')->where('introduce_order_id', $order->id)->get();
        return $this->success('ok', compact('logs', 'order'));
    }

    public function getActivityOrder(ActivityOrder $order, $activity_id)
    {
        $exists = Activity::where('id', $activity_id)->exists();
        if (!$exists) {
            return $this->failure('活动不存在');
        }
        $orders = $order->with(['activity', 'introduceUser'])->Paid()->where('activity_id', $activity_id)->orderByDesc('id')->paginate();
        return $this->success('ok', $orders);
    }
    /**
     * 介绍人订单列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function introduceOrders()
    {
        $user_id = auth()->id();
        $orders = ActivityOrder::with('activity:id,title,pic', 'introduceLog')->introduce($user_id)->paid()->orderByDesc('id')->paginate();
        foreach ($orders as $order) {
            $order->income = 0;
            if ($order->introduceLog) {
                $order->income = $order->introduceLog->amount;
            }
            unset($order->introduceLog);
        }

        return $this->success('ok', $orders);
    }

    public function introduceQrcode($activity_id)
    {
        $user = auth()->user();
        $qrcode = $user->activityQrcodes()->where('activity_id', $activity_id)->where('type', 'H5')->value('qrcode');
        if (!$qrcode) {
            $url = config("app.url") . "/h5/#/activityDetail?id={$activity_id}&from_user_id={$user->id}&from_type=activity";
            $qrcode = CommonService::makeQrcode($url);
            $user->activityQrcodes()->create(['activity_id' => $activity_id, 'type' => "H5", 'qrcode' => $qrcode]);
        }
        return $this->success('ok', compact('qrcode'));

    }

    public function activityMenu(Request $request, $activity_id)
    {
        try {
            $meeting = ActivityMeeting::where('activity_id', $activity_id)->first();
            if (!empty($meeting)) {
                $menus = json_decode($meeting->menu, true);

                $index = -1;
                foreach ($menus as $key => $subArray) {
                    if ($subArray['name'] === "座位查询") {
                        $index = $key;
                        break;
                    }
                }
                if ($index !== -1) {
                    // 移除特定元素并插入到数组第一位
                    $specificElement = $menus[$index];
                    unset($menus[$index]);
                    array_unshift($menus, $specificElement);
                }
                $meeting->menu = $menus;
            }
            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 activityMeetingApply(Request $request, $activity_id)
    {
        try {
            $user_id = auth()->user()->id;
            $name = $request->input('name');
            $mobile = $request->input('mobile');
            if (empty($mobile)) {
                return $this->failure('姓名和电话不为空');
            }
            $is_sign = ActivityMeetingApply::where('activity_id', $activity_id)->where('mobile', $mobile)->first();
            if ($is_sign) {
                if ($is_sign->user_id == 0) {
                    $is_sign->user_id = $user_id;
                    $is_sign->save();
                }
                return $this->success('ok', $is_sign);
            }
            //暂时注释部分，下一个活动打开
            $is_apply = ActivityOrder::paid()->where('activity_id', $activity_id)->where('mobile', $mobile)->first();
            if (!$is_apply) {
                $residue_amount = ActivityOrder::where('user_id', $user_id)->where('mobile', $mobile)->sum('residue_amount');
                if ($residue_amount < ActivityOrder::PRICE) {
                    return $this->failure('余额不足');
                }
            }
            //查看是否导入数据，下个活动去除
//            $import_apply = ImportApplyUser::where('mobile',$mobile)->first();
//            if(!$import_apply){
//                return $this->failure('暂未报名');
//            }
//            $name = $import_apply->name;

            $activity_meeting = ActivityMeeting::where('activity_id', $activity_id)->first();
            if (empty($activity_meeting)) {
                return $this->failure('活动会议不存在');
            }
            $number = $activity_meeting->start_desk;
            //查看是否已经排桌
            $apply_desk_user = ActivityMeetingApply::where('activity_id', $activity_id)->where('desk_number', $number)->count();
            while ($apply_desk_user >= $activity_meeting->user_number) {
                $number = $number + 1;
                $apply_desk_user = ActivityMeetingApply::where('activity_id', $activity_id)->where('desk_number', $number)->count();
            }
            //如果桌子号大于了最大排桌，往没坐满桌子排
//            if($number > $activity_meeting->total_desk){
//                $number = ActivityMeetingApply::where('activity_id',$activity_id)
//                    ->select('desk_number', DB::raw('count(*) as count'))
//                    ->groupBy('desk_number')
//                    ->havingRaw('count(*) < ?', [$activity_meeting->user_number])
//                    ->orderBy('desk_number', 'asc')
//                    ->value('desk_number');
//            }
//            if($number > $activity_meeting->total_desk || $number < $activity_meeting->start_desk || empty($number)){
//                return $this->failure('座位已满，请联系工作人员');
//            }
            $map = [];
            $map['user_id'] = $user_id;
            $map['activity_id'] = $activity_id;
            $map['name'] = $name;
            $map['mobile'] = $mobile;
            $map['desk_number'] = $number;
            ActivityMeetingApply::create($map);
            //暂时注释部分，下一个活动打开
            //没有分享下单，扣除签到金额
            $res = ActivityOrder::notOwner($user_id)->activity($activity_id)->paid()->introduce($user_id)->exists();
            if (empty($res)) {
                $this->decrementAmount($user_id, ActivityOrder::PRICE, $type = "SIGNIN");
            }
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('activityMeetingApply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }



    public function meetingMenuDetail(Request $request, $activity_id)
    {
        try {
            $name = $request->get('name');
            $meeting = ActivityMeeting::where('activity_id', $activity_id)->first();
            if (empty($meeting)) {
                return $this->success('ok', $meeting);
            }
            $menus = json_decode($meeting->menu, true);
            $images = null;
            foreach ($menus as $menu) {
                if (!isset($menu['name']) || !isset($menu['images'])) {
                    continue;
                }
                if ($menu['name'] != $name) {
                    continue;
                }
                $images = $menu['images'];
                break;
            }
            if ($name == "入场签到") {
                $images = $meeting->sign_images;
            }
            return $this->success('ok', $images);
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    public function getMeetingDeskNumber(Request $request, $activity_id)
    {
        try {
            $mobile = $request->get('mobile');
            $desk_number = ActivityMeetingApply::where('activity_id', $activity_id)->where('mobile', $mobile)->first();
            if (empty($desk_number)) {
                return $this->failure('暂未查询到座位');
            }
            $desk_number->desk_images = ActivityMeeting::where('activity_id', $activity_id)->value('desk_images');
            return $this->success('ok', $desk_number);
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    public function addActivityImportApply(Request $request)
    {
        try {
            $name = $request->input('name');
            $mobile = $request->input('mobile');
            $activity_id = $request->input('activity_id');
            if (empty($activity_id))
                return $this->failure('活动id不为空');

            if (empty($mobile) || empty($name)) {
                return $this->failure('手机号不为空');
            }
            $exists = ImportApplyUser::where('activity_id', $activity_id)->where('mobile', $mobile)->exists();
            if ($exists)
                return $this->failure('手机号已存在');

            ImportApplyUser::create(['activity_id' => $activity_id, 'name' => $name, 'mobile' => $mobile]);
            return $this->success("ok");
        } catch (\Exception $e) {
            AddErrorLog::dispatch('addActivityApplyUser file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 查询录入的人员列表
     */
    public function getActivityImportApply(Request $request)
    {
        try {
            $keyword = $request->input('keyword');
            $activity_id = $request->input('activity_id');

            if (empty($activity_id))
                return $this->failure('活动id不为空');

            $list = ImportApplyUser::when($keyword, function ($query) use ($keyword) {
                $query->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', "%" . $keyword . "%");
            })->where('activity_id', $activity_id)->orderByDesc('id')->paginate();

            foreach ($list as $item) {
                $item->is_sign = false;
                $exists = ActivityMeetingApply::where('activity_id', $activity_id)->where('mobile', $item->mobile)->exists();
                if ($exists) {
                    $item->is_sign = true;
                }
            }
            return $this->success("ok", $list);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('addActivityApplyUser file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 获取活动
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getActivity()
    {
        $date = date('Y-m-d H:i:s');
        $activity = Activity::where('start_time', '<=', $date)->where('end_time', '>=', $date)->where('status', Activity::STATUS_OPEN)->orderByDesc('start_time')->first();
        if (empty($activity)) {
            $activity = Activity::where('start_time', '>=', $date)->where('status', Activity::STATUS_OPEN)->orderBy('start_time', 'asc')->first();
        }
        if (empty($activity)) {
            $activity = Activity::where('end_time', '<=', $date)->where('status', Activity::STATUS_OPEN)->orderByDesc('end_time')->first();
        }
        return $this->success('ok', $activity);
    }
}
