<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Exports\OfflineOrderExport;
use App\Exports\OfflineOrderExportV2;
use App\Facades\ChatService;
use App\Facades\TaskService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\UnfreezeCommission;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\Order;
use App\Models\User;
use App\Services\OfflineOrderService;
use App\Validators\OfflineOrderValidator;
use cccdl\yunxin_sdk\Im\Msg;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class OfflineOrderController extends Controller
{
    use ResponseJson;
    private Order $order;
    private OfflineOrderService $offlineOrderService;
    private OfflineOrderValidator $validator;
    public function __construct(Order $order, OfflineOrderService $offlineOrderService, OfflineOrderValidator $offlineOrderValidator)
    {
        $this->order = $order;
        $this->offlineOrderService = $offlineOrderService;
        $this->validator = $offlineOrderValidator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $keywords = $request->get('keywords', '');
        $status = $request->get('status', '');
        $agency_id = $request->get('agency_id');
        $page = $request->get('page', 1);
        $page_size = $request->get('page_size', 1);

        $list = $this->offlineOrderService->getOrderList($keywords, $status, $agency_id, $page_size);
        if ($request->input('is_export')) {
            return Excel::download(new OfflineOrderExportV2($list), '线下订单.xlsx');
        }
        return $this->success('ok', $list);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        try {
            //数据验证
            $data = $request->all();
            $this->validator->scene('add')->validate($data);
            //增加user_id
//            $service_user_id = $data['user_id']??0;
//
//            $user_info = User::getMpUser($data['mobile']);
//            if($user_info && $service_user_id != $user_info->id){
//                $user_id = $user_info->id;
//            }else{
//                $user_id = 0;
//            }
            $user_id = $data['user_id'] ?? 0;

            // if ($user_id != 3740)
            //     return $this->failure("功能测试中");

            //创建线下订单
            $offline_order = $this->offlineOrderService->createOfflineOrder($data, $user_id);


            // $group->autoCreateChat($offline_order->order_id);
            //区分群聊
            if ($request->service_type == 1) { // DMA群聊
                //创建群记录
                $chat_id = $data['chat_id'] ?? null;
                Group::create(['name' => $offline_order->name . '服务群', 'order_id' => $offline_order->order_id, 'chat_id' => $chat_id]);
                $this->offlineOrderService->insertRoleData($chat_id, $offline_order->order_id);
                $group = new Group();
                $group_name = $offline_order->name . "服务群";
                $announcement = "😊 本群是您的专属健康服务群

👏 让我们一起携手创造快乐温馨的学习氛围，祝福您在此有一个美好的健康生活之旅

【请勿讨论政治、宗教或发广告】";
                $group->autoCreateChatV2($offline_order->order_id, $group_name, $request->service_type, $announcement);
            } else if ($request->service_type == 3) { //MINI DMA群聊
                //创建群记录
                $chat_id = $data['chat_id'] ?? null;
                Group::create(['name' => $offline_order->name . '服务群', 'order_id' => $offline_order->order_id, 'chat_id' => $chat_id]);
                $this->offlineOrderService->insertRoleData($chat_id, $offline_order->order_id);
                $group = new Group();
                $group_name = $offline_order->name . "服务群【Mini版】";
                $announcement = "【友福同享】欢迎加入DMA服务群【Mini版】!

·本群用于教练指导您的健康管理服务，请勿讨论政治、宗教或发布外部广告。

·服务团队将陆续进群为您提供支持，祝您健康之旅顺利! 🌹🌹";

                $group->autoCreateChatV2($offline_order->order_id, $group_name, $request->service_type, $announcement);
            } else if ($request->service_type == 2) { // 双证群
//                 $group_name = $offline_order->name . "双证咨询服务群";
//                 $announcement = "😊 本群是您的双证咨询服务群

                // 👏 让我们一起携手创造快乐温馨的学习氛围，祝福您在此有一个美好的健康生活之旅

                // 【请勿讨论政治、宗教或发广告】";
//                 $group->autoCreateChatV2($offline_order->order_id, $group_name, $request->service_type, $announcement);

                // 创建双证群
                $this->createCertGroup($offline_order);
            }

            if ($request->service_type == 1 || $request->service_type == 3) {
                // 是否自动拉人入群
                $group = Group::where("order_id", $offline_order->order_id)->first();
                if ($request->auth_join && $request->service_type != 2) {
                    $offlineService = new OfflineOrderService();
                    $offlineService->AutoServiceJoinGroup($group->im_chat_id, $group->id, $group->order_id, $user_id);
                    DmaProcessLog::addUserProcessLog($user_id, $offline_order->order_id ?? 0, 1, "add_server_to_group", "行政已拉服务人员入群(自动分配)", auth()->user()->id, 4);
                }
                // 缴费后自动发送线上
                if (isset($data["check_pay_status"]) && $data["check_pay_status"] == 1) {
                    $owner_accid_id = make_wangyiyun_accid($group->owner_id);
                    $ope = \App\Services\ChatService::MSG_GROUP_OPE;
                    // 自动标记线上合同并且发送合同信息
                    $type = \App\Services\ChatService::MSG_TYPE_CUSTOM;
                    $body = ChatService::getIdCardMessageBody($group->order_id);
                    ChatService::sendImMessage($owner_accid_id, $ope, $group->im_chat_id, $type, $body);

                    $message = "需要您点击上方链接，完成线上合约签署，谢谢您的配合";
                    $type = \App\Services\ChatService::MSG_TYPE_TEXT;
                    $body = ChatService::getTextBody($message);
                    ChatService::sendImMessage($owner_accid_id, $ope, $group->im_chat_id, $type, $body);

                    // 确认已缴费流程
                    DmaProcessLog::addUserProcessLog($user_id, $offline_order->order_id ?? 0, 1, "admin_check_pay_status", "行政确认用户已缴费", auth()->user()->id, 4);



                }
                // 创建双证群
                $this->createCertGroup($offline_order);
                //操作记录
                OperationLoggedEvent::dispatch("创建了虚拟订单: $offline_order->id ,主订单为 $offline_order->order_id");
                DmaProcessLog::addUserProcessLog($user_id, $offline_order->order_id ?? 0, 1, "create_group", "已自动建立群聊", auth()->user()->id, 4);
                DmaProcessLog::addUserProcessLog($user_id, $offline_order->order_id ?? 0, 1, "send_group_notice", "系统已发送群公告", auth()->user()->id, 4);

                // 待办事项
                $theme = "请确认用户[" . $offline_order->name . "]需签署的合同类型(线上/线下)";
                TaskService::AddTask(0, 0, $theme, [8]);
            }


            return $this->success('ok');
        } catch (\Exception | ValidationException $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 创建双证群
     * @param mixed $offline_order 线下订单
     * @return void
     */
    public function createCertGroup($offline_order)
    {
        // 35600订单可创建双证群
        $priceList = [25800, 36500, 5800];
        if (!in_array($offline_order->price, $priceList))
            return;

        $order = Order::where('id', $offline_order->order_id)->first();

        // 创建群聊
        $group = new Group();

        $chatName = $offline_order->name . "双证咨询服务群";
        $orderId = 0;
        if ($offline_order->price == 5800) {
            $orderId = $order->id;
        }
        $group->autoCreateCertChat($order->user_id, $chatName, $orderId);
        return;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $order_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function update(Request $request, $order_id)
    {
        try {
            //数据验证
            $data = $request->only(['name', 'mobile', 'pay_type', 'bank_name', 'bank_num', 'agency_id', "price"], );
            $this->validator->scene('edit')->validate($data);
            //修改线下订单
            $offline_order = $this->offlineOrderService->updateOfflineOrder($data, $order_id);

            //操作记录
            OperationLoggedEvent::dispatch("更新了虚拟订单: $offline_order->id ,主订单为 $offline_order->order_id");

            return $this->success('ok');
        } catch (ModelNotFoundException) {
            return $this->jsonResponse(1, '未找到对应订单');
        } catch (\Exception | ValidationException $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
