<?php

namespace App\Http\Controllers\App;

use App\Facades\CommonService;
use App\Http\Controllers\Controller;
use App\Facades\WechatService;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\NewFatLog;
use App\Models\User;
use App\Models\Version;
use App\Services\ChatService;
use App\Services\FatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class HealthController extends Controller
{
    use ResponseJson;

    /**
     * 获取最近一次体脂信息
     * @param Request $request
     */
    public function home(Request $request)
    {
        try {
            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                $user = auth()->user();
            } else {
                $user = User::find($user_id);
            }
            if ($user->name2) {
                $user->name = $user->name2;
            }
            $id = $request->get('id');

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getHomeData($user, $id);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getHomeData:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }

    }

    /**
     * 保存体脂信息
     * @param Request $request
     */
    public function storeHealthLog(Request $request)
    {
        try {
            $user = auth()->user();
            $params = $request->all();
            //是否完整资料
            $is_complete_info = $user->baseUserInfo();
            if (empty($is_complete_info))
                return $this->failure("请先完善基本信息");

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;


            $fatService = new FatService();
            $res = $fatService->saveFatLog($user, $params, Version::TYPE_APP);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('saveFatLog:' . $e->getMessage())->onQueue('health');
            return $this->failure('保存失败');
        }
    }

    /**
     * 保存体脂信息
     * @param Request $request
     */
    public function storeHealthLogV1(Request $request)
    {
        Log::info("开始保存体脂秤数据");
        // try {
        $user = auth()->user();
        $params = $request->all();
        Log::info(json_encode($params));
        //是否完整资料
        $is_complete_info = $user->baseUserInfo();
        Log::info("是否完整资料： " . $is_complete_info);
        if (empty($is_complete_info))
            return $this->failure("请先完善基本信息");

        $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

        $fatService = new FatService();
        $res = $fatService->saveFatLog($user, $params, Version::TYPE_APP);
        Log::info($res);
        if (!$res['status']) {
            return $this->failure($res['msg']);
        }
        $result = $res['data'];
        if (empty($res['data'])) {
            $result = ['flag' => false];
        }

        Log::info("结束保存体脂秤数据");
        return $this->success('ok', $result);
        // } catch (\Exception $e) {
        //     AddErrorLog::dispatch('saveFatLog:' . $e->getMessage())->onQueue('health');
        //     return $this->failure('保存失败');
        // }
    }
    /**
     * 体脂记录
     * @param Request $request
     */
    public function healthLogs(Request $request)
    {
        try {
            $user = auth()->user();

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getFatLogList($user);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getFatLogList:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    /**
     * 体脂详情
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function healthLog(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                return $this->failure('缺少参数id');
            }
            $unit = $request->input('unit');
            $user_id = $request->input('user_id');

            $user = auth()->user();

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getFatDetail($id, $user_id, $unit, $user);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getFatDetail:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }


    /**
     * 获取数据对比
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function compareHealthLogs(Request $request)
    {
        try {
            if (empty($user_id)) {
                $user = auth()->user();
            } else {
                $user = User::find($user_id);
            }
            $start_id = $request->input('start_id');
            $end_id = $request->input('end_id');
            if (empty($start_id) || empty($end_id)) {
                return $this->failure('请选择对比时间');
            }

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getCompareFatData($user, $start_id, $end_id);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getCompareFatData:' . $e->getMessage())->onQueue('health');
            return $this->failure('查询失败');
        }
    }

    /**
     * 获取统计图
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function healthStat(Request $request)
    {
        try {
            $name = $request->input('fat_name');
            $start_date = $request->input('start_date');
            $end_date = $request->input('end_date');

            $user = auth()->user();

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getFatStat($name, $start_date, $end_date, $user);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getFatStat:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取图标
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function healthKinds(Request $request)
    {
        try {
            $user = auth()->user();

            $user->fat_device = User::FAT_DEVICE_YUNKANGBAO;

            $fatService = new FatService();
            $res = $fatService->getFatKinds($user);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data'] ?? []);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('fatKinds:' . $e->getMessage())->onQueue('health');
            return $this->failure('查询失败');
        }
    }

    /**
     * 删除体脂信息
     * @param Request $request
     */
    public function deleteHealthLog(Request $request)
    {
        $id = $request->input("id");
        if (empty($id))
            return $this->failure('未获取到测量信息');
        NewFatLog::where(['id' => $id])->delete();
        return $this->success('ok');
    }

    /**
     * 发送称重信息到网易云信群
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function sendHealthMsgToGroup(Request $request)
    {
        try {
            $user = auth()->user();
            $fat_id = NewFatLog::where('user_id', $user->id)->orderByDesc('id')->value('id');
            $chatService = new ChatService();
            $params = [];
            $params['id'] = $fat_id;
            $params['yearMonth'] = date('Y年m月');
            $params['dayHour'] = date('d日 H:i');
            $params['type'] = $user->fat_device;
            $chatService->sendGroupMsg($user->id, '体重信息', '本次称重信息已为您自动生成，请点击查看详情', 'https://image.fulllinkai.com/202311/27/0ed7ffaa2eb0116dd46b6f1597795766.png', "yfheal://app/push/MeasurementRecordDetail", $params);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('sendFatMsgToGroup:' . $e->getMessage())->onQueue('health');
            return $this->failure('发送失败');
        }
    }
}
