<?php

namespace app\h5\controller;
use app\hander\HelpHander;
use think\Controller;
use think\Db;

class Recorddata extends Controller {
    private $userid;
    private $token;
    public function __construct() {
        parent::__construct();
        $this->token = input('token');
        if (empty($this->token)) {
            $this->lo(url('/h5/index/errorPage'));
        }
        $this->userid = $this->checktoken();
    }
    public function record() {
        $this->assign('token', $this->token);
        return $this->fetch('StaffLearning/record');
    }
    public function recordChart() {
        $days_arr = get_one_month();
        $days = array();
        $days2 = array();
        $times = array();
        foreach ($days_arr as $k => $v) {
            $days[] = date('m-d', strtotime($v));
            $days2[date('m-d', strtotime($v))] = $v;
            $times_list = Db::name('record')
                ->field('SUM(time) as times')
                ->where('user_id', $this->userid)
                ->where('create_yyyymmdd', $v)
                ->find();
            $times[] = empty($times_list['times']) ? 0 : $times_list['times'];
        }
        $data = array(
            'days' => $days,
            'days2' => $days2,
            'times' => $times,
        );
        HelpHander::success($data);
    }
    public function recordList() {
        $day = input('day');
        $where = array();
        if ($day == '') {
            $where[] = ['record.create_yyyymmdd', '=', date('Ymd')];
        }
        else {
            $where[] = ['record.create_yyyymmdd', '=', $day];
        }
        $data = Db::name('record')
            ->field('article.title,record.time,record.create_time,record.create_yyyymmdd')
            ->where($where)
            ->where('record.user_id', $this->userid)
            ->join('article', 'article.id = record.article_id')
            ->select();
        HelpHander::success($data);
    }
    public function lo($url) {
        header("Location: $url");
        exit();
    }
    public function checkToken() {
        $token = input('token');
        if (!$token) {
            $this->lo(url('/h5/index/errorPage'));
        }
        $tokenInfo = Db::name('token')
            ->where('token', $token)
            ->find();
        if (empty($tokenInfo)) {
            $this->lo(url('/h5/index/errorPage'));
        }
        return $tokenInfo['user_id'];
    }
}