<?php

namespace App\Http\Controllers\App;

use App\Facades\CommonService;
use App\Facades\TaskService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
//use App\Jobs\SendTemplateNotice;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\Order;
use App\Models\OrderOperateLog;
use App\Models\Service;
use App\Models\ServiceRole;
use App\Services\ChatService;
use App\Validators\OfflineOrderValidator;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    use ResponseJson;

    public function payOrder(Request $request, $service_id)
    {

        $service = Service::find($service_id);
        $user = auth()->user();
        if ($user->payOrders()->count())
            return $this->failure("该服务暂不支持多次购买");
        $order_arr = [
            'user_id' => $user->id,
            'price' => $service->price,
            'type' => 'SERVICE',
            'type_id' => $service_id,
            'pay_status' => 'UNPAID',
            'trade_no' => CommonService::getTradeNO(),
            'name' => $request->input('name'),
            'mobile' => $request->input('mobile'),
            'desc' => $service->title,
            'is_hook' => 0,
        ];
        if ($service->price) {
            $callback = config('app.url') . '/api/notify/orders/' . $order_arr['trade_no'];
            $config = WechatService::mpPay($order_arr['trade_no'], $user->wechat->openid, $service->price, $service->title, $callback);
        } else {
            $order_arr['pay_status'] = 'PAID';
            $order_arr['is_hook'] = 1;
        }
        $order = Order::create($order_arr);
        $order->config = $config;
        //todo 通知
        if ($order->price == 0)
            $this->sendNotice($order);
        return $this->success('ok', $order);
    }

    public function notifyOrder($trade_no)
    {
        $order = Order::where('trade_no', $trade_no)->first();
        if (empty($order))
            throw new \Exception("订单不存在");
        if ($order->is_hook)
            return true;
        //查询订单
//        $result = false;
        $result = WechatService::mpPaid($trade_no);
        if (empty($result)) {//成功
            DB::beginTransaction();
            Order::where("id", $order->id)->update(['pay_status' => 'PAID', 'is_hook' => 1]);
            //生成聊天组
            $order->group()->create(['name' => $order->user->name . '服务群']);
            GroupUser::firstOrCreate(['user_id' => $order->user_id, 'group_id' => $order->group->id]);
            DB::commit();
            //订阅通知通知
            $this->sendNotice($order);

        } else {//失败
            Order::where("id", $order->id)->update(['err_msg' => $result]);
        }
        return true;
    }

    public function sendNotice($order)
    {
        $params = [
            'touser' => $order->user->openid,
            'template_id' => config('wechat.sub_tpls.pay_success'),
            'page' => '/pages/users/myOrder',
            'miniprogram_state' => 'formal',
            "lang" => "zh_CN",
            'data' => [
                'thing1' => ["value" => $order->desc],
                'character_string3' => ["value" => $order->trade_no],
                'time2' => ["value" => $order->created_at->toDatetimeString()],
                'thing4' => ["value" => '点击查看详情']
            ]
        ];
        //        SendTemplateNotice::dispatch($params)->onQueue('health');
    }

    public function orders()
    {
        $orders = Order::with('service:id,title,pic,subtitle')->where('user_id', auth()->id())->where('pay_status', 'PAID')->orderByDesc('id')->simplePaginate();
        foreach ($orders as $order) {
            $order->service->title = $order->desc;
        }

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

    public function order(Request $request, $order_id)
    {
        $order = Order::find($order_id);
        $order->service;
        $order->service->title = $order->desc;
        $asginContract = $order->asginContract;
        if ($order->asginSigner) {
            $asginContract->preview_url = $order->asginSigner->user_sign_url;
        }
        unset($order->asginContract);
        $order->asginContract = $asginContract;
        return $this->success('OK', $order);
    }

    public function bindUser(Request $request, $order_id)
    {
        try {
            $data = $request->all();
            //数据验证
            $validator = new OfflineOrderValidator();
            $validator->scene('bindUser')->validate($data);

            //获取订单信息
            $order = Order::query()->find($order_id);

            if ($order->user_id != 0) {
                throw new \Exception('无法绑定。此订单此前已被绑定。');
            }

            if ($order->mobile != $data['mobile']) {
                throw new \Exception('手机号不匹配');
            }

            if ($order->mobile != $data['name']) {
                throw new \Exception('姓名不匹配');
            }

            //绑定
            $user = auth()->user();
            $order->user_id = $user->id;
            $order->save();

            return $this->success('绑定成功');
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function getOrderLog(Request $request)
    {
        try {
            $order = Order::where('user_id', auth()->id())->orderByDesc('id')->first();
            $list = OrderOperateLog::where('order_id', $order->id)->orderBy('created_at', 'desc')->get();
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function updateServerStatus(Request $request)
    {
        $user = auth()->user();
        $service_status = $request->input('service_status');
        $delivery_img = $request->input("delivery_img");
        $orderModel = new Order();
        $orderModel->updateServerStatus($user, $service_status, $delivery_img);

        //确认收货才发送消息
        if ($service_status == "FINISHED") {
            $order = Order::getPayOrder($user->id);
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '确认收货', "用户[" . ($order->name ?? "") . ']已确认收货,请客服设置餐单', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', config('app.url') . '/work/#/h5/appEditUserMenu', [ServiceRole::CUSTOMER]);
            $chatService->sendImMsgUserToUser($order->id, '系统通知', '请所有服务人员与用户[' . $order->name . ']进行第一次视频通话', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);

            // 待办事项-主教练
            $theme = "请邀请所有服务人员进行「用户" . $order->name . "」服务的第一次「视频通话」，并将相关视频链接转发给“友福服务”";
            TaskService::AddTask(0, 0, $theme, [1], $order->id);

            // 待办事项-客服
            $theme = "请标记「用户" . $order->name . "」的方案开始并确认方案开始时间";
            if (empty($order->status)) {
                TaskService::AddTask(0, 0, $theme, [3], $order->id);
            }

            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "user_take_delivery", "用户确认收货", $order->user_id ?? 0, 0);
        }
        return $this->success("ok");
    }
}
