<?php

namespace App\Http\Controllers;

use App\Facades\CommonService;
use App\Http\Response\ResponseJson;
use App\Models\FatKind;
use App\Models\FatLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FatController extends Controller
{
    use ResponseJson;

    const WEIGHT_RATE = 2.2;
    const WEIGHT_JIN_LB_RATE = 1.1;
    const WEIGHT_JIN_KG_RATE = 2;

    /**
     * 获取最近一次体脂信息
     * @param Request $request
     */
    public function home(Request $request, $user_id=null)
    {
        if (empty($user_id)) {
            $user = auth()->user();
            $user_id = $user->id;
        }else {
            $user = User::find($user_id);
        }
        $tested_at = $request->input('tested_at');
        if (empty($tested_at)) {
            //最近一次测量日期
            $tested_at = FatLog::where('user_id', $user_id)->groupBy('tested_at')->orderBy('tested_at', 'desc')->limit(1)->value('tested_at');
        }
        $logs = FatLog::with('fatKind')->where(['user_id' => $user_id, 'tested_at' => $tested_at])->select('fat_name', 'fat_state', 'fat_data', 'unit', 'tested_at','user_id')->get()->toArray();
        $score = [
            'weight'=>0,
            'weight_unit'=>'kg',
            'bodyfat'=>0,
            'bodyfat_unit'=>'%',
            'sinew'=>0,
            'sinew_unit'=>'%',
            'bmi'=>0,
            'metabolism'=>0,
            'metabolism_unit' => 'kcal',
            'tested_at'=>$tested_at,
        ];
        //判断用户信息
        $user->unit = get_user_unit($user->language,$user->unit);
        $unit = $user->unit??'kg';

        if (count($logs)) {
            foreach ($logs as &$log) {
                $log = $this->changeUnit($log, $unit,$user->language);
                $log = $this->changeKinds($log);
                if ($log['fat_name']  == '体重') {
                    $score['weight'] = $log['fat_data'];
                    $score['weight_unit'] = $unit;
                }
                if ($log['fat_name'] == 'BMI') {
                    $score['bmi'] = $log['fat_data'];
//                }elseif ($log['fat_name'] == '脂肪占比') {
                }elseif (in_array($log['fat_name'],['脂肪占比','脂肪率'])) {
                    $score['bodyfat'] = $log['fat_data'];
                    $score['bodyfat_unit'] = $log['unit'];
//                }elseif ($log['fat_name'] == '肌肉占比') {
                }elseif (in_array($log['fat_name'],['肌肉占比','肌肉率'])) {
                    $score['sinew'] = $log['fat_data'];
                    $score['sinew_unit'] = $log['unit'];
                }elseif (in_array($log['fat_name'],['基础代谢'])) {
                    $score['metabolism'] = $log['fat_data'];
                    $score['metabolism_unit'] = $log['unit'];
                }
            }
        }

        $score['weight_unit'] = get_user_unit($user->language,$user->unit);
        return $this->success('ok', compact('logs', 'score', 'user'));

    }

    /**
     * 修改数据
     * @param $log
     * @return mixed
     */
    public function changeKinds($log){
        $fat_names = [
            '脂肪率'=>'脂肪占比',
            '水分率'=>'体内水分',
            '肌肉率'=>'肌肉占比',
            '卡路里'=>'基础代谢',
            '脂肪重量'=>'体脂重量',
            '蛋白质重量'=>'蛋白质',
            '体重控制量'=>'脂肪控制',
        ];
        if(isset($fat_names[$log['fat_name']])){
            $log['fat_kind'] = FatKind::where('fat_name',$fat_names[$log['fat_name']])->select('fat_name','icon','h_icon')->first();
            $log['fat_kind']->fat_name = $log['fat_name']??'';
        }
        return $log;
    }

    /**
     * 获取两个时间的对比数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getDaysCompare(Request $request){
        try {
            if (empty($user_id)) {
                $user = auth()->user();
                $user_id = $user->id;
            }else {
                $user = User::find($user_id);
            }
            $start_tested_at = $request->input('start_tested_at');
            $end_tested_at = $request->input('end_tested_at');
            if(empty($start_tested_at) || empty($end_tested_at)){
                return $this->failure('请选择对比时间');
            }
            //判断两个时间大小
            if($start_tested_at > $end_tested_at){
                $temp_tested_at = $start_tested_at;
                $start_tested_at = $end_tested_at;
                $end_tested_at = $temp_tested_at;
            }
//            $start_time = strtotime($start_tested_at);
//            $end_time = strtotime($end_tested_at);
//            $differ_day = floor(($end_time-$start_time)/86400);

            $start_date = new \DateTime($start_tested_at);
            $end_date = new \DateTime($end_tested_at);

            $interval = $start_date->diff($end_date);
            $differ_day = $interval->days;
            $start_logs = FatLog::with('fatKind')
                ->where(['user_id' => $user_id, 'tested_at' => $start_tested_at])
                ->select('fat_name', 'fat_state', 'fat_data', 'unit', 'tested_at','user_id')
                ->orderBy('id', 'asc')
                ->get()
                ->toArray();
            $end_logs = FatLog::with('fatKind')
                ->where(['user_id' => $user_id, 'tested_at' => $end_tested_at])
                ->select('fat_name', 'fat_state', 'fat_data', 'unit', 'tested_at','user_id')
                ->orderBy('id', 'asc')
                ->get()
                ->toArray();

            if(empty($start_logs) || empty($end_logs)){
                return $this->failure('查询失败');
            }

            //判断用户信息
            $user->unit = get_user_unit($user->language,$user->unit);
            $unit = $user->unit??'kg';
            foreach ($start_logs as &$start_log) {
                $start_log = $this->changeUnit($start_log, $unit,$user->language);
                $start_log = $this->changeKinds($start_log);
            }
            foreach ($end_logs as &$end_log) {
                $end_log = $this->changeUnit($end_log, $unit,$user->language);
                $end_log = $this->changeKinds($end_log);
            }
            //对比两个数组的差值
            $merge_logs = [];
            foreach ($start_logs as $start){
                foreach ($end_logs as $end){
                    if(!isset($start['fat_name']) || !isset($end['fat_name'])){
                        continue;
                    }
                    if($start['fat_name'] != $end['fat_name']){
                        continue;
                    }
                    $status = 0;
                    $differ = '-';
                    $start['fat_data'] = floatval(str_replace(',', '', $start['fat_data']));
                    $end['fat_data'] = floatval(str_replace(',', '', $end['fat_data']));
                    if($start['fat_data'] < $end['fat_data']){
                        $status = 1;
                        $differ = get_two_float(abs($end['fat_data'] - $start['fat_data']),2);
                    }
                    if($start['fat_data'] > $end['fat_data']){
                        $status = 2;
                        $differ = get_two_float(abs($end['fat_data'] - $start['fat_data']),2);
                    }
                    $merge_logs[] = [
                        'fat_name' => $start['fat_name'],
                        'status' => $status,
                        'differ' => $differ,
                        'unit' => $start['unit']
                    ];
                }
            }
            //处理数组
            $fat_names = [];
            foreach ($merge_logs as $item) {
                if (isset($item['fat_name'])) {
                    $fat_names[] = $item['fat_name'];
                }
            }
            foreach ($start_logs as $sk=> $sv){
                if(!in_array($sv['fat_name'],$fat_names)){
                    unset($start_logs[$sk]);
                }
            }
            foreach ($end_logs as $ek=> $ev){
                if(!in_array($ev['fat_name'],$fat_names)){
                    unset($end_logs[$ek]);
                }
            }
            $start_logs = array_values($start_logs);
            $end_logs = array_values($end_logs);
            $data = [];
            $data['start_logs'] = $start_logs;
            $data['end_logs'] = $end_logs;
            $data['merge_logs'] = $merge_logs;
            $data['user'] = $user;
            $data['differ_day'] = $differ_day;
            return $this->success('ok',$data);
        }catch (\Exception $e){
            Log::error('getDaysCompare:'.$e->getMessage());
            return $this->failure('查询失败');
        }
    }
    public function changeUnit($log, $unit,$language)
    {
        if ($log['unit'] == 'kg' && $unit == '斤' && $language == 0) {
            $log['fat_data'] = get_two_float($log['fat_data'] * 2, 2);
            $log['unit'] = '斤';
        }
        if ($log['unit'] == 'kg' && $unit == '斤' && $language == 1) {
            $log['fat_data'] = get_two_float($log['fat_data'] * self::WEIGHT_RATE, 2);
            $log['unit'] = 'lb';
        }
        if($log['unit'] == 'kg' && $unit == 'lb' && $language == 1){
            $log['fat_data'] = get_two_float($log['fat_data'] * self::WEIGHT_RATE, 2);
            $log['unit'] = 'lb';
        }
        if($log['unit'] == 'kg' && $unit == 'lb' && $language == 0){
            $log['fat_data'] = get_two_float($log['fat_data'] * 2, 2);
            $log['unit'] = '斤';
        }
        if($log['unit'] == 'lb' && $unit == 'kg' ){
            $log['fat_data'] = get_two_float($log['fat_data'] / self::WEIGHT_RATE, 2);
            $log['unit'] = 'kg';
        }
        if($log['unit'] == 'lb' && $unit == '斤' ){
            $log['fat_data'] = get_two_float($log['fat_data'] / self::WEIGHT_JIN_LB_RATE, 2);
            $log['unit'] = '斤';
        }
        return $log;
    }

    /**
     * 保存体脂信息
     * @param Request $request
     */
    public function storeFatLog(Request $request)
    {
        $user = auth()->user();
        $user_id = $user->id;
        $tested_at = date('Y-m-d H:i:s');
        $data = $request->input('data');
        $type = $request->input('type');
        $flag = $request->input('flag',false);
        $device_model = $request->input('device_model');
        $init_data = $request->input('init_data');
        if(empty($data)){
            return $this->failure('数据不为空');
        }
        //是否完整资料
        $is_complete_info = $user->baseUserInfo();
        if (empty($is_complete_info)) return $this->failure("请先完善基本信息");

        $weight_score = 0;
        foreach ($data as $key => &$da) {
            if ($da['fat_name'] == "腰臀比") unset($data[$key]);
            $da['user_id'] = $user_id;
            $da['tested_at'] = $da['created_at'] = $da['updated_at'] = $tested_at;
            $da['unit'] = strtolower($da['unit']);
            if($type == 'lb'){
                $da['unit'] = 'lb';
//                $da['fat_data'] = get_two_float(floatval($da['fat_data'])/self::WEIGHT_RATE,2);
            }
            if($da['fat_name'] == '体重'){
                $weight_score = $da['fat_data'];
            }
        }
        //查询最近一次称重记录
        $weight = FatLog::where('user_id',$user_id)->where('fat_name','体重')->orderBydesc('id')->value('fat_data');
        if(!empty($weight) && !empty($weight_score) && !$flag){
            $weight_rate = $weight*0.1;
            $weight_differ = $weight_score - $weight;
            //弹出提示
            if(abs($weight_differ) >= $weight_rate){
                return $this->success('ok',['flag'=>true]);
            }
        }
        //增加原始数值
        foreach ($data as $index => $item){
            $data[$index]['init_data'] = $init_data;
            $data[$index]['device_model'] = $device_model;
        }
        FatLog::insert($data);
        return $this->success('ok');
    }

    /**
     * 体脂记录
     * @param Request $request
     */
    public function fatLogs(Request $request)
    {
        Log::info("fatLogs");
        $unit = auth()->user()->unit;
        $language = auth()->user()->language;
        $logs = FatLog::where(['user_id' => auth()->id(), 'fat_name' => "体重"])
            ->orderByDesc('id')
            ->select('id', 'fat_name', 'fat_data', 'tested_at')->paginate();
        foreach ($logs as $log) {
            $log->yearMonth = date('Y年m月', strtotime($log->tested_at));
            $log->dayHour = date('d日 H:i', strtotime($log->tested_at));
            $log->unit = get_user_unit($language,$unit);
            if ($unit != 'kg') {
                if(($unit == 'lb' || $unit == '斤') && $language == 1){
                    $log->fat_data = get_two_float($log->fat_data * self::WEIGHT_RATE, 2);
                }else{
                    $log->fat_data = get_two_float($log->fat_data * 2, 2);
                }
            }
        }
        return $this->success('ok', $logs);
    }

    public function fatLog(Request $request)
    {
        $tested_at = $request->input('tested_at');
        if(empty($tested_at)) throw new \Exception("缺少参数.tested_at");
        $unit = $request->input('unit');
        $user_id = $request->input('user_id');
        if (empty($user_id)) {
            $user = auth()->user();
            $user_id = $user->id;
            $unit = $user->unit;
            $language = $user->language;
        }else{
            $user = User::where('id',$user_id)->first();
            $language = $user->language;
        }
        if(empty($unit)){
            $unit = $user->unit;
        }
        $logs = FatLog::with('fatKind:fat_name,icon')->where(['user_id' => $user_id, 'tested_at' => $tested_at])->get()->toArray();
        if (count($logs)) {
            foreach ($logs as &$log) {
                $log = $this->changeUnit($log, $unit,$language);
                $log = $this->changeKinds($log);
            }
        }
        return $this->success('ok', $logs);
    }

    /**
     * 删除体脂信息
     * @param Request $request
     */
    public function deleteFatLog(Request $request)
    {
        $tested_at = $request->input("tested_at");
        if (empty($tested_at)) throw new \Exception("未获取到测量时间信息");
        FatLog::where(['user_id'=>auth()->id(), 'tested_at'=>$tested_at])->delete();
        return $this->success('ok');
    }

    public function fatKinds(Request $request)
    {
        $kinds = FatKind::where(function ($sql) {
            $sql->where('icon', '!=', '');
        })->get();
        $user = auth()->user();
        $fat_names = [
            '脂肪占比'=>'脂肪率',
            '体内水分'=>'水分率',
            '肌肉占比'=>'肌肉率',
            '卡路里'=>'基础代谢',
            '体脂重量'=>'脂肪重量',
            '蛋白质'=>'蛋白质重量',
            '脂肪控制'=>'体重控制量',
        ];
        foreach ($kinds as $kind) {
            if ($kind->unit == 'kg' && $user->unit != $kind->unit) {
                $kind->unit = change_unit($user->language,$user->unit);
            }
            if(isset($fat_names[$kind->fat_name])){
                $kind->fat_name = $fat_names[$kind->fat_name];
            }
        }
        return $this->success('ok', $kinds);
    }

    public function fatStat(Request $request)
    {
        $fat_name = $request->input('fat_name');
        $start_date = $request->input('start_date');
        $end_date = $request->input('end_date');
        if ($start_date && $end_date) {
            $day_arr = CommonService::daliy($start_date, $end_date);
        }else {
            $day_arr = CommonService::daliy(date('Y-m-d', strtotime('-180 days')), date('Y-m-d'));
            //获取用户第一次称的时间
//            $test_date = FatLog::where('user_id',auth()->id())->where('fat_name', $fat_name)->value('created_at');
//            $day_arr = CommonService::daliy(date('Y-m-d', strtotime($test_date)), date('Y-m-d'));
        }
        $x_arr = [];
        $y_arr = [];
        $z_arr = [];
        $unit = auth()->user()->unit;

        //这只是为了兼容之前不好的旧结构设计，有缘人自己把整个结构改了，我没时间重构整个旧数据结构，将错就错
        $fat_names = [
            '脂肪率'=>['脂肪占比','脂肪率'],
            '水分率'=>['体内水分','水分率'],
            '肌肉率'=>['肌肉占比','肌肉率'],
            '卡路里'=>['基础代谢','卡路里'],
            '脂肪重量'=>['体脂重量','脂肪重量'],
            '蛋白质重量'=>['蛋白质','蛋白质重量'],
            '体重控制量'=>['脂肪控制','体重控制量'],
        ];
        if(isset($fat_names[$fat_name])){
            $fat_name = $fat_names[$fat_name];
        }else{
            $fat_name = explode(',',$fat_name);
        }
        foreach ($day_arr as $day) {
            $x_arr[] = date('m/d', strtotime($day));
            $day_end = date('Y-m-d', strtotime($day) + 24 *3600);
            $log = FatLog::where('user_id', auth()->id())->whereIn('fat_name', $fat_name)->where('created_at', '>', $day)->where('created_at', '<', $day_end)->orderByDesc('fat_data')->first();
            $mix_log = FatLog::where('user_id', auth()->id())->whereIn('fat_name', $fat_name)->where('created_at', '>', $day)->where('created_at', '<', $day_end)->orderBy('fat_data','asc')->first();
            $fat_data = $fat_mix = 0;
            if ($log) {
                $log = $log->toArray();
                if ($log['unit'] == 'kg') {
                    $log = $this->changeUnit($log, $unit,auth()->user()->language);
                }
                $fat_data = $log['fat_data'];
            }
            $y_arr[] = $fat_data;

            if ($mix_log) {
                $mix_log = $mix_log->toArray();
                if ($mix_log['unit'] == 'kg') {
                    $mix_log = $this->changeUnit($mix_log, $unit,auth()->user()->language);
                }
                $fat_mix = $mix_log['fat_data'];
            }
            $z_arr[] = $fat_mix;
        }
        return $this->success('ok', compact('x_arr', 'y_arr','z_arr'));
    }
}
