<?php

namespace App\Http\Controllers\Admin;

use App\Exports\DragonUserExport;
use App\Exports\TalkExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SendEasySms;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\DmaServiceUserRole;
use App\Models\DragonConfig;
use App\Models\DragonUser;
use App\Models\Group;
use App\Models\Order;
use App\Models\Talk;
use App\Models\TalkComment;
use App\Models\TalkStar;
use App\Services\OfflineOrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Log;
use Maatwebsite\Excel\Facades\Excel;

class OtherController extends Controller
{
    use ResponseJson;

    public function createTalk(Request $request)
    {
        try {
            $title = $request->input('title');
            if (empty($title))
                return $this->failure('标题不为空');

            $images = $request->input('images');
            $images = json_encode($images);
            $model = Talk::create(['title' => $title, 'images' => $images]);

            $content = "欢迎参加头脑风暴[{$title}](" . config('app.url') . "/work/#/h5/discussDetail?id={$model->id})点击名称可以进入讨论详情";
            $send_data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $content,
                ]
            ];
            //正式群
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
            //测试群
            if (!(config('app.env') == 'production')) {
                $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
            }
            //            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
            //本地群
//            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";
            $response = Http::post($url, $send_data);
            $status = $response->status(); // 获取响应状态码
            if ($status != 200) {
                return $this->failure('发送失败');
            }

            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure('createTalk file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getTalkList(Request $request)
    {
        try {
            $keyword = $request->input('keyword');
            $is_export = $request->input('is_export');
            $type = $request->input('type');
            $status = $request->input('status');

            $query = Talk::query();

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

            $query->when(strlen($type) > 0, function ($query) use ($type) {
                $query->where('type', $type);
            });

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

            $query->orderByDesc('id');

            if ($is_export) {
                $list = $query->get();
                if ($list->isEmpty()) {
                    return $this->failure('暂无数据');
                }
                return Excel::download(new TalkExport($list), 'talk.xlsx');
            } else {
                $list = $query->paginate();
            }

            foreach ($list as $item) {
                $item->star = TalkStar::where('talk_id', $item->id)
                    ->count();
                $item->comment = TalkComment::where('talk_id', $item->id)
                    ->count();
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            return $this->failure('getTalkList file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getTalkDetail($id)
    {
        try {
            $detail = Talk::find($id);
            $detail->star = TalkStar::where('talk_id', $detail->id)
                ->count();
            $detail->comment = TalkComment::where('talk_id', $detail->id)
                ->count();
            return $this->success('ok', $detail);
        } catch (\Exception $e) {
            return $this->failure('getTalkDetail file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getTalkComment(Request $request, $id)
    {
        try {
            $keyword = $request->input('keyword');
            $comment = TalkComment::with(['user', 'serviceUser'])->where('talk_id', $id)
                ->where('content', 'like', '%' . $keyword . '%')
                ->where('type', TalkComment::TYPE_COMMENT)
                ->whereNull('comment_id')->orderByDesc('id')->paginate();
            foreach ($comment as $item) {
                $item->reply = TalkComment::with('user')->where('talk_id', $id)
                    ->where('type', TalkComment::TYPE_REPLY)
                    ->where('comment_id', $item->id)
                    ->orderByDesc('id')
                    ->get();
                $item->star = TalkStar::where('comment_id', $item->id)->count();
                if (isset($item->serviceUser)) {
                    $item->user->name = $item->serviceUser->name;
                    $item->user->mobile = $item->serviceUser->mobile;
                }
            }
            return $this->success('ok', $comment);
        } catch (\Exception $e) {
            return $this->failure('getTalkComment file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function updateTalk(Request $request, $id)
    {
        try {
            $detail = Talk::findorFail($id);
            if ($request->has('status')) {
                $detail->status = $request->input('status');
            }
            if ($request->has('title')) {
                $detail->title = $request->input('title');
            }
            if ($request->has('images')) {
                $detail->images = $request->input('images');
            }
            $detail->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure('updateTalk file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function deleteTalk($id)
    {
        try {
            Talk::where('id', $id)->delete();
            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure('deleteTalk file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getStarList(Request $request, $id)
    {
        try {
            $comment_id = $request->input('comment_id');
            $query = TalkStar::query()->with(['user']);
            $query->where('talk_id', $id);

            $query->when($comment_id, function ($query) use ($comment_id) {
                $query->where('comment_id', $comment_id);
            });
            $list = $query->orderByDesc('id')->paginate();
            foreach ($list as $item) {
                $item->content = '';
                if (empty($item->comment_id)) {
                    continue;
                }
                $item->content = TalkComment::where('id', $item->comment_id)->value('content');
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            return $this->failure('getStarList file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function createDragonConfig(Request $request)
    {
        try {
            $title = $request->input('title');
            $status = $request->input('status', DragonConfig::STATUS_OPEN);
            $config = $request->input('config');
            $open_rank = $request->input('open_rank', DragonConfig::OPEN_RANK_OFF);
            if (empty($title))
                return $this->failure('标题不为空');

            $model = DragonConfig::create(['title' => $title, 'status' => $status, 'config' => $config, 'open_rank' => $open_rank]);

            $domain = config('app.url');
            $content = "欢迎参加接龙[{$title}]({$domain}/api/oa/work/auth?target_path=inviteMerchant&id={$model->id})点击名称可以进入";
            $send_data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $content,
                ]
            ];
            //本地群
            $url = config("wechat.work.robot.local_url");
            //测试群
            if ((config('app.env') == 'production')) {
                $url = config("wechat.work.robot.online_url");
            }
            if (strpos($title, "测试") !== false) {
                $url = config("wechat.work.robot.test_url");
            }
            $response = Http::post($url, $send_data);
            $res = $response->status(); // 获取响应状态码
            if ($res != 200) {
                return $this->failure('发送失败');
            }
            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure('createDragonConfig file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getDragonConfigList(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $is_export = $request->get('is_export');
            $query = DragonConfig::query();
            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('title', 'like', '%' . $keyword . '%');
            });
            $query->orderByDesc('id');
            if ($is_export) {
                $list = $query->get();
            }
            $list = $query->paginate();
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            return $this->failure('getDragonList file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function updateDragonConfig(Request $request, $id)
    {
        try {
            $detail = DragonConfig::find($id);
            $data = $request->only(['title', 'status', 'open_rank', 'config']);
            if (empty($data['title']))
                return $this->failure('标题不为空');

            $detail->update($data);
            return $this->success('ok', $detail);
        } catch (\Exception $e) {
            return $this->failure('updateDragonConfig file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function deleteDragonConfig($id)
    {
        try {
            DragonConfig::where('id', $id)->delete();
            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->failure('deleteDragonConfig file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function getDragonUser(Request $request, $id)
    {
        try {
            $keyword = $request->get('keyword');
            $is_export = $request->get('is_export');
            $query = DragonUser::query();
            $query->where('dragon_id', $id);
            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('name', 'like', '%' . $keyword . '%')->orWhere('invite_name', 'like', '%' . $keyword . '%');
            });
            $query->orderByDesc('id');
            if ($is_export) {
                $list = $query->get();
                return Excel::download(new DragonUserExport($list), 'dragon_user.xlsx');
            }
            $list = $query->paginate();
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            return $this->failure('getDragonUser file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
        }
    }

    public function checkDmaQuestion(Request $request, $id)
    {
        $status = $request->input("status");
        $remark = $request->input("remark");

        $question = DB::table("dma_question")->where("id", $id)->first();
        $user = DB::table("users")->where("id", $question->user_id)->first();

        //查看用户订单是否存在,存在则绑定群id
        $order = Order::getPayOrder($user->id);
        $order_id = $order->id ?? null;
        if ($status == 1) {
            //创建虚拟订单
            $data = [];
            $data['name'] = $user->name;
            $data['price'] = Order::ORDER_PRICE;
            $data['mobile'] = $user->mobile;
            $OfflineOrderService = new OfflineOrderService();
            if (!$order) {
                $offline_order = $OfflineOrderService->createOfflineOrder($data, $user->id);
                //创建群聊
                $group = new Group();
                $group->autoCreateChat($offline_order->order_id);
                $order_id = $offline_order->order_id ?? null;
            }
        }

        DB::table("dma_question")->where("id", $id)->update(["status" => $status, "order_id" => $order_id ?? null, "remark" => $remark]);
        return $this->success('ok');
    }

    public function checkBeforeDmaQuestion(Request $request, $id)
    {
        $status = $request->input("status");
        $remark = $request->input("remark");

        $question = DB::table("before_dma_question")->where("id", $id)->first();
        $user = DB::table("users")->where("id", $question->user_id)->first();

        //查看用户订单是否存在,存在则绑定群id
        $order = Order::getPayOrder($user->id);
        $order_id = $order->id ?? null;
        if ($status == 1) {
            //创建虚拟订单
            $data = [];
            $data['name'] = $user->name;
            $data['price'] = Order::ORDER_PRICE;
            $data['mobile'] = $user->mobile;
            $OfflineOrderService = new OfflineOrderService();
            if (!$order) {
                $offline_order = $OfflineOrderService->createOfflineOrder($data, $user->id);
                $order_id = $offline_order->order_id ?? null;
            }

            DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "check_dma_question", "系统已同意[" . $user->name . "]的方案前调查表单", auth()->user()->id ?? 0, 4);

        } elseif ($status == 2) {
            $order_id = "";
            DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "check_dma_question", "系统已拒绝[" . $user->name . "]的方案前调查表单", auth()->user()->id ?? 0, 4);
        }
        DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "send_check_dma_question_to_user", "系统已发送[审核结果]给" . $user->name, auth()->user()->id ?? 0, 5);

        DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "send_check_dma_question_to_admin", "系统已发送[审核结果]给行政", auth()->user()->id ?? 0, 5);
        DB::table("before_dma_question")->where("id", $id)->update(["status" => $status, "order_id" => $order_id, "remark" => $remark, "operate_user_id" => auth()->user()->id, "operate_user_name" => auth()->user()->name]);

        if ($status == 1) {
            Log::info("通知行政");
            $data = [
                'message' => "用户" . $user->name . "的方案前健康评估表已审核通过，请跟进后续服务【友福同享】",
            ];
            // 短信通知行政
            $roles = DmaServiceUserRole::with("user")->where("status", 1)->where("role", 8)->get();
            foreach ($roles as $role) {
                if ($role->user && $role->user->mobile) {
                    Log::info("通知行政 " . $role->user->mobile);
                    SendEasySms::dispatch($role->user->mobile, $data, $role->user->area_code)->onQueue('send.code.sms');
                }
            }
        }
        return $this->success('ok');
    }
}
