<?php

namespace App\Http\Controllers\App;

use App\Facades\CommonService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SyncDailyStep;
use App\Models\Band;
use App\Models\BandBlood;
use App\Models\BandConsume;
use App\Models\BandDataTime;
use App\Models\BandGoal;
use App\Models\BandGoalLog;
use App\Models\BandHrrest;
use App\Models\BandHrv;
use App\Models\BandOriginBattery;
use App\Models\BandOriginBlood;
use App\Models\BandOriginDataTime;
use App\Models\BandOriginHrrest;
use App\Models\BandOriginHrv;
use App\Models\BandOriginSleep;
use App\Models\BandOriginSyn;
use App\Models\BandOriginTemp;
use App\Models\BandSleep;
use App\Models\BandSyn;
use App\Models\BandTemp;
use App\Models\BatteryHistory;
use App\Models\SplitModel;
use App\Models\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BandController extends Controller
{
    use ResponseJson;

    public function bindBand(Request $request)
    {
        $mac = $request->input('mac');
        $name = $request->input('name');
        $user = auth()->user();
        // 手环是否已绑定账号
        list($is_bind, $is_self, $mobile) = Band::bindStatus($mac, $user);
        if ($is_bind)
            return $this->failure("当前手环已被账号为{$mobile}绑定");
        // 账号是否绑定手环
        $userBand = Band::where("user_id", $user->id)->where('status', 1)->first();
        if ($userBand)
            return $this->failure("当前账号已绑定了手环{$userBand->name}");
        DB::beginTransaction();
        //绑定手环
        $band = Band::bindUser($mac, $name, $user);
        //设置目标
        $band->setGoals();
        //切換状态
        Band::connectUser($mac, $user);
        DB::commit();
        return $this->success('ok', $band);
    }

    public function bands(Request $request)
    {
        $bands = Band::owner(auth()->id())->orderByDesc("status")->get();
        return $this->success('ok', $bands);
    }

    public function unbindBand(Request $request)
    {
        $mac = $request->input('mac');
        $user = auth()->user();
        Band::unbindUser($mac, $user);
        return $this->success('ok');
    }

    public function connectBand(Request $request)
    {
        $mac = $request->input('mac');
        $user = auth()->user();
        Band::connectUser($mac, $user);
        return $this->success('ok');
    }

    public function breakBand(Request $request)
    {
        $mac = $request->input('mac');
        $user = auth()->user();
        Band::breakUser($mac, $user);
        return $this->success('ok');
    }

    public function setGoals(Request $request)
    {
        $data = $request->only(['step_num', 'distance', 'kcal', 'sleep', 'mac']);
        $band = Band::owner(auth()->id())->mac($data['mac'])->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        $band->setGoals($data);
        return $this->success('ok');
    }

    public function goals(Request $request)
    {
        $mac = $request->input('mac');
        $type = $request->input('type');
        $band = Band::owner(auth()->id())->mac($mac)->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        switch ($type) {
            case BandGoal::DAY_TYPE:
                $goals = $band->goals;
                break;
            case BandGoal::WEEK_TYPE:
            case BandGoal::MONTH_TYPE:
                $goals = $this->getGoals($band, $type);
                break;
            default:
                throw new \Exception("目标信息缺少参数");
        }
        return $this->success('ok', $goals);
    }

    public function getGoals($band, $type)
    {
        $step_num = $distance = $kcal = $sleep = 0;
        $times = [];
        if ($type == BandGoal::WEEK_TYPE) {
            $num = BandGoal::WEEK_NUM;
        } else {
            $num = BandGoal::MONTH_NUM;
        }
        for ($i = $num - 1; $i >= 0; $i--) {
            $start_time = date("Y-m-d", strtotime("-{$i} days"));
            $day = $i - 1;
            $end_time = date("Y-m-d", strtotime("-{$day} days"));
            $times[] = ["start_time" => $start_time, 'end_time' => $end_time];
        }
        foreach ($times as $time) {
            $start_time = $time['start_time'];
            $end_time = $time['end_time'];
            $log = $band->goalsLogs()->times($start_time, $end_time)->first();
            if (empty($log)) {
                $log = $band->goalsLogs()->where('created_at', '<', $start_time)->orderByDesc("id")->first();
                if (empty($log)) {
                    $log = $band->goalsLogs()->orderByDesc("id")->first();
                }
            }
            $step_num += $log->step_num;
            $distance += $log->distance;
            $kcal += $log->kcal;
            $sleep += $log->sleep;
        }
        return ["step_num" => $step_num, "distance" => $distance, 'kcal' => $kcal, 'sleep' => $sleep];
    }

    public function uploadSleepData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandSleep::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }

    public function uploadHrrestData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandHrrest::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }

    public function uploadTempData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandTemp::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }

    public function uploadHrvData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandHrv::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }

    public function uploadBloodData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandBlood::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }

    public function uploadSynData(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $last_time = $this->uploadData(BandSyn::class, $user, $mac, $data);
        return $this->success('ok', compact('last_time'));
    }


    public function uploadData($class, $user, $mac, $data)
    {
        DB::beginTransaction();
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            throw new \Exception("未获取到手环信息", 5000);
        $suffix = SplitModel::getMonthSuffix();
        switch ($class) {
            case BandSleep::class:
                $key = "sleep_time";
                break;
            case BandHrrest::class:
                $key = "hrrest_time";
                break;
            case BandTemp::class:
                $key = "temp_time";
                break;
            case BandHrv::class:
                $key = "hrv_time";
                break;
            case BandSyn::class:
                $key = "syn_time";
                break;
            case BandBlood::class:
                $key = "blood_time";
                break;
        }
        $date_time = BandDataTime::owner($user->id)->band($band->id)->first();
        $min_date = "";
        if ($date_time && $date_time->$key) {
            $min_date = date("Y-m-d H:i:s", $date_time->$key);
        }
        $data = collect($data)->where('date', '>', $min_date)->sortBy("date")->all();
        $items = [];
        foreach ($data as &$item) {
            $obj = collect($items)->where('date', $item['date'])->first();
            if ($obj)
                continue;
            $item['created_at'] = $item['updated_at'] = date("Y-m-d H:i:s");
            $item['user_id'] = $user->id;
            $item['band_id'] = $band->id;
            $items[] = $item;
        }
        $limit = 1000;
        $cols = collect($items)->count();
        $last_time = '';
        if ($cols) {
            collect($items)->chunk($limit)
                ->each(function ($calls) use ($class, $suffix, &$last_time) {
                    $data = $calls->toArray();
                    //                    Log::info($data);
                    $class::suffix($suffix)->insert($data);
                    Log::info($calls->sortByDesc("date")->value('date'));
                    $last_time = $calls->sortByDesc("date")->value('date');
                });
        } else {
            DB::commit();
            return $min_date ? strtotime($min_date) : '';
        }
        if ($last_time) {
            $last_time = strtotime($last_time);
            $date_time = BandDataTime::owner($user->id)->band($band->id)->first();
            if ($date_time) {
                BandDataTime::owner($user->id)->band($band->id)->update([$key => $last_time]);
            } else {
                BandDataTime::create(['user_id' => $user->id, 'band_id' => $band->id, $key => $last_time]);
            }
        }
        DB::commit();
        return $last_time;
    }

    public function uploadOriginData($class, $user, $mac, $data, $key): array
    {
        DB::beginTransaction();
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            throw new \Exception("未获取到手环信息", 5000);
        $suffix = SplitModel::getMonthSuffix();
        $date_time = BandOriginDataTime::owner($user->id)->band($band->id)->first();
        $min_date = "";
        if ($date_time && $date_time->$key) {
            $min_date = date("Y-m-d H:i:s", $date_time->$key);
        }
        $data = collect($data)->filter(function ($item, int $key) use ($min_date) {
            $date = str_replace('.', '-', $item['date']);
            return $date > $min_date;
        })->all();
        //        $data = collect($data)->where('date', '>', $min_date)->sortBy("date")->all();
        $items = [];
        $date = date("Y-m-d H:i:s");
        foreach ($data as &$item) {
            $item['date'] = str_replace('.', '-', $item['date']);
            if ($item['date'] == "2000-00-00 00:00:00")
                continue;
            //去重
            $obj = collect($items)->where('date', $item['date'])->first();
            if ($obj)
                continue;
            $items[] = ['date' => $item['date'], 'user_id' => $user->id, 'band_id' => $band->id, 'value' => json_encode($item), 'created_at' => $date, 'updated_at' => $date];
        }
        $limit = 1000;
        $cols = collect($items)->count();
        $last_time = '';
        $start_time = "";
        $prefix = config('database.connections.mysql.prefix');  // 获取表前缀
        $model = new $class;  // 实例化模型类
        $table = $prefix . $model->getTable() . '_' . $suffix;  // 获取表名
        if ($cols) {
            collect($items)->chunk($limit)
                ->each(function ($calls) use ($class, $suffix, &$start_time, &$last_time, $table) {
                    //                    Log::info('band_data:'.json_encode($insert_data));
    
                    $data = $calls->toArray();
                    $values = [];
                    foreach ($data as $value) {
                        $values[] = sprintf(
                            '(%d, %d, "%s", \'%s\', "%s", "%s")',
                            $value['user_id'],
                            $value['band_id'],
                            $value['date'],
                            $value['value'],
                            $value['created_at'],
                            $value['updated_at']
                        );
                    }
                    $sql = sprintf(
                        'REPLACE INTO %s (user_id, band_id, date, value, created_at, updated_at) VALUES %s',
                        $table,
                        implode(', ', $values)
                    );
                    DB::statement($sql);
                    $last_time = $calls->sortByDesc("date")->value('date');
                    $start_time = $calls->sortBy("date")->value('date');
                    $start_time = strtotime($start_time);
                });
        } else {
            DB::commit();
            return [$start_time, $min_date ? strtotime($min_date) : ''];
        }
        if ($last_time) {
            $last_time = strtotime($last_time);
            $date_time = BandOriginDataTime::owner($user->id)->band($band->id)->first();
            if ($date_time) {
                BandOriginDataTime::owner($user->id)->band($band->id)->update([$key => $last_time]);
            } else {
                BandOriginDataTime::create(['user_id' => $user->id, 'band_id' => $band->id, $key => $last_time]);
            }
        }
        DB::commit();
        return [$start_time, $last_time];
    }

    public function uploadOriginBatteryData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginBattery::class, $user, $mac, $data, $key = "battery_time");
        $last_time = $res[1];
        return $this->success('ok', compact('last_time'));
    }

    public function uploadOriginSleepData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginSleep::class, $user, $mac, $data, $key = "sleep_time");
        $last_time = $res[1];
        return $this->success('ok', compact('last_time'));
    }

    public function uploadOriginHrrestData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginHrrest::class, $user, $mac, $data, $key = "hrrest_time");
        $last_time = $res[1];
        return $this->success('ok', compact('last_time'));
    }

    public function uploadOriginTempData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginTemp::class, $user, $mac, $data, $key = "temp_time");
        $last_time = $res[1];
        return $this->success('ok', compact('last_time'));
    }

    public function uploadOriginHrvData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginHrv::class, $user, $mac, $data, $key = "hrv_time");
        $last_time = $res[1];

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

    public function uploadOriginBloodData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        $user = auth()->user();
        $mac = $request->input('mac');
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginBlood::class, $user, $mac, $data, $key = "blood_time");
        $last_time = $res[1];

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

    public function uploadOriginSynData(Request $request)
    {
        ini_set('max_execution_time', 18000);
        Log::info("uploadOriginSynData");
        $user = auth()->user();
        $mac = $request->input('mac');
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            throw new \Exception("未获取到手环信息", 5000);
        $data = $request->data;
        $res = $this->uploadOriginData(BandOriginSyn::class, $user, $mac, $data, $key = "syn_time");
        $start_time = $res[0];
        $last_time = $res[1];
        Log::info("uploadOriginSynData: user_id:{$user->id} start_time:{$start_time}  end_time:{$last_time}");
        if ($start_time && $last_time) {
            $suffix = SplitModel::getMonthSuffix();
            SyncDailyStep::dispatch($user, $start_time, $last_time, $suffix, $band->id)->onQueue('sync.daily.step');
        }
        return $this->success('ok', compact('last_time'));
    }

    public function dailyOriginBattery(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        if (empty($mac)) {
            $mac = Band::owner($user->id)->where("status", 1)->value("mac");
        }
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginBattery::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailySleep(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        if (empty($mac)) {
            $mac = Band::owner($user->id)->where("status", 1)->value("mac");
        }
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandSleep::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginSleep(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginSleep::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginHrrest(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginHrrest::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginTemp(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginTemp::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginHrv(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginHrv::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginBlood(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginBlood::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyOriginSyn(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input("mac");
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $res = $this->dailyData(BandOriginSyn::class, $user, $mac, $start_time, $end_time);
        return $this->success("ok", $res);
    }

    public function dailyData($class, $user, $mac, $start_time, $end_time)
    {
        Log::info($start_time);
        if (strtotime($end_time) < 1717171200)
            return [];
        if (strtotime($start_time) < 1717171200) {
            $start_time = "2024-06-01";
        }
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            throw new \Exception("未获取到手环信息", 5000);
        // $start_month = date("m", strtotime($start_time));
        // $suffix = date("Y") . $start_month;
        // Log::info($suffix);
        // $arr = $class::suffix($suffix)->owner($user->id)->band($band->id)->time($start_time, $end_time)->orderBy("date")->get()->toArray();
        // $end_month = date("m", strtotime($end_time));
        // $suffix2 = date("Y") . $end_month;
        // if ($start_month == $end_month) {//
        //     if ($end_month == 12) {
        //         $end_month = 1;
        //         $suffix2 = date("Y", strtotime("+1 year")) . $end_month;
        //     } else {
        //         $end_month = str_pad($end_month + 1, 2, 0, STR_PAD_LEFT);
        //         $suffix2 = date("Y") . $end_month;
        //     }
        // }
        $suffixArr = $this->getDailySuffix($start_time, $end_time);
        $suffix = $suffixArr[0];
        $suffix2 = $suffixArr[1];
        Log::info($suffix2);
        Log::info($start_time);
        Log::info($end_time);
        $arr = $class::suffix($suffix)->owner($user->id)->band($band->id)->time($start_time, $end_time)->orderBy("date")->get()->toArray();
        $arr2 = $class::suffix($suffix2)->owner($user->id)->band($band->id)->time($start_time, $end_time)->orderBy("date")->get()->toArray();
        $arr = array_merge($arr2, $arr);
        return $arr;
    }

    public function getDailySuffix($start_time, $end_time)
    {
        $suffix = $suffix2 = "";
        // 开始时间
        $start_month = date("m", strtotime($start_time));
        $start_year = date("Y", strtotime($start_time));

        // 结束时间
        $end_month = date("m", strtotime($end_time));
        $end_year = date("Y", strtotime($end_time));

        if ($start_year == $end_year && $start_month == $end_month) {// 同年 同月份
            $suffix = $start_year . $start_month;
            // 往后+1月
            if ($end_month == 12) {
                $end_year = $end_year + 1;
                $end_month = "01";
            } else {
                $date = Carbon::parse($end_time);
                $newDate = $date->addMonth();
                $end_month = $newDate->format("m");
                $end_year = $newDate->year;
            }
            $suffix2 = $end_year . $end_month;
        } else {
            $suffix = $start_year . $start_month;
            $suffix2 = $end_year . $end_month;
        }
        return [$suffix, $suffix2];
    }


    public function bindStatus(Request $request)
    {
        $mac = $request->input('mac');
        $user = auth()->user();
        list($is_bind, $is_self, $mobile) = Band::bindStatus($mac, $user);
        return $this->success('ok', compact('is_bind', 'is_self', 'mobile'));
    }

    public function newestDate(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        $date_time = BandDataTime::owner($user->id)->band($band->id)->first();
        $sleep_time = $hrrest_time = $temp_time = $hrv_time = $syn_time = $blood_time = '';
        if ($date_time) {
            $sleep_time = $date_time->sleep_time ?: '';
            $hrrest_time = $date_time->hrrest_time ?: "";
            $temp_time = $date_time->temp_time ?: "";
            $hrv_time = $date_time->hrv_time ?: '';
            $syn_time = $date_time->syn_time ?: "";
            $blood_time = $date_time->blood_time ?: "";
        }
        return $this->success('ok', compact('sleep_time', 'hrrest_time', 'temp_time', 'hrv_time', 'hrv_time', 'syn_time', 'blood_time'));
    }

    public function newestOriginDate(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        $date_time = BandOriginDataTime::owner($user->id)->band($band->id)->first();
        $sleep_time = $hrrest_time = $temp_time = $hrv_time = $syn_time = $blood_time = $battery_time = "";
        if ($date_time) {
            $sleep_time = $date_time->sleep_time ?: "";
            $temp_time = $date_time->temp_time ?: "";
            $hrv_time = $date_time->hrv_time ?: "";
            $syn_time = $date_time->syn_time ?: "";
            $blood_time = $date_time->blood_time ?: "";
            $battery_time = $date_time->battery_time ?: "";
            $hrrest_time = $date_time->hrrest_time ?: "";
        }
        return $this->success('ok', compact('sleep_time', 'hrrest_time', 'temp_time', 'hrv_time', 'hrv_time', 'syn_time', 'blood_time', "battery_time"));
    }

    public function newestOriginFirstDate(Request $request)
    {
        $user = auth()->user();
        $mac = $request->input('mac');
        $band = Band::owner($user->id)->mac($mac)->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        $sleep_time = $hrrest_time = $temp_time = $hrv_time = $syn_time = $blood_time = "";
        $date_time = BandOriginDataTime::owner($user->id)->band($band->id)->first();
        if ($date_time) {
            $sleep_time = $date_time->sleep_time ?: '';
            $hrrest_time = $date_time->hrrest_time ?: "";
            $temp_time = $date_time->temp_time ?: "";
            $hrv_time = $date_time->hrv_time ?: '';
            $syn_time = $date_time->syn_time ?: "";
            $blood_time = $date_time->blood_time ?: "";
        }

        if ($sleep_time) {
            //如果大于当天16点  开始时间为当天时间16点， 小于当天16点  开始时间为前一天的16点
            $time = strtotime(date("Y-m-d 16:00:00", $sleep_time));
            if ($sleep_time > $time) {
                $start_time = $time;
            } else {
                $start_time = $time - 24 * 60 * 60;
            }
            $start_month = date("m", $start_time);
            $end_month = date("m", $sleep_time);

            $suffix = date("Y") . $start_month;
            $sleep_date = BandOriginSleep::suffix($suffix)->owner($user->id)->band($band->id)->time(date("Y-m-d H:i:s", $start_time), date("Y-m-d H:i:s", $sleep_time))->orderBy("date")->value("date");
            if (empty($sleep_date) && $start_month != $end_month) {
                $suffix = date("Y") . $end_month;
                $sleep_date = BandOriginSleep::suffix($suffix)->owner($user->id)->band($band->id)->time(date("Y-m-d H:i:s", $start_time), date("Y-m-d H:i:s", $sleep_time))->orderBy("date")->value("date");
            }
            $sleep_time = $sleep_date ? strtotime($sleep_date) : "";

        }

        if ($hrrest_time) {
            $hrrest_time = $this->getFirstTime(BandOriginHrrest::class, $hrrest_time, $user->id, $band->id);
        }
        if ($temp_time) {
            $temp_time = $this->getFirstTime(BandOriginTemp::class, $temp_time, $user->id, $band->id);
        }
        if ($hrv_time) {
            $hrv_time = $this->getFirstTime(BandOriginHrv::class, $hrrest_time, $user->id, $band->id);
        }
        if ($syn_time) {
            $syn_time = $this->getFirstTime(BandOriginSyn::class, $syn_time, $user->id, $band->id);
        }
        if ($blood_time) {
            $blood_time = $this->getFirstTime(BandOriginBlood::class, $blood_time, $user->id, $band->id);
        }

        return $this->success('ok', compact('sleep_time', 'hrrest_time', 'temp_time', 'hrv_time', 'syn_time', 'blood_time'));
    }

    public function getFirstTime($class, $time, $user_id, $band_id)
    {
        $start_time = strtotime(date("Y-m-d 00:00:00", $time));
        $end_time = $time;
        $start_month = date("m", $start_time);
        $suffix = date("Y") . $start_month;
        $date = $class::suffix($suffix)->owner($user_id)->band($band_id)->time(date("Y-m-d H:i:s", $start_time), date("Y-m-d H:i:s", $end_time))->orderBy("date")->value("date");
        $date_time = $date ? strtotime($date) : "";
        return $date_time;
    }

    // 手环消耗数据
    public function uploadBandConsumeData(Request $request)
    {
        $mac = $request->input("mac");
        $data = $request->input("data");
        $user_id = auth()->id();
        $band = Band::owner($user_id)->mac($mac)->first();
        if (empty($band))
            return $this->failure("未获取到手环信息");
        BandConsume::create(['user_id' => $user_id, "band_id" => $band->id, "data" => $data]);
        return $this->success("Ok");
    }
}
