<?php

declare(strict_types=1);

namespace app\control\controller\system;

use app\BaseController;
use app\common\model\book\Chapter;
use app\common\model\book\Volume;
use app\common\model\exam\Subject;
use app\control\model\User;
use mb\helper\Collection;
use think\response\Json;

/**
 * Class Book
 * @package app\control\controller
 */
class Book extends BaseController
{
    /**
     * @return Json
     * @api {post} /book/tree 电子书树状结构
     * @apiGroup Book
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 电子书树状结构
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","dataSet":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function tree()
    {
        $where = [];
        $user = User::fetchCurrent();
        if ($user['role'] != 'root') {
            $subjectIds = Subject::userWatch();
            $where['ids'] = implode(',', $subjectIds);
        }
        $subjects = Subject::search($where, 0);
        $subjects = array_map(function ($s) {
            unset($s['watch']);
            return $s;
        }, $subjects);
        $subjects = Collection::key($subjects, 'id');
        $volumes = Volume::search($where, 0);
        $volumes = Collection::key($volumes, 'id');
        $chapters = Chapter::search($where, 0);
        $newChapters = [];
        foreach ($chapters as $val) {
            $val = [
                'id' => $val['id'],
                'subjectId' => $val['subjectId'],
                'volumeId' => $val['volumeId'],
                'caption' => $val['caption'],
                'type' => 'chapter',
                'volumeTitle' => $val['volumeTitle']
            ];
            $newChapters[$val['volumeId']][] = $val;
        }
        foreach ($newChapters as $k => $val) {
            $volumes[$k]['children'] = $val;
        }
        $newVolume = [];
        foreach ($volumes as $val) {
            $val['type'] = 'volume';
            $newVolume[$val['subjectId']][] = $val;
        }
        foreach ($newVolume as $k => $val) {
            if (isset($subjects[$k])) {
                $subjects[$k]['children'] = $val;
            } else {
                continue;
            }
        }
        $subjects = array_map(function ($row) {
            $row['type'] = 'subject';
            return $row;
        }, $subjects);
        return payload(['dataSet' => array_values($subjects)]);
    }
}