<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Events\OrderServeFinishedEvent;
use App\Events\OrderServeStartedEvent;
use App\Exports\AgencyExport;
use App\Exports\AgreementExport;
use App\Exports\AgreementLogExport;
use App\Exports\OrderSchemeExport;
use App\Exports\OrdersExport;
use App\Exports\OrdersExportV2;
use App\Exports\OrderStatExport;
use App\Exports\SchemeExport;
use App\Exports\StepApplyExport;
use App\Facades\CommonService;
use App\Facades\TaskService;
use App\Http\Controllers\Controller;
use App\Jobs\AddErrorLog;
use App\Jobs\SendTemplateNotice;
use App\Models\Agency;
use App\Models\Agreement;
use App\Models\AgreementLog;
use App\Models\Collaborator;
use App\Models\DmaProcessLog;
use App\Models\DmaShop;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\GuideScheme;
use App\Models\MarkOrderLog;
use App\Models\Order;
use App\Models\OrderOperateLog;
use App\Models\Quota;
use App\Models\QuotaLog;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\Shop;
use App\Models\ShopOrder;
use App\Models\ShopOrderStatus;
use App\Models\User;
use App\Models\UserStepApply;
use App\Services\FatService;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends Controller
{
    public function orders(Request $request)
    {
        $orders = Order::with([
            'user:id,name,mobile,avatar,is_privacy',
            'service:id,title,pic',
            'agency:id,name,mobile',
            //            'agency' => function($agency){
//                $agency->with('partner:id,name,mobile')->select('id','province','city','partner_id');
//            },
            'commission' => function ($commission) {
                $commission->with(['service_user:user_id,name,mobile'])->select('id', 'order_id', 'role', 'user_id');
            },
            'service_role' => function ($service_role) {
                $service_role->with(['serviceUser:user_id,name,mobile'])->select('order_id', 'role_id', 'user_id');
            },
            'offline_order:id,order_id,operate_user_id,operate_user_name',
            'agreement:order_id,number,sign_date,quota_id',
            'agreement.quotaInfo:id,agency_id,collaborator_id,num',
            'agreement.quotaInfo.collaboratorInfo:id,avatar,name,mobile',
            'agreement.quotaInfo.agencyInfo:id,grade,pro_id,city_id,province,city',
            "recommendUser",
            "asginSigner:order_id,status,company_status,user_sign_url,company_sign_url",
            "asginContract:order_id,preview_url",
            "userInfo:user_id,card_photo",
            "payment",
            "group",
        ])->serviceOrder();
        $keyword = $request->input('keyword');
        //关键词筛选
        if ($keyword) {
            $keyword = trim($keyword);
            // $orders = $orders->whereHas("user", function ($sql) use ($keyword) {
            //     $sql->where('name', 'like', '%' . $keyword . '%')
            //         ->orWhere('mobile', 'like', '%' . $keyword . '%');
            // });

            $orders = $orders->Where(function ($sql) use ($keyword) {
                $sql->whereHas("user", function ($sql) use ($keyword) {
                    $sql->where('name', 'like', '%' . $keyword . '%')
                        ->orWhere('mobile', 'like', '%' . $keyword . '%');
                })->orWhere("name", "like", "%" . $keyword . "%")->orWhere('mobile', 'like', '%' . $keyword . '%');
            });
        }

        //支付状态筛选
        $pay_status = $request->input('pay_status');
        if ($pay_status) {
            $orders = $orders->where('pay_status', $pay_status);
        }

        //开始状态筛选
        $status = $request->input('status');
        if ($status) {
            $orders = $orders->where("status", $status);
        }

        //子公司筛选
        $agency_id = $request->input('agency_id');
        if ($agency_id) {
            //            $orders = $orders->where("agency_id", $agency_id);
            $orders = $orders->whereHas('agreement.quotaInfo', function ($query) use ($agency_id) {
                $query->where('agency_id', $agency_id);
            });
        }
        $is_export = $request->input('is_export');
        if ($is_export) {
            $orders = $orders->orderByDesc('id')->get();
            return Excel::download(new OrdersExportV2($orders), 'DMA订单.xlsx');
        }
        $orders = $orders->orderByDesc('id')->paginate();

        foreach ($orders as $order) {
            if ($order->user) {
                $order->user->makeVisible('mobile');
            }
        }
        return $this->success('ok', $orders);
    }

    public function getAllOrders()
    {
        $list = Order::select('id', 'name', 'mobile', 'trade_no')->get();
        return $this->success('ok', $list);
    }
    /**
     * 设置订单是否展示
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function setOrderIsShow(Request $request)
    {
        try {
            $is_show = $request->get('is_show');
            $order_id = $request->get('order_id');
            $order_info = Order::where('id', $order_id)->first();
            if (empty($order_info)) {
                return $this->failure('订单不存在');
            }
            $order_info->is_show = $is_show;
            $order_info->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('setOrderIsShow:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function export(Request $request)
    {
        return Excel::download(new OrdersExport($request->all()), '订单.xlsx');
    }

    public function order(Request $request, $order_id)
    {
        $order = Order::find($order_id); //service_users.id,service_users.user_id,service_users.name,service_users.mobile'
        $roles = ServiceRole::with([
            'roleUsers' => function ($sql) use ($order_id) {
                $sql->where('order_id', $order_id);
            }
        ])->get();
        $order->service = $order->service()->select('id', 'pic', 'title')->first();
        $order->group;
        //是否有餐单
        $order->has_guides = $order->guides()->count() ? 1 : 0;
        if ($order->has_guides) {
            $order->guide_status = 'MADE';
            Cache::forget('guide_status_' . $order_id);
        } else {
            //餐单生成状态
            $order->guide_status = Cache::get('guide_status_' . $order_id, 'NOTMAKE');
        }

        foreach ($roles as $role) {
            $url = config('app.url') . "/h5/#/temporaryIdentity?order_id=" . $order_id . "&role=" . $role->id;
            $role->qr_code = CommonService::makeqrcode($url);
            if (count($role->roleUsers)) {

                $role->share_option = ServiceRoleOrder::where("order_id", $order_id)->where("user_id", ($role->roleUsers)[0]->user_id)->where("role_id", $role->id)->value("share_option") ?: "";
            }
        }

        $order->asginContract;
        $order->asginSigner;
        return $this->success('ok', compact('order', 'roles'));
    }

    public function changeOrderAgency(Request $request, $order_id)
    {
        $order = Order::find($order_id);
        $agency_id = $request->input('agency_id');
        $order->agency_id = $agency_id;
        $order->save();

        //操作记录
        OperationLoggedEvent::dispatch("修改订单: $order->id 的子公司为:$agency_id");
        return $this->success('ok');
    }

    public function updateOrder(Request $request, $order_id)
    {
        $order = Order::find($order_id);
        $status = $request->input('status');
        if ($status) {
            $order->status = $status;
            if ($status == 'STARTING') { //通知
                $user = $order->user;
                if ($user && $user->officialWechat) {
                    $param = [
                        'touser' => $user->officialWechat->openid,
                        'template_id' => config('wechat.tpls.make_guide_notice'),
                        'url' => '',
                        'miniprogram' => [
                            'appid' => config('wechat.mini_program.app_id'),
                            'pagepath' => 'pages/tabBar/serve',
                        ],
                        'data' => [
                            'first' => ['value' => '您的餐单生成成功！'],
                            'keyword1' => ['value' => $user->name],
                            "keyword2" => ['value' => date('Y-m-d H:i:s')],
                            'remark' => ['value' => "点击进入查看详情"]
                        ]
                    ];
                    SendTemplateNotice::dispatch($param)->onQueue('health');
                }

                //该订单是否是线下订单
                if ($order->offline_order) {
                    //触发订单服务开始事件
                    OrderServeStartedEvent::dispatch($order->offline_order);
                }

            }

            //订单结束
            if ($status == 'FINISHED') {
                //该订单是否是线下订单
                if ($order->offline_order) {
                    //触发订单结束事件
                    OrderServeFinishedEvent::dispatch($order->offline_order);
                }
            }

            //操作记录
            OperationLoggedEvent::dispatch("修改订单: $order->id 的状态为:$status");
        }
        $order->save();
        return $this->success('ok');
    }

    public function updateOrderCheckSign(Request $request, $order_id)
    {
        $order = Order::find($order_id);
        //合同签署
        $check_sign_status = $request->input("check_sign_status");
        $order->check_sign_status = $check_sign_status;
        $order->save();

        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order_id, 1, "admin_sign_status", "行政确认用户已签署合同", auth()->user()->id ?? 0, 4);
        //创建群聊
        $group_exists = Group::where("order_id", $order_id)->exists();
        if ($group_exists) {
            $group = new Group();
            $group->autoCreateChat($order->id);
        }

        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order_id, 1, "create_group", "已自动建立群聊", auth()->user()->id ?? 0, 4);
        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order_id, 1, "add_user_to_group", "行政已拉用户入群", auth()->user()->id ?? 0, 4);
        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order_id, 1, "send_group_notice", "系统已发送群公告", auth()->user()->id ?? 0, 5);

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

    public function storeOrderRoleUser(Request $request, Order $order)
    {
        $role_user_id = $request->input('role_user_id');
        $user_id = $request->input("user_id");
        $role_id = $request->input('role_id');
        $role_user = null;
        if ($role_user_id) {
            $role_user = ServiceUser::find($role_user_id);
        } else if ($user_id) {
            $role_user = ServiceUser::where("user_id", $user_id)->first();
        }
        if (empty($role_user)) {
            return $this->failure("服务人员不存在");
        }

        $role = $role_user->roles()->where('service_roles.id', $role_id)->first();
        if (empty($role))
            throw new \Exception("用户角色有误");
        //订单角色是否存在
//        $order_role = ServiceRoleOrder::where('order_id',$order->id)->where('role_id', $role_id)->first();
//        if ($order_role) return $this->failure("订单已经有角色【".$role->name."】");
        if (empty($role_user->user_id))
            return $this->failure("该服务成员未绑定微信信息");
        DB::beginTransaction();
        ServiceRoleOrder::firstOrCreate(['order_id' => $order->id, 'role_id' => $role->id, 'user_id' => $role_user->user_id]);
        //        GroupUser::firstOrCreate(['user_id'=>$role_user->user_id, 'group_id'=>$order->group->id, 'role_id'=>$role->id, 'role_name'=>$role->name]);
        $groupRoles = [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER, ServiceRole::TUTOR, ServiceRole::PERSONAL_COACH, ServiceRole::INTERN_COACH];
        if (!empty($order->group->im_chat_id) && in_array($role_id, $groupRoles)) {
            GroupUser::addGroupUser($order->group, $role_user, [$role_id]);
        }
        DB::commit();
        //操作记录
        OperationLoggedEvent::dispatch("给订单: $order->id 增加服务人员-$role->name :$role_user->name");
        DmaProcessLog::addUserProcessLog($order->user_id, $order->id, 1, "add_server_to_group", "行政已拉服务人员入群", auth()->user()->id, 4);
        return $this->success('ok');
    }

    public function deleteOrderRoleUser(Request $request, Order $order)
    {
        DB::beginTransaction();
        $role_id = $request->input("role_id");
        $user_id = $request->input("user_id");
        $role_order = ServiceRoleOrder::where('order_id', $order->id)->where('user_id', $user_id)->where('role_id', $role_id)->first();
        GroupUser::where(['user_id' => $role_order->user_id, 'group_id' => $order->group->id, 'role_id' => $role_order->role_id])->delete();
        ServiceRoleOrder::where('order_id', $order->id)->where('user_id', $user_id)->where('role_id', $role_id)->delete();
        DB::commit();

        if (!empty($order->group->im_chat_id)) {
            $owner_ac_cid = make_wangyiyun_accid($order->group->owner_id);
            $delete_user_ac_cid = make_wangyiyun_accid($role_order->user_id);

            $other_role = ServiceRoleOrder::where('order_id', $order->id)->where('user_id', $user_id)->where('role_id', "<>", $role_id)->first();
            if (empty($other_role)) {
                //踢人
                $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
                $imTeam->kick($order->group->im_chat_id, $owner_ac_cid, $delete_user_ac_cid);
            }
        }
        //操作记录
        OperationLoggedEvent::dispatch("删除了订单的: $order->id 的服务人员:$role_order->user_id");
        return $this->success('ok');
    }

    /**
     * 查询订单方案列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getOrderSchemeList(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $end_time = date('Y-m-d', strtotime('+1 day', strtotime($end_time)));
            //            $order_scheme = Order::with('scheme')
//                ->when($keyword,function($query) use ($keyword) {
//                    $query->where('name','like','%'.$keyword."%");
//                })
//                ->whereHas('scheme',function ($roleQuery) use ($start_time,$end_time){
//                    if(!empty($start_time)){
//                        $roleQuery->whereBetween('created_at',[$start_time,$end_time]);
//                    }
//                })
//                ->orderBy('created_at','desc')
//            ->paginate();
            $order_scheme = Order::rightJoin('guide_schemes', 'orders.id', '=', 'guide_schemes.order_id')
                ->when($keyword, function ($query) use ($keyword) {
                    $query->where('orders.name', 'like', '%' . $keyword . "%");
                })
                ->where(function ($query) use ($start_time, $end_time) {
                    if (!empty($start_time)) {
                        $query->whereBetween('guide_schemes.created_at', [$start_time, $end_time]);
                    }
                })
                ->orderByDesc('guide_schemes.created_at')
                ->paginate();
            return $this->success('ok', $order_scheme);
        } catch (\Exception $e) {
            Log::error('getOrderSchemeList:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 导出数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function exportOrderSchemeList(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $end_time = date('Y-m-d', strtotime('+1 day', strtotime($end_time)));
            $order_scheme = Order::rightJoin('guide_schemes', 'orders.id', '=', 'guide_schemes.order_id')
                ->when($keyword, function ($query) use ($keyword) {
                    $query->where('orders.name', 'like', '%' . $keyword . "%");
                })
                ->where(function ($query) use ($start_time, $end_time) {
                    if (!empty($start_time)) {
                        $query->whereBetween('guide_schemes.created_at', [$start_time, $end_time]);
                    }
                })
                ->orderByDesc('guide_schemes.created_at')
                ->get()->toArray();
            // 下载 Excel 文件
            return Excel::download(new OrderSchemeExport($order_scheme), 'Reappraises.xlsx');
        } catch (\Exception $e) {
            Log::error('getOrderSchemeList:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 通过订单id获取餐单方案
     * @param Request $request
     * @param Order $order
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getSchemeByOrderId(Request $request, Order $order)
    {
        if (empty($order)) {
            return $this->failure('订单不存在');
        }
        $scheme = GuideScheme::where('order_id', $order->id)->first();
        return $this->success('ok', $scheme);
    }

    /**
     * 更新方案
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateOrderScheme(Request $request)
    {
        try {
            $order_id = $request->input('order_id');
            if (empty($order_id)) {
                return $this->failure('订单不存在');
            }
            $scheme_info = GuideScheme::where('order_id', $order_id)->first();
            if (empty($scheme_info)) {
                return $this->failure('方案不存在');
            }
            $schemes = $request->input("schemes") ?? [];
            $hour = (time() - strtotime($scheme_info->created_at)) / 3600;
            if ($hour > 24) {
                //插入操作记录
                OrderOperateLog::create(['order_id' => $order_id, 'type' => 2]);
            }
            $scheme_info->update(['scheme' => $schemes]);
            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 导出方案信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function exportOrderScheme(Request $request)
    {
        try {
            $order_id = $request->get('order_id');
            if (empty($order_id)) {
                return $this->failure('订单不存在');
            }
            $scheme = GuideScheme::where('order_id', $order_id)->first();
            return Excel::download(new SchemeExport($scheme), 'scheme.xlsx');
        } catch (\Exception $e) {
            Log::error('exportScheme:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }

    public function addAgreement(Request $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->only(['order_id', 'number', 'sign_date', 'material_type', 'sign_id', 'introduce_id', 'introduce_rights', 'quota_id']);
            $validated = Validator::make($data, [
                'order_id' => 'required|unique:agreement',
                'sign_date' => 'required',
                'sign_id' => 'required',
                'number' => 'required|unique:agreement',
                'quota_id' => 'required',
            ], [
                'order_id.unique' => '订单已存在协议',
                'order_id.required' => '请选择订单',
                'sign_date.required' => '请填写签署日期',
                'number.required' => '请填写协议编号',
                'number.unique' => '协议编号重复',
                'sign_id.required' => '请选择合作商',
                'quota_id.required' => '请选择名额归属'
            ]);

            $data['introduce_rights'] = json_encode($data['introduce_rights']);

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

            $quota_info = Quota::find($data['quota_id']);
            if (empty($quota_info))
                return $this->failure('名额归属不为空');

            $admin = auth()->user();

            $quota_info->num = $quota_info->num - Quota::USE_NUM;
            if ($quota_info->num < 0) {
                return $this->failure('名额不足');
            }
            $quota_info->save();

            QuotaLog::addQuotaLog($admin, $data['order_id'], Quota::USE_NUM, $quota_info->id);

            $agreementModel = Agreement::create($data);


            AgreementLog::addAgreementLog($admin, $data['order_id'], $agreementModel->id, "创建了订单协议");
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('addAgreement:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function getAgreement(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $order_id = $request->get('order_id');
            $no_page = $request->get('no_page');
            $is_export = $request->get('is_export');
            if ($is_export) {
                $no_page = true;
            }
            $query = Agreement::query()->with('signInfo', 'introduceInfo', 'orderInfo', 'quotaInfo');

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

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

            $query->orderByDesc('id');

            if ($no_page) {
                $list = $query->get();
            } else {
                $list = $query->paginate();
            }
            foreach ($list as $item) {
                $item->img = json_decode($item->img);
                $item->notice_img = json_decode($item->notice_img);
                $item->rights_img = json_decode($item->rights_img);
                $item->introduce_rights = json_decode($item->introduce_rights, true);
                $item->agency_info = null;
                if (empty($item->quotaInfo)) {
                    continue;
                }
                $item->agency_info = Agency::where('id', $item->quotaInfo->agency_id)->first();
                $item->collaborator_info = Collaborator::where('id', $item->quotaInfo->collaborator_id)->first();
            }
            if ($is_export) {
                return Excel::download(new AgreementExport($list), '协议.xlsx');
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getAgreement:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function updateAgreement(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $data = $request->only(['number', 'sign_date', 'material_type', 'sign_id', 'introduce_id', 'introduce_rights', 'quota_id', 'is_receive', 'is_notice', 'notice_img', 'rights_img', 'img']);
            $detail = Agreement::findOrFail($id);

            $remark = "修改了订单协议:";
            if (isset($data['is_notice']) && $data['is_notice']) {
                $remark .= "标记通知书.";
            }
            if (isset($data['is_receive']) && $data['is_receive']) {
                $remark .= "标记权益已领取.";
            }
            if (isset($data['img']) && !empty($data['img'])) {
                $remark .= "添加扫描文件.";
            }
            $admin = auth()->user();
            AgreementLog::addAgreementLog($admin, $detail->order_id, $id, $remark);

            //查看名额是否修改
            if (!empty($data['quota_id']) && ($data['quota_id'] != $detail->quota_id)) {
                $old_quota = Quota::find($detail->quota_id);
                $old_quota->num = $old_quota->num + Quota::USE_NUM;
                $old_quota->save();
                QuotaLog::addQuotaLog($admin, $detail->order_id, Quota::USE_NUM, $old_quota->id);

                $new_quota = Quota::find($data['quota_id']);
                if ($new_quota->num < 0) {
                    return $this->failure('名额不足');
                }
                $new_quota->num = $new_quota->num + Quota::USE_NUM;
                $new_quota->save();
                QuotaLog::addQuotaLog($admin, $detail->order_id, Quota::USE_NUM, $new_quota->id);

                AgreementLog::addAgreementLog($admin, $detail->order_id, $id, '修改订单协议名额:旧名额id为:' . $old_quota->id . '|新的名额id为:' . $new_quota->id);
            }

            $detail->update($data);
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateAgreement:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function getAgreementDetail($id, Agreement $agreement)
    {
        try {
            $detail = $agreement->with('signInfo', 'introduceInfo', 'orderInfo')->find($id);
            $detail->img = json_decode($detail->img);
            $detail->notice_img = json_decode($detail->notice_img);
            $detail->rights_img = json_decode($detail->rights_img);
            $detail->introduce_rights = json_decode($detail->introduce_rights);
            $detail->quota_info = Quota::with('agencyInfo')->where('id', $detail->quota_id)->first();
            return $this->success('ok', $detail);
        } catch (\Exception $e) {
            Log::error('getAgreementDetail:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function getAgreementLog(Request $request, $id, AgreementLog $agreementLog)
    {
        try {
            $is_export = $request->get('is_export');
            $query = $agreementLog::query()->with('agreement')->where('agreement_id', $id);

            $query->orderByDesc('id');
            if ($is_export) {
                $list = $query->get();
            } else {
                $list = $query->paginate();
            }

            if ($is_export) {
                return Excel::download(new AgreementLogExport($list), '协议操作记录.xlsx');
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getAgreementLog:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

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

            $query = UserStepApply::query()->with(['user']);

            $query->when(strlen($status) > 0, function ($query) use ($status) {
                $query->where('status', $status);
            });
            $query->whereHas('user', function ($query) use ($keyword) {
                $query->where('name', 'like', '%' . $keyword . '%');
            });

            if ($is_export) {
                $list = $query->get();
                return Excel::download(new StepApplyExport($list), '订单.xlsx');
            } else {
                $list = $query->paginate();
            }

            return $this->success('ok', $list);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getStepApply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function updateStepApplyStatus(Request $request, $id)
    {
        try {
            $detail = UserStepApply::findOrFail($id);

            if ($request->has('status')) {
                $detail->status = $request->input('status');
            }
            if ($request->has('reason')) {
                $detail->reason = $request->input('reason');
            }
            $detail->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('updateStepApplyStatus file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('更新失败');
        }
    }

    public function getOrderStatList(Request $request)
    {
        try {
            $type = $request->get('type');
            $keyword = $request->get('keyword');
            $query = Order::query();

            $is_export = $request->get('is_export');

            if ($type == 0) {
                $query->where('pay_status', 'PAID');
            }

            if ($type == 1) {
                $query->whereNotIn('id', function ($sql) {
                    $sql->where('role_id', ServiceRole::MAIN_COACH)->select('order_id')->from('service_role_orders');
                });
            }

            if ($type == 2) {
                $query->whereNotIn('id', function ($sql) {
                    $sql->where('role_id', ServiceRole::COACH)->select('order_id')->from('service_role_orders');
                });
            }

            if ($type == 3) {
                $query->whereNotIn('id', function ($sql) {
                    $sql->where('role_id', ServiceRole::CUSTOMER)->select('order_id')->from('service_role_orders');
                });
            }

            if ($type == 4) {
                $query->leftJoin('users as u', 'u.id', '=', 'orders.user_id')
                    ->where(function ($query) {
                        $query->whereNull('u.id')
                            ->orWhere(function ($query) {
                                $query->whereNull('u.name')
                                    ->orWhereNull('u.birthday')
                                    ->orWhereNull('u.stature');
                            });
                    });
            }

            $query->select('orders.*');

            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
            });

            if ($is_export) {
                $list = $query->get();
                return Excel::download(new OrderStatExport($list), '订单统计.xlsx');
            }
            $list = $query->paginate();
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getOrderStatList file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function getOrderMarkLog(Request $request, $id)
    {
        try {
            $keyword = $request->input('keyword');
            $query = MarkOrderLog::query();

            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('operate_name', 'like', '%' . $keyword . '%')->orWhere('remark', 'like', '%' . $keyword . '%');
            });

            $query->where('order_id', $id);

            $log = $query->paginate();

            return $this->success('ok', $log);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getOrderMarkLog file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取图标数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getFatKindsV1(Request $request)
    {
        $user_id = $request->input('user_id');
        if (empty($user_id)) {
            return $this->failure('用户id不为空');
        }
        $user = User::find($user_id);
        if (empty($user))
            return $this->failure("用户不存在");
        $fatService = new FatService();
        $res = $fatService->getFatKinds($user);

        if (!$res['status']) {
            return $this->failure($res['msg']);
        }
        return $this->success('ok', $res['data'] ?? []);
    }

    /**
     * 获取图表统计
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getFatStatV1(Request $request)
    {
        try {
            $user_id = $request->input('user_id');
            if (empty($user_id)) {
                return $this->failure('用户id不为空');
            }
            $name = $request->input('fat_name');
            $start_date = $request->input('start_date');
            $end_date = $request->input('end_date');

            $user = User::find($user_id);
            if (empty($user))
                return $this->failure("用户不存在");

            $fatService = new FatService();
            $res = $fatService->getFatStat($name, $start_date, $end_date, $user, "斤");

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getFatStatV1:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }
}
