<?php

namespace addons\exam\controller;

use addons\exam\enum\CommonStatus;
use addons\exam\model\PaperModel;
use addons\exam\model\RoomGradeModel;
use addons\exam\model\RoomModel;
use app\admin\model\exam\NoticeModel;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Config;

/**
 * 公共接口
 */
class Common extends Base
{
    protected $noNeedLogin = ['index', 'login'];
    protected $noNeedRight = ['*'];

    /**
     * 读取配置
     */
    public function index()
    {
        $data['system']  = getConfig('system_config');
        $data['page']    = getConfig('page_config');
        $data['ad']      = getConfig('ad_config');
        $data['notice']  = NoticeModel::where('status', CommonStatus::NORMAL)->order('weigh desc')->column('name');
        $data['notices'] = NoticeModel::where('status', CommonStatus::NORMAL)->order('weigh desc')->field('id,name')->limit(5)->select();
        $data['papers']  = $this->indexPaperList();
        $data['rooms']   = $this->indexRoomList();
        // $data['version'] = $this->getAppVersion();
        $this->success('请求成功', $data);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action     = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename   = $this->request->post("filename");
            $method     = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload     = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload     = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 首页试卷列表
     * @return array
     */
    protected function indexPaperList()
    {
        $now    = time();
        $papers = PaperModel::where('status', CommonStatus::NORMAL)
            ->where('is_only_room', 0)
            ->whereRaw("((start_time = 0 and end_time = 0) or (start_time < {$now} and end_time > {$now}))")
            ->order('join_count', 'desc')
            ->limit(6)->select();
        foreach ($papers as &$paper) {
            // 试卷参与人员
            $users = PaperModel::getJoinUsers($paper['id'], -4);
            // 参与人员头像
            $user_avatars = [];
            foreach ($users as $user) {
                $user_avatars[] = [
                    'src' => $user['avatar']
                ];
            }
            $paper['users'] = $user_avatars;
        }

        return $papers;
    }

    /**
     * 首页考场列表
     * @return array
     */
    protected function indexRoomList()
    {
        $rooms = RoomModel::where('status', CommonStatus::NORMAL)->order('grade_count', 'desc')->limit(6)->select();
        foreach ($rooms as &$room) {
            // 考场考试人员
            $users = RoomGradeModel::getJoinUsers($room['id'], -4);
            // 参与人员头像
            $user_avatars = [];
            foreach ($users as $user) {
                $user_avatars[] = [
                    'src' => $user['avatar']
                ];
            }
            $room['users'] = $user_avatars;
        }

        return $rooms;
    }
}