<?php

namespace App\Http\Controllers;
use App\Models\China;
use App\Models\DailyStep;
use App\Models\GroupUser;
use App\Models\HealthLevel;
use App\Models\MedicalReport;
use App\Models\NewFatLog;
use App\Models\OfflineOrder;
use App\Models\Order;
use App\Models\ServiceOrderStatus;
use App\Models\ServiceRoleOrder;
use App\Models\UserInfo;
use App\Models\Version;
use App\Services\FatService;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Support\Facades\Redis;
use App\Services\ImService;

use App\Exports\TestActivityMembersExport;
use App\Exports\TestLottoCodeList;
use App\Exports\TestOrderUsersExport;
use App\Exports\TestResidueUsersExport;
use App\Facades\CommonService;
use App\Facades\UserService;
use App\Facades\WechatService;
use App\Imports\ActivityOrdersImport;
use App\Models\Activity;
use App\Models\ActivityIntroduceLog;
use App\Models\ActivityMember;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderLog;
use App\Models\AgentOrder;
use App\Models\AgentShop;
use App\Models\AgentUser;
use App\Models\AgentUserLog;
use App\Models\BandDataTime;
use App\Models\BandSleep;
use App\Models\Collaborator;
use App\Models\DmaServiceUserRole;
use App\Models\Food;
use App\Models\Group;
use App\Models\GroupMessage;
use App\Models\Lottery;
use App\Models\LotteryMember;
use App\Models\LottoCode;
use App\Models\Partner;
use App\Models\RegularActivity;
use App\Models\S2ShopExpress;
use App\Models\S2ShopOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\Shop;
use App\Models\SplitModel;
use App\Models\User;
use App\Models\WangYiYun;
use App\Models\Wechat;
use cccdl\yunxin_sdk\Im\User as ImUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use GuzzleHttp\Client;
use App\Exports\TestAugMemberExport;
use App\Imports\ShopOrderImport;
use App\Imports\CustomerVisitImport;
use PhpParser\Node\Stmt\GroupUse;
class TestController extends Controller
{
    public function testTransfer(Request $request, $name)
    {
        $res = $this->$name();
        return $res;
    }

    public function agentOrderH5()
    {
        $orders = AgentOrder::whereDoesntHave("user.officialWechat")->paid()->get();
        foreach ($orders as $order) {
            $user = User::whereHas("officialWechat")->where("mobile", $order->mobile)->first();
            if (empty($user)) {
                //                Log::info("渣酒订单：{$order->id}  姓名：{$order->name}  手机号：{$order->mobile} 没有找到H5用户");
            } else {
                Log::info("渣酒订单：{$order->id}  姓名：{$order->name}  手机号：{$order->mobile} 用户id：{$order->user_id}  转 {$user->id}");
                AgentOrder::where('id', $order->id)->update(["user_id" => $user->id]);
            }
        }
    }

    public function activityH5()
    {
        $orders = ActivityOrder::whereDoesntHave("user.officialWechat")->paid()->get();
        foreach ($orders as $order) {
            $user = User::whereHas("officialWechat")->where("mobile", $order->mobile)->first();
            if (empty($user)) {
                //                Log::info("活动订单：{$order->id}  姓名：{$order->name}  手机号：{$order->mobile} 没有找到H5用户");
            } else {
                Log::info("活动订单：{$order->id}  姓名：{$order->name}  手机号：{$order->mobile} 用户id：{$order->user_id}  转 {$user->id}");
                ActivityOrder::where('id', $order->id)->update(["user_id" => $user->id]);
            }
        }
    }

    /**
     * 导入批发商订单
     */
    public function testAgentOrder()
    {
        $orders = DB::connection("no_prefix_mysql")->table('oa_agent_goods_order as go')
            ->leftJoin('oa_agent_user as au', 'au.id', '=', 'go.user_id')
            ->where('go.pay_status', 'PAID')
            ->get();
        foreach ($orders as $order) {
            DB::beginTransaction();
            //用户
            $user_id = Wechat::where('openid', $order->openid)->value('user_id');
            if (!$user_id) {
                $user_id = User::where("mobile", $order->mobile)->value('id');
            }
            if (empty($user_id)) {
                $user = User::create(['name' => $order->name, 'mobile' => $order->mobile]);
                Wechat::create(['user_id' => $user->id, 'type' => 'official', 'openid' => $order->openid]);
                $user_id = $user->id;
            }
            $shop = Shop::find(1);
            $sku_arr = $shop->shopAgent->sku;
            $sku = collect($sku_arr)->where('sku_id', 1)->first();
            $shop_info = ["id" => $shop->id, 'title' => $shop->title, 'pic' => $shop->icon, 'sku' => $sku];
            //订单
            $agent_order = AgentOrder::updateOrCreate(['trade_no' => $order->trade_no], [
                'user_id' => $user_id,
                'name' => $order->name,
                'mobile' => $order->mobile,
                'origin_price' => $order->origin_price,
                'price' => $order->price,
                'is_online' => 1,
                'pay_type' => 'wechat',
                'pay_status' => 'PAID',
                'shop_id' => 1,
                'sku_id' => 1,
                'shop_info' => $shop_info,
                'num' => $order->num,
                'created_at' => date("Y-m-d H:i:s", $order->created_at),
                'updated_at' => date("Y-m-d H:i:s", $order->updated_at)
            ]);
            //酒码
            $codes = DB::connection("no_prefix_mysql")->table('oa_agent_code')->where('trade_no', $order->trade_no)->get();
            foreach ($codes as $code) {
                LottoCode::updateOrCreate(['code' => $code->code], ['user_id' => $user_id, 'order_id' => $agent_order->id]);
            }
            //批发商
            AgentUser::changeLevel($user_id, AgentUser::AgentLevelBeing, "同步oa渣酒订单");
            DB::commit();
        }
        return $this->success('ok');
    }

    public function importActivityOrders()
    {
        $file = storage_path("orders.xlsx");
        Excel::import(new ActivityOrdersImport(), $file);
        return $this->success('ok');
    }

    public function syncLottoCode()
    {
        AgentOrder::paid()->where('shop_id', 3)->chunk(100, function ($orders) {
            foreach ($orders as $order) {
                //抽奖码
                $order->lottoCode()->update(['user_id' => $order->user_id]);
                $num = $order->num;
                //已存在的抽奖码
                $count = $order->lottoCode()->count();
                if ($num - $count <= 0)
                    continue;
                for ($index = 0; $index < ($num - $count); $index++) {
                    $code = time() . CommonService::random(6, 1) . strtoupper(CommonService::random(1));
                    //生成抽奖码
                    $order->lottoCode()->create(['user_id' => $order->user_id, 'code' => $code]);
                }
            }
        });
    }

    public function syncActivityAgentUser()
    {
        $orders = ActivityOrder::whereDoesntHave("agentUser", function ($sql) {
            $sql->where("level", '>', 0);
        })->where('is_pay', 1)->whereIn('activity_id', [17, 18])->get();
        foreach ($orders as $order) {
            AgentUser::changeLevel($order->user_id, 2, "同步购买活动门票");
        }
    }

    public function syncShopAgentUser()
    {
        $orders = AgentOrder::whereDoesntHave("agentUser", function ($sql) {
            $sql->where("level", 1);
        })->where('pay_status', "PAID")->where('shop_id', 3)->get();
        foreach ($orders as $order) {
            AgentUser::changeLevel($order->user_id, 2, "同步购买渣酒");
        }
    }

    public function syncAgentStaff()
    {
        $collaborators = Collaborator::where('type', Collaborator::TYPE_FULL_TIME)->where('status', 1)->get();
        foreach ($collaborators as $collaborator) {
            $agent_user = AgentUser::where("user_id", $collaborator->user_id)->first();
            if (empty($agent_user) || $agent_user->level == 0) {
                AgentUser::changeLevel($collaborator->user_id, AgentUser::AgentStaff, "同步全职合作商为员工");
            }
        }
    }

    public function syncAgentUser()
    {
        $logs = AgentUserLog::where("before_level", ">", 0)->where("desc", "同步全职合作商为员工")->get();
        foreach ($logs as $log) {
            AgentUser::where('user_id', $log->user_id)->update(['level' => $log->before_level]);
        }
    }

    public function syncFoodShop()
    {
        $foods = Food::whereHas("shop")->get();
        foreach ($foods as $food) {
            $sku = [
                ["sku_id" => 1, "name" => $food->name, 'stock' => $food->stock, 'price' => $food->price, 'agent_price' => $food->price, 'ready_agent_price' => $food->price, 'staff_price' => $food->price, "ship_num" => 0, "ship_price" => 0, "ship_each_price" => 0, "ship_max_price" => 0],
            ];
            Shop::where('id', $food->shop_id)->update(['sku' => $sku]);
        }
    }

    public function syncLotteryQrcode()
    {
        $lotteries = Lottery::whereNull("new_qrcode")->get();
        foreach ($lotteries as $lottery) {
            $new_path = config('app.url') . '/award/#/newLuckyDraw?id=' . $lottery->id;
            $new_qrcode = CommonService::makeQrcode($new_path);
            $lottery->update(['new_path' => $new_path, 'new_qrcode' => $new_qrcode]);
        }
    }

    /**
     * 渣酒抽奖码到指定抽奖池
     */
    public function syncWineLottoMember()
    {
        $shop_id = ((config('app.env') == "production") ? AgentShop::WINEID : AgentShop::ALPHA_WINEID);
        AgentOrder::with("lottoCodes")->whereIn("pay_status", [AgentOrder::PAIDSTATUS, AgentOrder::SENDSTATUS, AgentOrder::SIGNEDSTATUS])->where("shop_id", $shop_id)->chunk(100, function ($agent_orders) {
            foreach ($agent_orders as $agent_order) {
                $lottery_id = (config('app.env') == "production") ? AgentShop::LOTTERYID : AgentShop::ALPHA_LOTTERYID;
                $lottoCodes = $agent_order->lottoCodes;
                foreach ($lottoCodes as $lottoCode) {
                    LotteryMember::updateOrCreate(['user_id' => $agent_order->user_id, 'code' => $lottoCode->code], ['lottery_id' => $lottery_id, 'name' => $agent_order->name, 'mobile' => $agent_order->mobile]);
                }
            }
        });
    }

    /**
     * 手环抽奖码到指定抽奖池
     */
    public function syncBandLottoMember()
    {
        $shop_id = ((config('app.env') == "production") ? AgentShop::BANDID : AgentShop::ALPHA_BANDID);
        AgentOrder::with("lottoCodes")->whereIn("pay_status", [AgentOrder::PAIDSTATUS, AgentOrder::SENDSTATUS, AgentOrder::SIGNEDSTATUS])->where("shop_id", $shop_id)->chunk(100, function ($agent_orders) {
            foreach ($agent_orders as $agent_order) {
                $lottery_id = (config('app.env') == "production") ? AgentShop::BAND_LOTTERY_ID : AgentShop::ALPHA_BAND_LOTTERY_ID;
                $lottoCodes = $agent_order->lottoCodes;
                foreach ($lottoCodes as $lottoCode) {
                    LotteryMember::updateOrCreate(['user_id' => $agent_order->user_id, 'code' => $lottoCode->code], ['lottery_id' => $lottery_id, 'name' => $agent_order->name, 'mobile' => $agent_order->mobile]);
                }
            }
        });
    }

    public function syncActivityLottoMember()
    {
        $activity_id = ((config('app.env') == "production") ? Activity::ACTIVITY_ID : Activity::ALPHA_ACTIVITY_ID);
        $activity = Activity::find($activity_id);
        ActivityOrder::paid()->residue()->chunk(100, function ($orders) use ($activity) {
            foreach ($orders as $order) {
                $activity->lottery->members()->updateOrCreate(['user_id' => $order->user_id, 'lottery_id' => $activity->lottery->id], ['name' => $order->user->name, 'mobile' => $order->user->mobile]);
            }
        });
    }

    /**
     * 同步含余额用户进入到小会抽奖池
     */
    public function syncRegularActivityLottoMember()
    {
        $activity_id = ((config('app.env') == "production") ? RegularActivity::ACTIVITY_ID : RegularActivity::ALPHA_ACTIVITY_ID);
        $activity = RegularActivity::find($activity_id);
        ActivityOrder::paid()->residue()->chunk(100, function ($orders) use ($activity) {
            foreach ($orders as $order) {
                $activity->lottery->members()->updateOrCreate(['user_id' => $order->user_id, 'lottery_id' => $activity->lottery->id], ['name' => $order->user->name, 'mobile' => $order->user->mobile]);
            }
        });
    }

    public function exportActivityResidueMembers()
    {
        $user_ids = ActivityOrder::paid()->residue()->distinct()->pluck("user_id");
        $data = [];
        foreach ($user_ids as $user_id) {
            $user = User::find($user_id);
            $level = AgentUser::where("user_id", $user_id)->value("level");
            $level_name = AgentUser::agentName($level);
            $amount = ActivityOrder::owner($user_id)->paid()->residue()->sum("residue_amount");
            $data[] = ['name' => $user->name, 'mobile' => $user->mobile, 'level' => $level_name, 'amount' => $amount];
        }
        return Excel::download(new TestResidueUsersExport($data), 'members.xlsx');
    }

    public function testBandOrder()
    {
        $orders = AgentOrder::where('shop_id', 89)->where("pay_status", "UNPAID")->get();

        foreach ($orders as $order) {
            $client = new Client();
            $url = config('app.url') . "/api/h5/agent/order/{$order->trade_no}/callback";
            $response = $client->get($url);
        }
    }

    public function testWineOrder()
    {
        $orders = AgentOrder::where('shop_id', 3)->where("pay_status", "UNPAID")->get();

        foreach ($orders as $order) {
            $client = new Client();
            $url = config('app.url') . "/api/h5/agent/order/{$order->trade_no}/callback";
            $response = $client->get($url);
        }
    }

    public function sycnAgentOrderName()
    {
        $orders = AgentOrder::where('shop_id', 89)->where("pay_status", "PAID")->where('name', "【预定】友福同享智能健康手环(自提)")->get();

        foreach ($orders as $order) {
            Log::info("订单id {$order->id}");
            $user = $order->user;
            $order->update(['name' => $user->name, 'mobile' => $user->mobile]);
            LotteryMember::where('id', 30)->where("user_id", $order->user_id)->update(['name' => $user->name, 'mobile' => $user->mobile]);
        }
    }

    public function syncLotteryMemberName()
    {
        $members = LotteryMember::where('lottery_id', 30)->whereNull('name')->get();
        foreach ($members as $member) {
            $member->update(['name' => $member->user_id, 'mobile' => $member->user_id]);
        }
    }

    public function syncAgentLevelReadyToBeing()
    {
        $agent_users = AgentUser::where("level", 2)->get();
        foreach ($agent_users as $agent_user) {
            AgentUser::changeLevel($agent_user->user_id, AgentUser::AgentLevelBeing, "取消准批发商，转为批发商");
        }
    }

    public function refreshApiJwtToken()
    {
        $user = User::find(6);
        $token = UserService::refreshApiJwtToken($user);
        dd($token);
    }

    /**
     * 第二次大会签到用户列表
     */
    public function exportActivityMembers()
    {
        $members = ActivityMember::with("agentUser")->where("activity_id", 18)->withCount([
            'orders as amount' => function ($sql) {
                $sql->paid()->select(DB::raw("sum(residue_amount) as amount"));
            }
        ])->get();

        return Excel::download(new TestActivityMembersExport($members), "users.xlsx");
    }

    /**
     * 第二次大会非vip用户签到扣除余额
     */
    //    public function decrementAmountActivityMembers()
//    {
//        DB::beginTransaction();
//        $members = ActivityMember::where('activity_id', 18)->where('status', 1)->whereHas('agentUser', function ($sql) {
//            $sql->where('level', "<>", AgentUser::AgentVIP);
//        })->withCount(['orders as amount'=>function($sql) {
//            $sql->paid()->select(DB::raw("sum(residue_amount) as amount"));
//        }])->get();
//        foreach ($members as $member) {
//            Log::info("用户id {$member->user_id} 余额：{$member->amount}");
//            if($member->amount > Activity::SIGN_FEE) {
//                $orders = ActivityOrder::owner($member->user_id)->paid()->residue()->get();
//                //剩余需要退金额
//                $remain = Activity::SIGN_FEE;
//                foreach ($orders as $order) {
//                    if ($remain == 0) break;
//                    if ($order->residue_amount >= $remain) {
//                        $order_amount = $remain;
//                    }else {
//                        $order_amount = $order->residue_amount;
//                    }
//                    ActivityIntroduceLog::create(['order_id'=>$order->id, 'amount'=>$order_amount, 'introduce_order_id'=>$order->id, 'type'=>ActivityIntroduceLog::SIGNINTYPE]);
//                    $log = ActivityOrderLog::addActivityOrderLog($order->user_id,$order->id,-$order_amount, "友福同享批发商大会【第二期】", null, null, ActivityOrderLog::SIGNIN_TYPE);
//                    $order->decrement('residue_amount', $order_amount);
//                    $remain -= $order_amount;
//                }
//            }
//        }
//        DB::commit();
//    }

    public function syncMpUserLevel()
    {
        AgentUser::chunk(100, function ($agent_users) {
            foreach ($agent_users as $agent_user) {
                AgentUser::changeLevel($agent_user->user_id, $agent_user->level, "小程序用户同步批发商身份", true);
            }
        });

    }

    public function testBandDateTime()
    {
        $suffix = SplitModel::getMonthSuffix();
        $band_ids = BandSleep::suffix($suffix)->groupBy("band_id")->pluck('band_id');
        foreach ($band_ids as $band_id) {
            $sleep = BandSleep::suffix($suffix)->where("band_id", $band_id)->orderByDesc('date')->first();
            $date_time = BandDataTime::owner($sleep->user_id)->band($sleep->band_id)->first();
            if ($date_time) {
                BandDataTime::owner($sleep->user_id)->band($sleep->band_id)->update(["sleep_time" => strtotime($sleep->date)]);
            } else {
                BandDataTime::create(['user_id' => $sleep->user_id, 'band_id' => $sleep->band_id, "sleep_time" => strtotime($sleep->date)]);
            }
        }
    }

    public function testDeleteSleepData()
    {
        set_time_limit(0);
        DB::table("band_sleeps_202405")->orderBy("id")->chunk(100, function ($sleeps) {
            foreach ($sleeps as $sleep) {
                $obj = DB::table("band_sleeps_202405_1")
                    ->where('user_id', $sleep->user_id)
                    ->where('band_id', $sleep->band_id)
                    ->where("date", $sleep->date)->first();
                if (empty($obj)) {
                    DB::table("band_sleeps_202405_1")->insert((array) $sleep);
                }
            }

        });

    }

    public function testActivityOrder()
    {
        $orders = ActivityOrder::withCount("signActivities")->withCount("signRegularActivities")
            ->withCount("bandOrders")->withCount("wineOrders")
            ->withCount("winLotteries")
            ->with("signActivities")->with("agentUser")
            ->withCount([
                'orderLogs as sign_amount' => function ($sql) {
                    $sql->where("type", ActivityOrderLog::SIGNIN_TYPE)->select(DB::raw("sum(amount) as sign_amount"));
                }
            ])
            ->withCount([
                'orderLogs as refund_amount' => function ($sql) {
                    $sql->whereIn("type", [ActivityOrderLog::REFUND_TYPE, ActivityOrderLog::NOREFUND_TYPE])->select(DB::raw("sum(amount) as refund_amount"));
                }
            ])
            ->with("signRegularActivities")->with("recommendUser")->where(['amount' => 2200])->where("is_pay", ">", 0)->get();

        return Excel::download(new TestOrderUsersExport($orders), 'orders.xlsx');
    }

    public function testActivityOrder2()
    {
        ActivityOrder::where("is_pay", 1)->where('amount', 2200)->withCount([
            'refunds as refund_amount' => function ($sql) {
                $sql->where("status", 1)->select(DB::raw("sum(amount) as refund_amount"));
            }
        ])->chunk(100, function ($orders) {
            foreach ($orders as $order) {
                if ($order->refund_amount == 2200) {
                    DB::beginTransaction();
                    $log = ActivityOrderLog::where("order_id", $order->id)->where("type", "REFUND")->first();
                    if (empty($log)) {
                        ActivityOrderLog::create([
                            "user_id" => $order->user_id,
                            "order_id" => $order->id,
                            "amount" => -2200,
                            "remark" => "直接退款",
                            "type" => "REFUND",
                        ]);
                    }
                    ActivityOrder::where('id', $order->id)->update(["is_pay" => 2]);

                    DB::commit();
                }
            }
        });
    }

    public function testActivityOrder3()
    {
        $orders = ActivityOrder::withCount("signActivities")->with("signActivities")->with("agentUser")->where(["is_pay" => 1, 'amount' => 2200])->get();
        foreach ($orders as $order) {
            if ($order->agentUser && $order->agentUser->level == AgentUser::AgentVIP) {
                continue;
            }
            //非 vip 根据签到次数扣费
            $log_count = $order->orderLogs()->where("type", ActivityOrderLog::SIGNIN_TYPE)->count();
            $num = $order->sign_activities_count - $log_count;
            if ($num > 0) {
                DB::beginTransaction();
                for ($i = 0; $i < $num; $i++) {
                    ActivityOrderLog::create([
                        "user_id" => $order->user_id,
                        "order_id" => $order->id,
                        "amount" => -200,
                        "remark" => "活动签到",
                        "type" => ActivityOrderLog::SIGNIN_TYPE,
                    ]);
                    ActivityOrder::where("id", $order->id)->decrement("residue_amount", 200);
                }
                DB::commit();
            }
        }
    }

    public function checkUserLottoCode()
    {
        $result = S2ShopOrder::whereIn("sku_id", [3, 86])->whereIn('status', [2, 6])->groupBy("user_id")->selectRaw("user_id, sum(num) as count")->get();
        $arr = [];
        foreach ($result as $res) {
            // 抽奖码数量
            $code_count = LottoCode::where('user_id', $res->user_id)->count();
            // 原有商品数
            $shop_count = $res->count;
            $order_ids = S2ShopOrder::whereIn("sku_id", [3, 86])->whereIn('status', [2, 6])->where('user_id', $res->user_id)->pluck('id')->toArray();
            // 几个订单退款
            $refund_order_count = S2ShopExpress::whereIn('order_id', $order_ids)->where('ship', 3)->where("status", 6)->groupBy("order_id")->count();
            // 用户信息
            $user = User::find($res->user_id);
            $arr[] = ["user" => $user, 'code_count' => $code_count, 'shop_count' => $shop_count, 'refund_order_count' => $refund_order_count];

        }
        return Excel::download(new TestLottoCodeList($arr), 'code.xlsx');
    }

    // 八月抽奖名单
    public function AugMemberExport()
    {
        return Excel::download(new TestAugMemberExport(), "member.xlsx");
    }

    // 八月抽奖池
    public function addAugWinLotteryMember()
    {// VIP 和 批发商有酒订单
        $lottery_id = 52;

        //VIP有酒订单
        $orders = S2ShopOrder::where("sku_id", 3)->whereIn("status", [2, 6])->with("user")->whereHas("agentUser", function ($sql) {
            $sql->where("level", AgentUser::AgentVIP)->orWhere("level", AgentUser::AgentLevelBeing);
        })->whereHas("lottoCode")->get();
        foreach ($orders as $order) {
            $codes = $order->lottoCodes;
            foreach ($codes as $code) {
                LotteryMember::firstOrCreate([
                    "user_id" => $order->user_id,
                    "lottery_id" => $lottery_id,
                    "name" => $order->user->name,
                    "mobile" => $order->user->mobile,
                    "code" => $code->code,
                    "index" => 1
                ]);
            }
        }
    }



    // 八月抽奖池
    public function addAugBandLotteryMember()
    {// VIP 和 批发商有手环订单
        $lottery_id = 53;

        //VIP有酒订单
        $orders = S2ShopOrder::where("sku_id", 86)->whereIn("status", [2, 6])->with("user")->whereHas("agentUser", function ($sql) {
            $sql->where("level", AgentUser::AgentVIP)->orWhere("level", AgentUser::AgentLevelBeing);
        })->whereHas("lottoCode")->get();
        foreach ($orders as $order) {
            $codes = $order->lottoCodes;
            foreach ($codes as $code) {
                LotteryMember::firstOrCreate([
                    "user_id" => $order->user_id,
                    "lottery_id" => $lottery_id,
                    "name" => $order->user->name,
                    "mobile" => $order->user->mobile,
                    "code" => $code->code,
                    "index" => 2
                ]);
            }
        }
    }

    public function syncDmaServiceUserRole()
    {
        $serviceUsers = ServiceUser::with("user")->whereHas("user")->get();
        foreach ($serviceUsers as $serviceUser) {
            Log::info($serviceUser->user_id);
            $role_ids = ServiceRoleUser::where("user_id", $serviceUser->user_id)->where("s_user_id", $serviceUser->id)->pluck("role_id")->toArray();
            if (count($role_ids) > 0) {
                foreach ($role_ids as $role_id) {

                    $userRole = DmaServiceUserRole::where("user_id", $serviceUser->user_id)->where("role", $role_id)->first();
                    if (empty($userRole)) {

                        Log::info($serviceUser->user_id . "----" . $serviceUser->user->mobile);
                        DmaServiceUserRole::create([
                            "user_id" => $serviceUser->user_id,
                            "name" => $serviceUser->user->name,
                            "mobile" => $serviceUser->user->mobile,
                            "avatar" => $serviceUser->user->avatar,
                            "role" => $role_id,
                            "status" => 1,
                            "audit_at" => date("Y-m-d H:i:s")
                        ]);
                    }
                }
            }
        }
        return $this->success("ok");
    }

    public function syncGroupMessageImid()
    {
        GroupMessage::whereNull("im_msg_id")->orWhereNull("msg_timestamp")->chunk(100, function ($messages) {
            foreach ($messages as $message) {
                $im_msg_id = $message->im_msg_id;
                if (empty($message->im_msg_id)) {
                    $im_msg_id = uniqid("uftux_");
                }

                $msg_timestamp = $message->msg_timestamp;
                if (empty($message->msg_timestamp)) {
                    $msg_timestamp = strtotime($message->created_at) * 1000;
                }
                GroupMessage::where("id", $message->id)->update(["im_msg_id" => $im_msg_id, "msg_timestamp" => $msg_timestamp]);
            }
        });
    }

    public function syncGroupLastMsg()
    {
        Group::where("last_msg_id", 0)->chunk(100, function ($groups) {
            foreach ($groups as $group) {
                $last_msg_id = GroupMessage::where('group_id', $group->id)->orderBy("msg_timestamp", "desc")->value("id");
                if ($last_msg_id) {
                    Group::where("id", $group->id)->update(['last_msg_id' => $last_msg_id]);
                }
            }
        });
    }

    // public function updateAddress() {
    //     $redis = Redis::client();
    //     $address = $redis->get('china_address');
    //     $addresses = json_decode($address);
    //     foreach ($addresses as $address) {
    //         // China::where("id", $address->id)->update(["pid"=>0]);
    //         China::create([
    //             "id"=>$address->id,
    //             "name"=>$address->name,
    //             "pid"=>$address->pid,
    //         ]);
    //         foreach($address->city as $city) {
    //             // China::where("id",  $city->id)->update(["pid"=>$city->pid]);
    //             China::create([
    //                 "id"=>$city->id,
    //                 "name"=>$city->name,
    //                 "pid"=>$city->pid,
    //             ]);
    //             foreach($city->county as $country) {
    //                 // China::where("id",  $country->id)->update(["pid"=>$country->pid]);
    //                 China::create([
    //                     "id"=>$country->id,
    //                     "name"=>$country->name,
    //                     "pid"=>$country->pid,
    //                 ]);
    //             }
    //         }
    //     }
    // }

    public function importShopOrder()
    {
        $file = storage_path("shop_order.xlsx");
        Excel::import(new ShopOrderImport(), $file);
        return $this->success("ok");
    }

    public function importCustomerVisit()
    {
        $file = storage_path("visit.xlsx");
        Excel::import(new CustomerVisitImport(), $file);
        return $this->success("ok");
    }

    public function statOrder()
    {
        $exclusiveUserIds = [6, 7, 71, 755, 10676, 8815, 4099, 9013, 12012, 3504, 3740];

        $start_time = request()->input("start_time");
        if (empty($start_time)) {
            $start_time = "2025-01-01";
        }
        $end_time = request()->input("end_time");
        if (empty($end_time)) {
            $end_time = date("Y-m-d H:i:s");
        }
        $total_count = Order::whereNotIn("user_id", $exclusiveUserIds)->where("pay_status", "PAID")->where("price", "<>", 0.01)->where("price", "<>", 5800)->where("created_at", ">=", $start_time)->where("created_at", '<=', $end_time)->count();
        $finished_count = Order::whereNotIn("user_id", $exclusiveUserIds)->where("pay_status", "PAID")->where("service_status", "FINISHED")->where("price", "<>", 0.01)->where("price", "<>", 5800)->where("created_at", ">=", $start_time)->where("created_at", '<=', $end_time)->count();
        $offline_count = Order::whereNotIn("user_id", $exclusiveUserIds)->whereHas("offline_order")->where("pay_status", "PAID")->where("price", "<>", 0.01)->where("price", "<>", 5800)->where("created_at", ">=", $start_time)->where("created_at", '<=', $end_time)->count();
        $online_count = $total_count - $offline_count;
        $after_report_count = MedicalReport::whereNotIn("user_id", $exclusiveUserIds)->where("type", 1)->where("created_at", ">=", $start_time)->where("created_at", '<=', $end_time)->count();
        return $this->success("ok", compact("total_count", "finished_count", "offline_count", "online_count", "after_report_count"));
    }

    public function addGroupUserRole($tid, $user_id)
    {
        if (empty($user_id)) {
            $user_id = request()->input("user_id");
        }
        if (empty($tid)) {
            $tid = request()->input("tid");
        }
        $group = Group::where("im_chat_id", $tid)->first();
        $order_role_ids = ServiceRoleOrder::where("order_id", $group->order_id)->where("user_id", $user_id)->pluck("role_id")->toArray();
        $service_user = ServiceUser::where("user_id", $user_id)->first();
        $groupUser = GroupUser::where("group_id", $group->id)->where("user_id", $user_id)->first();
        $map = [];
        $map['role'] = $order_role_ids;
        $map["comment"] = $groupUser->comment ?: "";
        $options = ['custom' => json_encode($map, JSON_UNESCAPED_UNICODE), 'nick' => $service_user->name];
        $owner_accid = make_wangyiyun_accid($group->owner_id);
        $user_accid = make_wangyiyun_accid($service_user->user_id);
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        $imTeam->updateTeamNick($group->im_chat_id, $owner_accid, $user_accid, $options);
        return $this->success('ok');
    }

    public function checkGroupRole()
    {
        $groups = Group::with("groupRoleUsers")->whereNotNull("order_id")->whereNotNull("im_chat_id")->orderByDesc("id")->get();
        foreach ($groups as $group) {
            Log::info($group->im_chat_id);
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $res = $imTeam->queryDetail($group->im_chat_id);
            $members = $res["tinfo"]["members"];
            foreach ($group->groupRoleUsers as $groupUser) {
                Log::info($groupUser->user_id);
                $member = collect($members)->where("accid", make_wangyiyun_accid($groupUser->user_id))->first();
                if ($member && isset($member["custom"]) && strpos($member["custom"], "role"))
                    continue;
                $this->addGroupUserRole($group->im_chat_id, $groupUser->user_id);
            }


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

    public function getGroupInfo()
    {
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        $res = $imTeam->queryDetail(request()->tid);
        return $this->success("ok", $res);
    }

    public function getYunxinUserInfo()
    {
        $imUser = new ImUser(config('chat.im.app_id'), config('chat.im.app_secret'));
        $res = $imUser->getUserInfos([make_wangyiyun_accid(request()->user_id)]);
        return $this->success("ok", $res);
    }

    public function deleteRepeatStep()
    {
        $logs = DB::table("daily_step")->whereNull("deleted_at")->groupBy(["user_id", "date"])->having("count", ">", 1)->selectRaw("user_id, date, count(*) as count")->get();
        foreach ($logs as $log) {
            $step = DailyStep::where("user_id", $log->user_id)->where("date", $log->date)->orderBy("id", "asc")->first();
            $step->delete();
        }
    }

    public function syncMobileName()
    {
        $index = 0;
        User::whereNotNull("name")->where("name", "<>", "")->whereNotNull("mobile")->where("mobile", "<>", "")->whereIn("source", [2, 3, 5])
            ->chunk(100, function ($users) use (&$index) {
                foreach ($users as $user) {
                    $index++;
                    $mobileArr = [$user->mobile];
                    if (aesEncryptCBC($user->mobile)) {
                        $mobileArr[] = aesEncryptCBC($user->mobile);
                    }
                    if (aesDecryptCBC($user->mobile)) {
                        $mobileArr[] = aesDecryptCBC($user->mobile);
                    }
                    $customer = User::whereIn("mobile", $mobileArr)->whereIn("source", [1, 4])->first();
                    if (empty($customer))
                        continue;
                    if ($customer->name == $user->name)
                        continue;

                    Log::info($user->id);
                    Log::info($customer->id);

                    // 修改im昵称
                    $imService = new ImService();
                    $customer->name = $user->name;
                    $imService->updateImUser($customer->id, $customer);

                    // 修改昵称
                    User::where("id", $customer->id)->update(["name" => $user->name]);

                }
            });
        Log::info($index);
    }

    public function updateFatLogData()
    {
        $id = request()->id;
        $log = NewFatLog::where("id", $id)->first();
        if (empty($log))
            return;
        $data = json_decode($log->data, true);

        $fatService = new FatService();
        $oldData = json_decode($log->old_data, true);

        $user = $log->user;
        $BRM_level = [];

        foreach ($oldData as $item) {
            //计算基础代谢标准
            if ($item['e_name'] == "BMR") {
                $standard = $fatService->calculateBmrStandard($oldData, $user);
                if ($item["score"] >= $standard) {
                    $desc_key = "BMR.1002";
                } else {
                    $desc_key = "BMR.1003";
                }
                $level = HealthLevel::where('desc_key', $desc_key)->select('name', 'e_name', 'color', 'desc', 'desc_key')->first();
                $level["desc"] = str_replace("xxx", $standard, $level['desc']);
                $BRM_level = $level->toArray();
            }
        }
        if (empty($BRM_level))
            return;
        foreach ($data as &$item) {
            if ($item['e_name'] != "BMR")
                continue;
            $item["level"] = $BRM_level;
            $item["fat_state"] = $BRM_level["name"];
        }
        dd($data);
    }

    // 同步主教练、副教练、客服到专属教练
    public function syncRole15()
    {
        $role_id = 15;
        $user_ids = DmaServiceUserRole::whereIn("role", [1, 2, 3])->groupBy("user_id")->pluck("user_id");
        foreach ($user_ids as $user_id) {
            $user = User::find($user_id);
            if (empty($user))
                continue;
            $serviceUser = ServiceUser::where("user_id", $user_id)->first();
            if (empty($serviceUser))
                continue;
            $role = DmaServiceUserRole::where("user_id", $user_id)->where("role", 15)->first();
            if (empty($role)) {
                DmaServiceUserRole::create([
                    "user_id" => $user_id,
                    "name" => $user->name,
                    "mobile" => aesDecryptCBC($user->mobile) ? aesDecryptCBC($user->mobile) : $user->mobile,
                    "avatar" => $user->avatar,
                    "role" => $role_id,
                    "status" => 1,
                    "audit_at" => date("Y-m-d H:i:s")
                ]);
            }

            $roleUser = ServiceRoleUser::where("role_id", $role_id)->where("user_id", $user_id)->first();
            if (empty($roleUser)) {
                ServiceRoleUser::create([
                    "role_id" => $role_id,
                    "user_id" => $user_id,
                    "s_user_id" => $serviceUser->id,
                ]);
            }
        }
    }

    /**
     * 开启所有服务人员接单状态
     * @return void
     */
    public function OpenRoleOrderStatus()
    {
        $user_ids = DmaServiceUserRole::where("status", 1)->distinct("user_id")->pluck("user_id")->toArray();

        foreach ($user_ids as $user_id) {
            $orderStatus = ServiceOrderStatus::where("user_id", $user_id)->first();
            if ($orderStatus)
                continue;

            ServiceOrderStatus::create([
                "user_id" => $user_id,
                "order_status" => 1,
                "last_owner" => 0,
            ]);
        }
    }
}
