<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\Order;
use App\Models\OrderSurvey;
use App\Models\ServiceRole;
use App\Models\Survey;
use App\Services\ChatService;
use App\Facades\TaskService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class SurveyController extends Controller
{
    use ResponseJson;

    /**
     * 问卷调查列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function surveys()
    {
        $surveys = Survey::orders()->keyword()->select('id', 'title')->orderByDesc('id')->simplePaginate();
        foreach ($surveys as $survey) {
            $survey->is_write = ($survey->orderSurveys->first()) ? true : false;
        }
        return $this->success('ok', $surveys);
    }

    /**
     * 问卷调查内容
     * @param Request $request
     * @param Survey $survey
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function orderSurvey(Request $request, Survey $survey)
    {
        $chat_id = $request->input('chat_id');
        $is_im = $request->input('is_im');
        if ($is_im) {
            $group = Group::where('im_chat_id', $chat_id)->first();
        } else {
            $group = Group::where('chat_id', $chat_id)->first();
        }
        $content = $survey->orderSurveys()->where('group_id', $group->id)->value('content');
        if ($content)
            $survey->content = json_encode($content);
        return $this->success('ok', $survey);
    }

    /**
     * 提交问卷调查
     * @param Request $request
     * @param Survey $survey
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function addOrderSurvey(Request $request, Survey $survey)
    {
        $chat_id = $request->chat_id;
        $is_im = $request->input('is_im');
        if ($is_im) {
            $group = Group::where('im_chat_id', $chat_id)->first();
        } else {
            $group = Group::where('chat_id', $chat_id)->first();
        }
        if (!isset($group->order_id) || empty($group->order_id))
            return $this->failure("企业微信群未绑定订单");
        $order_survey = OrderSurvey::where(['survey_id' => $survey->id, 'order_id' => $group->order_id, 'chat_id' => $chat_id])->first();
        if ($order_survey)
            return $this->failure("提交失败，问卷调查已提交");
        $content = $request->input('content');
        if (!is_array($content) || count($content) == 0)
            $this->failure("请完善调查问卷后提交");
        OrderSurvey::create(['survey_id' => $survey->id, 'group_id' => $group->id, 'order_id' => $group->order_id, 'chat_id' => $chat_id, 'content' => json_encode($content)]);

        //发送网易云通知
        $chatService = new ChatService();
        $chatService->sendImMsgUserToUser($group->order_id, '系统通知', ($group->name ?? "") . '调查问卷填写完毕,请所有服务人员填写复盘评估表', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', 'yfheal://app/push/ReviewEvaluate', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);

        DmaProcessLog::addUserProcessLog($group->order->user_id ?? 0, $group->order_id ?? 0, 1, "submit_after_question", ($group->order->name ?? "") . "·填写方案后调查问卷", $group->order->user_id ?? 0, 0);
        DmaProcessLog::addUserProcessLog($group->order->user_id ?? 0, $group->order_id ?? 0, 1, "system_send_evaluate_msg", "系统发送服务评价表填写通知", $group->order->user_id ?? 0, 5);

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

    /**
     * 发送自定义消息
     */
    public function sendSurveyToGroup(Request $request)
    {
        try {
            $chat_id = $request->input('chat_id');
            $is_im = $request->input('is_im');
            if ($is_im) {
                $group = Group::where('im_chat_id', $chat_id)->first();
            } else {
                $group = Group::where('chat_id', $chat_id)->first();
            }
            $survey_id = $request->input('survey_id');
            if ($group && isset($group->owner_id)) {
                $order = Order::where('id', $group->order_id)->first();
                //查看用户是否已有订单
                $chatService = new ChatService();
                $params = [];
                $url = config('app.url') . "/go_html/role_apply#/app/afterSurveyMenu?chat_id=" . $group->im_chat_id;
                Log::info('sendSurveyToGroup url:' . $url);
                $chatService->sendGroupMsg($order->user_id, '问卷调查', $group->name ?? "" . '本次为问卷调查，请点击查看详情', 'https://image.fulllinkai.com/202403/29/db0ba6c40579c15293969a7097a77a0c.png', $url, $params);
            }
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('sendSurveyToChat 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 sendImChatMsg(Request $request)
    {
        $chat_id = $request->input('chat_id');
        $is_im = $request->input('is_im');
        if ($is_im) {
            $group = Group::where('im_chat_id', $chat_id)->first();
        } else {
            $group = Group::where('chat_id', $chat_id)->first();
        }
        if ($group && isset($group->owner_id)) {
            $order = Order::where('id', $group->order_id)->first();
            //查看用户是否已有订单
            $chatService = new ChatService();
            $chatService->sendGroupMsg($order->user_id, '健康信息', $group->name ?? "" . '本次为健康信息填写，请点击查看详情', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', 'yfheal://app/push/InputInfoHealthManagerFirstPage', []);
        }
        return $this->success('ok');
    }
}
