<?php

namespace app\app\controller;

use think\Controller;
use think\Db;

class Skip extends Base{
    
    protected $color = ['#FF5656','#FFAB00','#5AD06D','#6492F6','#3967D6'];
    protected $curve_data_format = ['jump_num'=>['跳绳个数','个数/个','#009DFF'],'jump_time'=>['跳绳时长','时长/分','#009DFF'],'jump_kcal'=>['消耗卡路里','卡路里/kcal','#009DFF']];
    
    protected $result_end_data_mould = [
        'name'=>'',
        'value'=>'',
        'unit'=>'',
        'standard'=>'',
        'color'=>'',
        'list'=>[]
    ];
    // 加 bcadd(,,20)
    // 减 bcsub(,,20)
    // 乘 bcmul(,,20)
    // 除 bcdiv(,,20)
    ################################################################接口################################################################
    ################################################################接口################################################################
    ################################################################接口################################################################
    // 手动记录
    public function skip_manual_recording($data = ['aud_id'=>'26','r_time'=>'2024-05-25 10:10:15','num'=>'582','time_m'=>'10','time_s'=>'00','type'=>'free','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }

        if(!array_key_exists('aud_id', $data) || !array_key_exists('r_time', $data) || !array_key_exists('num', $data) || !array_key_exists('time_m', $data) || !array_key_exists('time_s', $data) || !array_key_exists('type', $data) || !array_key_exists('token', $data)){
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        if($this->validate_user_identity($data['aud_id']) === false){
            return $this->msg(10003);
        }
        if(abs($data['time_s']) >= 60){
            return $this->msg(10005);
        }

        return $this->skip_manual_recording_action($data);
    }
    // 今日数据
    public function skip_today_data($data = ['aud_id'=>'26','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('aud_id', $data) || !array_key_exists('token', $data)){
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        // dump($data);
        // die;
        return $this->skip_today_data_action($data);
    }
    // 曲线
    public function skip_curve_chart($data = ['aud_id'=>'26','time'=>'2024-05-25','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('aud_id', $data) || !array_key_exists('time', $data) || !array_key_exists('token', $data)){
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        return $this->skip_curve_chart_action($data);
    }
    // 删除历史数据
    public function skip_del_record_data($data = ['id'=>'16','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('id', $data) || !array_key_exists('token', $data)){
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        $user_data = Db::table('app_card_skip_data')->where(['id'=>$data['id']])->update(['is_del'=>1]);
        if($user_data){
            return $this->msg([]);
        }else{
            return $this->msg(10002);
        }
    }
    ################################################################接口################################################################
    ################################################################接口################################################################
    ################################################################接口################################################################
    ################################################################skip_manual_recording
    public function skip_manual_recording_action($data){
        // 分秒转换为秒
        $data['time'] = abs($data['time_m'])*60+abs($data['time_s']);
        $last_data_body = Db::table('app_card_body_data')->where(['aud_id'=>$data['aud_id']])->order('record_time desc,id desc')->field('id,weight,record_time')->find();
        if(!$last_data_body){
            return $this->msg(10004);
        }
        $data_set = [
            'create_time'=>date('Y-m-d H:i:s'),
            'last_update_time'=>date('Y-m-d H:i:s'),
            'jump_num'=>$data['num'],
            'jump_time'=>$data['time'],
            'jump_kcal'=>$this->skip_kcal_calculate($data['num'],$data['time'],$last_data_body['weight'])['totalCalories'],
            'average_num'=>$this->skip_kcal_calculate($data['num'],$data['time'],$last_data_body['weight'])['averageAchievement'],
            'average_kcal'=>$this->skip_kcal_calculate($data['num'],$data['time'],$last_data_body['weight'])['caloriesPerMinute'],
            'aud_id'=>$data['aud_id'],
            'record_time'=>$data['r_time'],
            'jump_type'=>$data['type']
        ];
        $last_data_body = Db::table('app_card_skip_data')->insert($data_set);
        $result = [
            'today_jump_num'=>0,
            'today_jump_time'=>0,
            'today_jump_kcal'=>0,
        ];
        $all_data = Db::table('app_card_skip_data')->where(['aud_id'=>$data['aud_id']])->whereTime('record_time','today')->field('jump_num,jump_time,jump_kcal')->select();
        foreach ($all_data as $key => $value) {
            $result['today_jump_num'] = $result['today_jump_num']+$value['jump_num'];
            $result['today_jump_time'] = $result['today_jump_time']+$value['jump_time'];
            $result['today_jump_kcal'] = bcadd($result['today_jump_kcal'],$value['jump_kcal'],2);
        }
        $result['last_jump_num'] = $data['num'];
        $result['last_jump_time'] = $data['time'];
        $result['last_jump_kcal'] = $data_set['jump_kcal'];
        $result['last_record_time'] = str_replace('-', '/', $data['r_time']);
        $time_conversion = $this->handle_hour_branch_second($result['today_jump_time']);
        $result['today_jump_time'] = $time_conversion['h'].':'.$time_conversion['m'].':'.$time_conversion['s'];
        $time_conversion = $this->handle_hour_branch_second($result['last_jump_time']);
        $result['last_jump_time'] = $time_conversion['h'].':'.$time_conversion['m'].':'.$time_conversion['s'];
        return $this->msg($result);
    }
    ################################################################skip_today_data
    public function skip_today_data_action($data){
        $all_data = Db::table('app_card_skip_data')->where(['aud_id'=>$data['aud_id']])->whereTime('record_time','today')->field('jump_num,jump_time,jump_kcal')->select();
        $last_data = Db::table('app_card_skip_data')->where(['aud_id'=>$data['aud_id']])->order('record_time desc,id desc')->field('id,jump_num,jump_time,jump_kcal,record_time')->find();
        $result = [
            'today_jump_num'=>0,
            'today_jump_time'=>0,
            'today_jump_kcal'=>0,
        ];
        foreach ($all_data as $key => $value) {
            $result['today_jump_num'] = $result['today_jump_num']+$value['jump_num'];
            $result['today_jump_time'] = $result['today_jump_time']+$value['jump_time'];
            $result['today_jump_kcal'] = bcadd($result['today_jump_kcal'],$value['jump_kcal'],2);
        }
        if($last_data){
            $result['last_jump_num'] = $last_data['jump_num'];
            $result['last_jump_time'] = $last_data['jump_time'];
            $result['last_jump_kcal'] = $last_data['jump_kcal'];
            $result['last_record_time'] = str_replace('-', '/', $last_data['record_time']);
        }else{
            $result['last_jump_num'] = 0;
            $result['last_jump_time'] = 0;
            $result['last_jump_kcal'] = 0;
            $result['last_record_time'] = '';
        }
        $time_conversion = $this->handle_hour_branch_second($result['today_jump_time']);
        $result['today_jump_time'] = $time_conversion['h'].':'.$time_conversion['m'].':'.$time_conversion['s'];
        $time_conversion = $this->handle_hour_branch_second($result['last_jump_time']);
        $result['last_jump_time'] = $time_conversion['h'].':'.$time_conversion['m'].':'.$time_conversion['s'];
        return $this->msg($result);
    }
    ################################################################skip_curve_chart
    // 运动曲线
    public function skip_curve_chart_action($data = ['aud_id'=>'11','time'=>'2024']){
    // public function skip_motion_curve($data = ['aud_id'=>'11','time_data'=>['2024','04']]){
    // public function skip_motion_curve($data = ['aud_id'=>'11','time_data'=>['2024','12','31']]){
        
  
        $audid = $data['aud_id'];  
        $timeData = explode('-', $data['time']);  
  
        // 根据$timeData的长度构建不同的查询条件  
        $map = ['aud_id' => $audid];  
        switch (count($timeData)) {  
            case 3: // 年月日  
                $map['record_time'] = ['between', [date('Y-m-d 00:00:00', strtotime($timeData[0] . '-' . $timeData[1] . '-' . $timeData[2])), date('Y-m-d 23:59:59', strtotime($timeData[0] . '-' . $timeData[1] . '-' . $timeData[2]))]];  
                break;  
            case 2: // 年月  
                $map['record_time'] = ['between', [date('Y-m-01 00:00:00', strtotime($timeData[0] . '-' . $timeData[1])), date('Y-m-t 23:59:59', strtotime($timeData[0] . '-' . $timeData[1]))]];  
                break;  
            case 1: // 年  
                $map['record_time'] = ['between', [date('Y-01-01 00:00:00', strtotime($timeData[0])), date('Y-12-31 23:59:59', strtotime($timeData[0]))]];  
                break;  
            default:  
                return $this->msg(10005); // 无效的时间数据格式  
        }  
  
        // 使用查询构造器进行查询  
        $result = Db::name('app_card_skip_data')->where($map)->field('jump_num,jump_time,jump_kcal,aud_id,record_time,jump_type,DATEPART(hour, record_time) AS hour,DATEPART(day, record_time) AS day,DATEPART(month, record_time) AS month')->order('record_time')->select();
        
        $return_data = [];
        if(count($timeData) == 3){
            $key_condition = 'hour';
        }else if(count($timeData) == 2){
            $key_condition = 'day';
        }else if(count($timeData) == 1){
            $key_condition = 'month';
        }

        foreach ($this->curve_data_format as $key => $value) {
            $temporary_arr['title'] = $value[0];
            $temporary_arr['key'] = $key;
            $temporary_arr['line']['categories'] = [];
            $temporary_arr['line']['series'][0]['color'] = $value[2];
            $temporary_arr['line']['series'][0]['name'] = $value[0];
            $temporary_arr['line']['series'][0]['data'] = [];
            foreach ($result as $k => $v) {
                if($key_condition == 'hour'){
                    if(in_array($result[$k][$key_condition].'时',$temporary_arr['line']['categories'])){
                        $num = array_search($result[$k][$key_condition].'时', $temporary_arr['line']['categories']);
                        $temporary_arr['line']['series'][0]['data'][$num] = bcadd($temporary_arr['line']['series'][0]['data'][$num],$result[$k][$key],2);
                    }else{
                        array_push($temporary_arr['line']['categories'],$result[$k][$key_condition].'时');
                        array_push($temporary_arr['line']['series'][0]['data'],$result[$k][$key]);
                    }
                }else if($key_condition = 'day'){
                    if(in_array($result[$k]['month'].'/'.$result[$k][$key_condition],$temporary_arr['line']['categories'])){
                        $num = array_search($result[$k]['month'].'/'.$result[$k][$key_condition], $temporary_arr['line']['categories']);
                        $temporary_arr['line']['series'][0]['data'][$num] = bcadd($temporary_arr['line']['series'][0]['data'][$num],$result[$k][$key],2);
                    }else{
                        array_push($temporary_arr['line']['categories'],$result[$k]['month'].'/'.$result[$k][$key_condition]);
                        array_push($temporary_arr['line']['series'][0]['data'],$result[$k][$key]);
                    }
                    
                }else{
                    if(in_array($result[$k]['month'].'月',$temporary_arr['line']['categories'])){
                        $num = array_search($result[$k]['month'].'月', $temporary_arr['line']['categories']);
                        $temporary_arr['line']['series'][0]['data'][$num] = bcadd($temporary_arr['line']['series'][0]['data'][$num],$result[$k][$key],2);
                    }else{
                        array_push($temporary_arr['line']['categories'],$result[$k]['month'].'月');
                        array_push($temporary_arr['line']['series'][0]['data'],$result[$k][$key]);
                    }
                }
            }
            // dump($temporary_arr);
            array_push($return_data,$temporary_arr);
        }
        foreach ($return_data[1]['line']['series'][0]['data'] as $key => $value) {
            $return_data[1]['line']['series'][0]['data'][$key] = bcdiv($return_data[1]['line']['series'][0]['data'][$key],60,2);
        }
        return $this->msg($return_data);
    }
    

    ################################################################other################################################################
    ################################################################other################################################################
    ################################################################other################################################################

    // 跳绳卡路里计算
    public function skip_kcal_calculate($num=143, $time=222, $weight=70) {  
        // 加 bcadd(,,20)
        // 减 bcsub(,,20)
        // 乘 bcmul(,,20)
        // 除 bcdiv(,,20)
        // 将时间从秒转换为分钟
        $minutes = bcdiv($time,60,20);
        // 计算每分钟的跳绳次数  
        $jumpsPerMinute = bcdiv($num,$minutes,2); 
        // 根据跳绳次数确定MET值  
        // $met = 11.8;  
        if ($jumpsPerMinute < 100) {  
            $met = 8.8;  
        } else if ($jumpsPerMinute >= 100 && $jumpsPerMinute < 120) {  
            $met = 11.8;  
        } else {  
            $met = 12.3;
        }
        // 计算每分钟燃烧的卡路里
        $caloriesPerMinute = bcdiv(bcmul(bcmul($met,$weight,20),3.5,20),200,2);
        // 计算总卡路里消耗
        $totalCalories = bcmul($caloriesPerMinute,$minutes,2);
        // 返回结果  
        return [  
            'averageAchievement' => $jumpsPerMinute,
            'caloriesPerMinute' => $caloriesPerMinute,
            'totalCalories' => $totalCalories  
        ];  
    }  


}