<?php

namespace App\Services;

use App\Facades\CommonService;
use App\Facades\WechatService;
use App\Http\Controllers\H5\OrderController;
use App\Jobs\UnfreezeCommission;
use App\Models\DmaServiceUserRole;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\OfflineOrder;
use App\Models\Order;
use App\Models\PartnerCommission;
use App\Models\PartnerWallet;
use App\Models\ServiceOrderStatus;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\ServiceUserBindRole;
use App\Models\TeslaRanking;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\DB;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Support\Facades\Log;

class OfflineOrderService
{
    public function createOfflineOrder(array $data, $user_id = 0)
    {
        // 是否是隐私用户
        if (isset($data["is_privacy"])) {
            User::where("id", $user_id)->update(["is_privacy" => $data["is_privacy"]]);
        }

        // 创建订单
        $tradeNo = CommonService::getTradeNO();
        $order = Order::create([
            'user_id' => $user_id,
            'type' => 'SERVICE',
            'type_id' => 1,
            'price' => $data['price'],
            'pay_status' => 'PAID',
            'trade_no' => $tradeNo,
            'name' => $data['name'],
            'area_code' => $data['area_code'] ?? 86,
            "status" => Order::NOTSTART_STATUS,
            "service_status" => "NOINFO",
            //            'mobile' => aesDecryptCBC($data['mobile']),
            'mobile' => ctype_digit($data['mobile']) ? $data['mobile'] : aesDecryptCBC($data['mobile']),
            'agency_id' => $data['agency_id'] ?? null,
            'desc' => '友福健康服务',
            'is_hook' => 1,
            "payment_id" => $data["payment_id"] ?? 1,
            "check_pay_status" => $data["check_pay_status"] ?? 0,
            "check_pay_img" => $data["check_pay_img"] ?? null,
            "sign_type" => (isset($data["check_pay_status"]) && $data["check_pay_status"] == 1) ? 1 : 0,
            "is_tesla" => $data["is_tesla"] ?? 0,
            "filiale_id" => $data["filiale_id"] ?? null,
        ]);

        $contract_no = 0;
        if (isset($data['contract_no']) && !empty($data['contract_no'])) {
            $contract_no = $data['contract_no'];
        }
        if ($contract_no == 0 && !empty($order->mobile)) {
            $contract_no = $order->mobile;
        }
        // 创建线下订单
        $offline_order = OfflineOrder::create([
            'order_id' => $order->id,
            'name' => $order->name,
            'area_code' => $data['area_code'] ?? 86,
            'mobile' => $order->mobile,
            'contract_no' => $contract_no,
            'pay_type' => $data['pay_type'] ?? 1,
            'bank_name' => $data['bank_name'] ?? null,
            'bank_num' => $data['bank_num'] ?? null,
            'agency_id' => $data['agency_id'] ?? null,
            'price' => $order->price ?? 0,
            "operate_user_id" => auth()->id(),
            "operate_user_name" => auth()->user()->name,
        ]);



        if (config('app.env') == 'production') {
            //生成用户绑定二维码
            $scene = 'order_id=' . $order->id;
            $page = 'pages/offlineOrder/bindUser';
            $qrcode = WechatService::getMPQrcode($scene, $page);
            //更新线下订单信息
            $offline_order->bind_qrcode = $qrcode;
            $offline_order->save();
        }

        DB::commit();
        return $offline_order;

    }

    public function updateTeslaRanking($order)
    {
        $orderId = null;
        $finishedAt = null;
        if (empty($order->referrer)) {
            return;
        }
        $totalNum = Order::where("referrer_id", $order->referrer)->where("is_tesla", 1)->count();
        if (empty($totalNum)) {
            TeslaRanking::where("user_id", $order->referrer)->delete();
            return;
        }
        if ($totalNum >= 10) {
            $orderList = Order::where("referrer_id", $order->referrer)->where("is_tesla", 1)->orderBy("id", "asc")->get();
            if (count($orderList) == 0) {
                $orderId = $orderList[9]->id;
                $finishedAt = $orderList[9]->finishedAt;
            }
        }

        $ranking = TeslaRanking::where("user_id", $order->referrer)->first();
        if (empty($ranking)) {
            TeslaRanking::create([
                "user_id" => $order->referrer,
                "total_num" => $totalNum,
                "finished_at" => $finishedAt,
                "finished_order_id" => $orderId
            ]);
        } else {
            TeslaRanking::where("user_id", $order->referrer)->update([
                "total_num" => $totalNum,
                "finished_at" => $finishedAt,
                "finished_order_id" => $orderId
            ]);
        }
        return;
    }

    public function getOrderList($keywords = '', $status = '', $agency_id = '', $page_size = 15)
    {
        $orders = OfflineOrder::with([
            'main_order' => function ($order) {
                $order->with([
                    'service_role' => function ($serviceRole) {
                        $serviceRole->with(['serviceUser:user_id,name,mobile'])->select('order_id', 'role_id', 'user_id');
                    }
                ]);
            },
            "main_order.user:id,name,mobile,avatar,is_privacy",
            'agency:id,name,mobile',
            'order_commission' => function ($commission) {
                $commission->with(['service_user:user_id,name,mobile'])->select('id', 'order_id', 'role', 'user_id');
            },
            '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'
        ])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where(function ($query) use ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%')->orWhere('mobile', 'like', '%' . $keywords . '%');
                });
            })
            ->when(!empty($status), function ($query) use ($status) {
                $query->whereHas('main_order', function ($query) use ($status) {
                    $query->where('status', $status);
                });
            })
            //            ->when($agency_id,function ($query) use ($agency_id) {
//                $query->where('agency_id',$agency_id);
//            })
            ->when($agency_id, function ($query) use ($agency_id) {
                return $query->whereHas('agreement.quotaInfo', function ($q) use ($agency_id) {
                    $q->where('agency_id', $agency_id);
                });
            })
            ->orderByDesc('id');
        $is_export = request()->input('is_export');
        if ($is_export) {
            $orders = $orders->get();
            return $orders;
        }
        $orders = $orders->paginate($page_size);
        return $orders;
    }

    /**
     * 更新线下订单
     * @param array $data
     * @return void
     * @throws \Exception
     */
    public function updateOfflineOrder(array $data, $order_id)
    {
        //获取订单状态
        $offline_order = OfflineOrder::with('main_order')->findOrFail($order_id);
        if ($offline_order->main_order->status != 'NOTSTART')
            throw new \Exception('订单已开始服务,不可修改');

        // 计算佣金
//        $commission_type = $data['subcommission_type'];
//        $commission_val  = $data['subcommission_val'];
//        $data['commission_amount'] = $this->getCommissionAmount($commission_type,$commission_val,$offline_order->price);

        try {
            DB::beginTransaction();
            //更新线下订单
            $offline_order->update($data);
            //更新对应主订单
            $order_data = [
                'name' => $offline_order->name,
                'mobile' => $offline_order->mobile,
                'price' => $offline_order->price,
                'agency_id' => $offline_order->agency_id,
                "is_tesla" => $data["is_tesla"] ?? 0,
                "filiale_id" => $data["filiale_id"] ?? null,
            ];

            $offline_order->main_order()->update($order_data);
            DB::commit();

            return $offline_order;
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }

    private function getCommissionAmount($type, $val, $price)
    {
        // 计算佣金
        if ($type === 1) {
            // 比例分佣
            $commission_percentage = bcdiv($val, 100, 4);
            $commission_amount = bcmul($price, $commission_percentage, 2);
        } else {
            // 固定金额
            $commission_amount = $val;
        }
        return $commission_amount;
    }

    /**
     * 查看是否存在角色数据,存在则绑定角色
     * @param $chat_id
     * @param $order_id
     */
    public function insertRoleData($chat_id, $order_id, $service_user_id = null)
    {
        if ($service_user_id) {
            $service_user = ServiceUser::where("user_id", $service_user_id)->first();
        } else {
            //查看是否绑定企业微信
            $work_wechat_user = session('work_wechat_user');
            $work_user_id = $work_wechat_user['raw']['userid'] ?? 0;
            $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
        }
        if ($service_user) {
            $roleIds = ServiceUserBindRole::where('chat_id', $chat_id)
                ->where('user_id', $service_user->user_id)
                ->select('role_id')
                ->get()->toArray();
            //如果存在数据,则绑定订单
            if ($roleIds) {
                foreach ($roleIds as $value) {
                    $ServiceRoleOrder = new ServiceRoleOrder();
                    $ServiceRoleUser = new ServiceRoleUser();
                    $ServiceRoleOrder->insertRoleOrder($value['role_id'], $service_user, $order_id);
                    $ServiceRoleUser->insertRoleUserData($service_user, $value['role_id']);
                }
            }
        }
    }

    public function AutoServiceJoinGroup($imChatId, $groupId, $orderId, $userId)
    {
        Log::info("自动分配用户订单角色");
        // 主教练id
        $mainCoachRoleId = 1;
        $mainCoachUserId = $this->getOrderService($userId, $mainCoachRoleId);
        Log::info("主教练用户id：" . $mainCoachUserId);
        if ($mainCoachUserId) {
            $this->joinServiceGroup($imChatId, $groupId, $orderId, $mainCoachRoleId, $mainCoachUserId);
        }

        // 副教练
        $coachRoleId = 2;
        $coachUserId = $this->getOrderService($userId, $coachRoleId);
        Log::info("副教练用户id：" . $coachUserId);
        if ($coachUserId) {
            $this->joinServiceGroup($imChatId, $groupId, $orderId, $coachRoleId, $coachUserId);
        }

        // 客服
        $customerRoleId = 3;
        $customerUserId = $this->getOrderService($userId, $customerRoleId);
        Log::info("客服用户id：" . $customerUserId);
        if ($customerUserId) {
            $this->joinServiceGroup($imChatId, $groupId, $orderId, $customerRoleId, $customerUserId);
        }
    }

    public function joinServiceGroup($imChatId, $groupId, $orderId, $roleId, $userId)
    {
        DB::beginTransaction();
        try {
            // 订单绑定服务人员
            $roleOrder = ServiceRoleOrder::where(["order_id" => $orderId, "user_id" => $userId, "role_id" => $roleId])->first();
            if (empty($roleOrder)) {
                ServiceRoleOrder::create([
                    "order_id" => $orderId,
                    "user_id" => $userId,
                    "role_id" => $roleId
                ]);
            }

            // 服务人员加入群聊
            $groupUser = GroupUser::where(["user_id" => $userId, "group_id" => $groupId])->first();
            if (empty($groupUser)) {
                $roleName = ServiceRole::where("id", $roleId)->value("name");
                GroupUser::create([
                    "user_id" => $userId,
                    "group_id" => $groupId,
                    "status" => 0,
                    "type" => 0,
                    "role_id" => $roleId,
                    "role_name" => $roleName,
                ]);
            }

            $group_info = Group::where('id', $groupId)->first();
            $owner_ac_cid = make_wangyiyun_accid($group_info->owner_id);
            // 加入im群聊
            $user_accid = make_wangyiyun_accid($userId);
            $imTeam = new Team(config('chat.im.app_id'), appSecrt: config('chat.im.app_secret'));
            $imTeam->add($imChatId, $owner_ac_cid, [$user_accid], 0, '邀请进群');

            // 修改群角色
            $map = [];
            $map['role'] = [$roleId];
            $options = ['custom' => json_encode($map)];
            $imTeam->updateTeamNick($imChatId, $owner_ac_cid, $user_accid, $options);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
        }
    }

    /**
     * 获取服务人员id(轮训)
     * @param mixed $userId
     * @param mixed $roleId
     * @return void
     */
    public function getOrderService($userId, $roleId): int
    {
        if ($userId == 3740 || $userId == 6) // 测试用户
            return 1;
        // $userIds = [];
        // switch ($roleId) {
        //     case 1:
        //         if ($userId == 3740 || $userId == 6)
        //             return 1;
        //         // $userIds = [218, 178, 175, 176];
        //         $userIds = [218, 175, 176];
        //         // $userIds = [153, 152, 11043, 1]; // 测试
        //         break;
        //     case 3:
        //         if ($userId == 3740 || $userId == 6)
        //             return 7;
        //         $userIds = [181, 177, 184];
        //         // $userIds = [7, 3306]; // 测试
        //         break;
        // }

        $userIds = DmaServiceUserRole::where("role", $roleId)->where("status", 1)->pluck("user_id")->toArray();

        $userIds = ServiceOrderStatus::whereIn("user_id", $userIds)->where("order_status", 1)->orderByDesc("id")->pluck("user_id")->toArray();
        $serviceUserId = $this->getLastServiceUserId($roleId, $userIds);
        return $serviceUserId;
    }

    public function getLastServiceUserId($roleId, $userIds): int
    {
        $serviceUserId = 0;
        if (!in_array($roleId, [1, 2, 3]))
            return $serviceUserId;

        if (count($userIds) == 0)
            return $serviceUserId;

        // 上一个订单对应服务人员id
        $serviceRoleOrder = ServiceRoleOrder::where("role_id", $roleId)->whereIn("user_id", $userIds)->orderByDesc("id")->first();
        if (!$serviceRoleOrder)
            return $userIds[0];

        $serviceUserId = $this->findIndex($userIds, $serviceRoleOrder->user_id);
        return $serviceUserId;
    }

    public function findIndex($userIds, $userId): int
    {
        Log::info("查询服务人员id");
        Log::info(json_encode($userIds));
        Log::info($userId);
        if (!in_array($userId, $userIds))
            return $userIds[0];
        foreach ($userIds as $key => $item) {
            if ($item == $userId) {
                if ($key == count($userIds) - 1)
                    return $userIds[0];
                return $userIds[$key + 1];
            }
        }
        return $userIds[0];
    }
}
