<?php

namespace app\app\controller;

use think\Controller;
use think\Db;
use app\bj\controller\Common;
use think\Log;
use \think\Validate;

class Index extends Base{
    
    protected $db_name = ['2'=>'app_card_body_data','6'=>'app_card_skip_data','8'=>'app_card_vitalcapacity_data'];
    // protected $card_key = ['2'=>'body','6'=>'skip','8'=>'vitalcapacity'];
    protected $card_data = [
        '2'=>['身体数据','body',['height'=>['身高','cm'],'weight'=>['体重','公斤'],'bmi'=>['BMI','无']]],
        // 'skip'=>['跳绳数据',['height,weight,bmi,record_time']],
        '8'=>['肺活量','vitalcapacity',['average'=>['本次数据','ml']]],
    ];
    
    protected $data_name_unit = [
        'height'=>['身高','cm','pc_heightstand2'],
        'weight'=>['体重','公斤','pc_weightstand2'],
        'bmi'=>['BMI','','pc_bmistand2'],
        'average'=>['肺活量','ml','pc_vitalcapacity_standard']
    ];

    protected $grade_list = [
        ['id'=>'nothing','name'=>'无'],
        ['id'=>'grade_s_1','name'=>'小学一年级'],
        ['id'=>'grade_s_2','name'=>'小学二年级'],
        ['id'=>'grade_s_3','name'=>'小学三年级'],
        ['id'=>'grade_s_4','name'=>'小学四年级'],
        ['id'=>'grade_s_5','name'=>'小学五年级'],
        ['id'=>'grade_s_6','name'=>'小学六年级'],
        ['id'=>'grade_m_1','name'=>'初中一年级'],
        ['id'=>'grade_m_2','name'=>'初中二年级'],
        ['id'=>'grade_m_3','name'=>'初中三年级'],
        ['id'=>'grade_h_1','name'=>'高中一年级'],
        ['id'=>'grade_h_2','name'=>'高中二年级'],
        ['id'=>'grade_h_3','name'=>'高中三年级'],
        ['id'=>'grade_u_12','name'=>'大学一、二年级'],
        ['id'=>'grade_u_34','name'=>'大学三、四年级']
    ];
    
    ################################################################个人资料卡################################################################
    ################################################################个人资料卡################################################################
    ################################################################个人资料卡################################################################

    // // 个人信息
    // public function personal_information(){
    //     // phpinfo();
    //     dump(123);
    //     $result = Db::table('admin_user')->select();
    //     dump($result);
    // }
    // 创建用户
    public function create_user_data($data = ['aan_id'=>66,'nickname'=>'王小二','birthday'=>'2019-01-01','gender'=>1,'grade'=>'二年级','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('token', $data)){ 
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        $verify_result = $this->verify_parameters($data,'register');
        if(!is_array($verify_result)){
            return $this->msg(10001,$verify_result);
        }
        $result = Db::table('app_user_data')->insert($verify_result);
        if($result){
            return $this->msg([]);
        }else{
            return $this->msg(10002);
        }
    }

    // 获取账号下用户列表
    // $type  1获取列表，2获取详细信息
    public function get_user_card_list($data = ['aan_id'=>66,'type'=>1,'token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('token', $data) || !array_key_exists('aan_id', $data) || !array_key_exists('type', $data)){ 
            return $this->msg(10001);
        }
        
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        $result = Db::table('app_user_data')->where(['aan_id'=>$data['aan_id']])->select();
        // $result = Db::table('app_user_data')->where(['aan_id'=>$aan_id])->field('id,nickname')->select();
        $temporary_data = [];
        if($data['type'] == 1){
            for ($i=0; $i < count($result); $i++) { 
                array_push($temporary_data,['id'=>$result[$i]['id'],'nickname'=>$result[$i]['nickname']]);
            }
        }else{
            $temporary_data = $result;
        }
        return $this->msg($temporary_data);
    }

    // 获取指定用户详细信息
    public function get_user_data_information($data = ['aud_id'=>26,'token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        // dump(input('post.'));
        // dump(input('get.'));
        // // dump($data);
        // die;
        if(!array_key_exists('token', $data) || !array_key_exists('aud_id', $data)){ 
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        unset($data['token']);
        $result = Db::table('app_user_data')->where(['id'=>$data['aud_id']])->field('id,aan_id,nickname,head_pic,birthday,gender,card_order,target_weight,initial_weight,initial_date')->find();
        if(!$result){
            return $this->msg(10003);
        }
        unset($result['ROW_NUMBER']);
        $result['age'] = $this->calculate_age($result['birthday']);
        if($result['card_order'] === ''){
            $result['card_order'] = [];
            $result['card_data_list'] = [];
            $result['target_current'] = $this->base_target_initial_cumulative_weight([]);
            
        }else{
            $result['card_order'] = explode(',',$result['card_order']);
            $calculation_results = $this->get_user_card_data_list($result,$result['id']);
            // dump($calculation_results);
            // die;
            $result['card_data_list'] = $calculation_results[0];
            $result['target_current'] = $calculation_results[1];
        }
        // base_target_initial_cumulative_weight
        // dump($result);
        // die;
        $result['birthday'] = str_replace('-', '/', $result['birthday']);
        foreach ($result['card_data_list'] as $key => $value) {
            // dump($key);
            if($key == 'record_time' && $value != ''){
                // dump(111);
                $result['card_data_list'][$key] = str_replace('-', '/', $result['card_data_list'][$key]);
            }
        }
        unset($result['target_weight']);
        unset($result['initial_weight']);
        unset($result['initial_date']);
        // dump($result);
        // die;
        return $this->msg($result);
    }

    // 获取所有卡片列表信息
    public function get_card_all_list($data = ['aud_id'=>11,'token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!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_card_list = Db::table('app_user_data')->where(['id'=>$data['aud_id']])->field('id,card_order')->find();
        if(!$user_card_list){
            return $this->msg(10003);
        }
        unset($user_card_list['ROW_NUMBER']);
        $user_card_list['card_order'] = explode(',',$user_card_list['card_order']);
        $all_card_list = Db::table('app_card_data')->field('id,name')->select();
        // dump($user_card_list);
        // dump($all_card_list);
        $result = ['user'=>[],'all'=>[]];
        foreach ($all_card_list as $key => $value) {
            if(in_array($value['id'],$user_card_list['card_order'])){
                $result['user'][array_search($value['id'], $user_card_list['card_order'])] = ['id'=>$value['id'],'name'=>$value['name']];
            }else{
                array_push($result['all'],['id'=>$value['id'],'name'=>$value['name']]);
            }
        }
        ksort($result['user']);
        return $this->msg($result);
    }

    // 保存用户的卡片排序
    public function save_user_card_order($data=['aud_id'=>11,'card_order'=>'2,8','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('aud_id', $data) || !array_key_exists('card_order', $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->is_num_array(explode(',',$data['card_order']))){
            return $this->msg(10001,'数据内参数格式或值错误');
        }
        $result = Db::table('app_user_data')->where(['id'=>$data['aud_id']])->update(['card_order'=>$data['card_order']]);
        if($result){
            return $this->msg([]);
        }else{
            return $this->msg(10002);
        }
        
    }

    public function get_grade_list(){
        $data = input('post.');
        if(!array_key_exists('token', $data)){ 
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        return $this->msg($this->grade_list);
    }
    

    ################################获取账号下信息操作################################

    // 获取账号下首页卡片的基础数据
    public function get_user_card_data_list($data,$aud_id){
        
        $result = [];
        $db_arr = [];
        foreach ($data['card_order'] as $key => $value) {
            $db_arr[$value] =  Db::table($this->db_name[$value])->where(['aud_id'=>$aud_id,'is_del'=>'0'])->order('id desc')->limit(1)->select();
            // dump($db_arr[$value]);
            
            if(count($db_arr[$value]) > 0){
                $db_arr[$value] = $db_arr[$value][0];
            }else{
                unset($db_arr[$value]);
            }
        }

        // dump($db_arr);
        // die;
        // 添加目标体重于当前体重差数据
        if(array_key_exists('2', $db_arr)){
            $target_current = $this->base_target_initial_cumulative_weight([
                'weight'=>$db_arr['2']['weight']>0?$db_arr['2']['weight']:0,
                'target_weight'=>$data['target_weight']>0?$data['target_weight']:0,
                'initial_weight'=>$data['initial_weight']>0?$data['initial_weight']:0,
                'initial_date'=>$data['initial_date']!=null?$data['initial_date']:0,
            ]);
        }else{
            $target_current = $this->base_target_initial_cumulative_weight([
                'weight'=>0,
                'target_weight'=>$data['target_weight']>0?$data['target_weight']:0,
                'initial_weight'=>$data['initial_weight']>0?$data['initial_weight']:0,
                'initial_date'=>$data['initial_date']!=null?$data['initial_date']:0,
            ]);
        }
        if(count($db_arr) <= 0){
            // 没有数据，传递一个空的卡片
            // $
            return [
                [[
                    'id'=>'',
                    'acd_id'=>'2',
                    'record_time'=>'',
                    'card_name'=>'身体数据',
                    'card_key'=>'body',
                    'inside_data'=>[
                        [
                            'key'=>'',
                            'name'=>'身高',
                            'value'=>'',
                            'unit'=>'cm',
                            'standard'=>'',
                            'color'=>'',
                        ],
                        [
                            'key'=>'',
                            'name'=>'体重',
                            'value'=>'',
                            'unit'=>'公斤',
                            'standard'=>'',
                            'color'=>'',
                        ],
                        [
                            'key'=>'',
                            'name'=>'BMI',
                            'value'=>'',
                            'unit'=>'',
                            'standard'=>'',
                            'color'=>'',
                        ],
                    ]
                ]],
                $target_current
            ];
        }
        // dump($db_arr);
        // die;
        foreach ($db_arr as $key => $value) {
            $temporary_arr = [];
            $temporary_arr['id'] = $value['id'];
            $temporary_arr['acd_id'] = $value['acd_id'];
            $temporary_arr['record_time'] = $value['record_time'];
            // $temporary_arr['value'] = $value['record_time'];
            $temporary_arr['card_name'] = $this->card_data[$value['acd_id']][0];
            $temporary_arr['card_key'] = $this->card_data[$value['acd_id']][1];
            $temporary_arr['inside_data'] = [];
            if(array_key_exists($value['acd_id'],$this->card_data)){
                
                foreach ($this->card_data[$value['acd_id']][2] as $k => $v) {
                    $tem_arr_2 = explode(',', $db_arr[$key][$k."_data"]);
                    array_push($temporary_arr['inside_data'],[
                        'key'=>$k,
                        'name'=>$v[0],
                        'value'=>$tem_arr_2[0],
                        'unit'=>$v[1]!='无'?$v[1]:'',
                        'standard'=>$tem_arr_2[1]!='无'?$tem_arr_2[1]:'',
                        'color'=>$tem_arr_2[2]!='无'?$tem_arr_2[2]:''
                    ]);
                }
            }
            array_push($result,$temporary_arr);
        }
        // dump($result);
        // die;
        return [$result,$target_current];
    }



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

    public function verify_parameters($data,$type){
        // 设置验证
        $rule = [
            'aan_id'  => 'require|number',
            'nickname'   => 'require|chsAlpha',
            'birthday' => 'require|date',
            'gender' => 'require|number|in:0,1,2',
            'grade' => 'require',
        ];
        $msg = [
            'aan_id.require' => '账号信息缺失',
            'nickname.require' => '昵称缺失',
            'birthday.require' => '生日缺失',
            'gender.require' => '性别缺失',
            'grade.require' => '年级缺失',

            'aan_id.number'   => '账号信息格式错误',
            'nickname.chsAlpha'   => '昵称只能是只能是汉字、字母',
            'birthday.date'  => '生日信息格式错误',
            'gender.number'  => '性别格式错误',
            'gender.in'  => '性别信息错误',
        ];
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return $validate->getError();
        }
        
        $parameter['aan_id'] = $data['aan_id'];
        $parameter['nickname'] = $data['nickname'];
        $parameter['birthday'] = $data['birthday'];
        $parameter['gender'] = $data['gender'];
        $parameter['grade'] = $data['grade'];
        $parameter['card_order'] = '2,8';
        $parameter['create_time'] = date('Y-m-d H:i:s');
        $parameter['last_update_time'] = date('Y-m-d H:i:s');
        $parameter_pd = Db::table('app_account_number')->where(['id'=>$parameter['aan_id']])->count();
        if($parameter_pd <= 0){
            return '该账户不存在';
        }
        $result =  Db::table('app_user_data')->where(['nickname'=>$parameter['nickname'],'aan_id'=>$parameter['aan_id']])->count();
        if($result>0){
            return '该成员已存在';
        }
        
        return $parameter;
    }

    
    


}