<?php

declare(strict_types=1);

namespace app\control\controller\book;

use app\common\model\Base;
use app\common\model\book\Chapter as ModelChapter;
use app\BaseController;
use app\common\model\exam\Subject;
use app\control\model\User;
use app\Request;
use think\facade\App;
use think\response\Json;
use ZipArchive;

/**
 * Class Chapter
 * @package app\control\controller\book
 */
class Chapter extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     * @api {post} /book/chapter/search 电子书节列表
     * @apiGroup Book
     * @apiName sort5
     * @apiVersion 1.0.0
     *
     * @apiDescription 电子书节列表
     *
     * @apiParam {Number} [subjectId]  科目id
     * @apiParam {Number} [volumeId]  章id
     * @apiParam {String} [volumeTitle] 章名称
     * @apiParam {String} [caption] 节名称
     * @apiParam {Number} [current]  页码
     * @apiParam {Number} [pageSize]  页数
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object[]} dataSet 返回数据
     * @apiSuccess {Number} total 记录总数
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"", "dataSet" : [], "total" : 1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function search(Request $request)
    {
        $input = $request->post();
        $pageIndex = empty($input['current']) ? 1 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        $total = 0;
        $filters = [];
        $user = User::fetchCurrent();
        if ($user['role'] != 'root') {
            $subjectIds = Subject::userWatch();
            $filters['ids'] = implode(',', $subjectIds);
        }
        if (!empty($input['caption'])) {
            $filters['caption'] = $input['caption'];
        }
        if (!empty($input['volumeId'])) {
            $filters['volume_id'] = intval($input['volumeId']);
        }
        if (!empty($input['subjectId'])) {
            $filters['subject_id'] = intval($input['subjectId']);
        }
        if (!empty($input['volumeTitle'])) {
            $filters['volume_title'] = trim($input['volumeTitle']);
        }
        $dataSet = ModelChapter::search($filters, $pageIndex, $pageSize, $total);
        return payload(['dataSet' => $dataSet, 'total' => $total]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /book/chapter/add 电子书节新增
     * @apiGroup Book
     * @apiName sort6
     * @apiVersion 1.0.0
     *
     * @apiDescription 电子书节新增
     *
     * @apiParam {Number} subjectId  科目id
     * @apiParam {Number} volumeId  章id
     * @apiParam {String} caption 节名称
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Number} id   节id
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"", "id" : 1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function add(Request $request)
    {
        $input = $request->post();
        if (empty($input['subjectId']) || empty($input['volumeId']) || empty($input['caption'])) {
            return payload(error(-1, '参数不完整'));
        }
        $user = User::fetchCurrent();
        $data = [
            'subject_id' => intval($input['subjectId']),
            'volume_id' => intval($input['volumeId']),
            'caption' => trim($input['caption']),
            'founder' => $user['id']
        ];
        $id = ModelChapter::add($data);
        return payload(['id' => $id]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /book/chapter/modify 电子书节编辑
     * @apiGroup Book
     * @apiName sort7
     * @apiVersion 1.0.0
     *
     * @apiDescription 电子书节编辑
     *
     * @apiParam {Number} id 节id
     * @apiParam {String} [caption] 节名称
     * @apiParam {String} [content] 节内容
     * @apiParam {String[]} [source] 节附件
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function modify(Request $request)
    {
        $input = $request->post();
        $data = [];
        if (!empty($input['caption'])) {
            $data['caption'] = trim($input['caption']);
        }
        if (!empty($input['content'])) {
            $data['content'] = $input['content'];
        }
        if (!empty($input['source'])) {
            $data['source'] = serialize($input['source']);
        }
        if (empty($input['id']) || empty($data)) {
            return payload(error(-1, '参数不完整'));
        }
        $check = ModelChapter::check(intval($input['id']));
        if (!$check) {
            return payload(error(-1, '暂无权限操作'));
        }
        $res = ModelChapter::modify(['id' => intval($input['id'])], $data);
        if (!$res) {
            return payload(error(-1, '操作失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /book/chapter/delete 电子书节删除
     * @apiGroup Book
     * @apiName sort8
     * @apiVersion 1.0.0
     *
     * @apiDescription 电子书节删除
     *
     * @apiParam {Number} id 节id
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function delete(Request $request)
    {
        $input = $request->post();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $res = ModelChapter::delete(['id' => intval($input['id'])]);
        if (!$res) {
            return payload(error(-1, '操作失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /book/chapter/addView 章节点击量更新
     * @apiGroup Book
     * @apiName  sort9
     * @apiVersion 1.0.0
     *
     * @apiDescription 章节点击量更新
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function addView(Request $request)
    {
        $input = $request->post();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $res = Base::addView('chapter', intval($input['id']));
        if (!$res) {
            return payload(error(-1, '更新失败'));
        }
        return payload();
    }

    public function export(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-10, '参数不完整'));
        }
        $check = ModelChapter::check(intval($input['id']));
        if (!$check) {
            return payload(error(-1, '暂无权限操作'));
        }
        $chapterInfo = ModelChapter::fetch(intval($input['id']));
        $zip = new ZipArchive();
        $fileList = [];
        if (empty($chapterInfo['source'])) {
            return payload(error(-20,'无可供下载文件'));
        }
        foreach ($chapterInfo['source'] as $v) {
            $fileList[] = $v;
        }
        $filename = App::getRootPath() . 'public/file/'."{$input['id']}.zip";
        $zip->open($filename,1);   //打开压缩包
        foreach($fileList as $file){
            $zip->addFile($file,basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        header("location:{$request->domain()}/file/{$input['id']}.zip");exit;
    }
}