<?php

declare(strict_types=1);

namespace app\control\controller\exam;

use app\BaseController;
use app\common\model\account\Department;
use app\common\model\account\User as UserModel;
use app\common\model\exam\Knowledge;
use app\common\model\exam\Subject as ModelSubject;
use app\Request;
use think\facade\App;
use think\response\Json;

/**
 * Class Subject
 * @package app\control\controller\exam
 */
class Subject extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/subject/search 科目列表
     * @apiGroup Exam-Subject
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 科目列表
     *
     * @apiParam {Number} [current]  页码
     * @apiParam {Number} [pageSize]  页数
     * @apiParam {String} [title]  科目名称
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","dataSet":[], "total" : 0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function search(Request $request): Json
    {
        $input = $request->post();
        $pageIndex = empty($input['current']) ? 1 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        $total = 0;
        $filters = [];
        if (!empty($input['title'])) {
            $filters['title'] = $input['title'];
        }
        $dataSet = ModelSubject::search($filters, $pageIndex, $pageSize, $total);
        $dataSet = array_map(function ($val) {
            if (!empty($val['watch'])) {
                $val['watch'] = unserialize($val['watch']);
            }
            if (!empty($val['watch']['user'])) {
                $val['watch']['user'] = array_map(
                    function ($v) {
                        $user = UserModel::fetch(intval($v));
                        if (!empty($user)) {
                            $department = Department::fetch($user['department']);
                            $user = [
                                'id' => $user['id'],
                                'uid' => $user['uid'],
                                'name' => $user['name'],
                                'department' => $department['id'],
                                'departmentTitle' => $department['title'],
                            ];
                        }
                        return $user;
                    },
                    $val['watch']['user']
                );
            }
            if (empty($val['watch']['user']) && empty($val['watch']['department'])) {
                $val['watch'] = "";
            }
            return $val;
        }, $dataSet);
        return payload(['dataSet' => $dataSet, 'total' => $total]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/subject/add 科目新增/批量新增
     * @apiGroup Exam-Subject
     * @apiName sort2
     * @apiVersion 1.0.0
     *
     * @apiDescription 科目新增/批量新增
     *
     * @apiParam {String} type  single 单个新增 batch 批量新增
     * @apiParam {String} titles  科目标题 批量新增时用,隔开
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function add(Request $request)
    {
        $input = $request->post();
        if (empty($input['type']) || empty($input['titles'])) {
            return payload(error(-1, '参数不完整'));
        }
        $titles = $input['titles'];
        $data = [
            'title' => $titles,
        ];
        if (!is_array($titles)) {
            $titles = [$titles];
        }
        $check = ModelSubject::check($titles);
        if (!$check) {
            return payload(error(-1, '科目名已存在'));
        }
        $res = ModelSubject::add($input['type'], $data);
        if (!$res) {
            return payload(error(-1, '操作失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/subject/update 科目修改
     * @apiGroup Exam-Subject
     * @apiName sort3
     * @apiVersion 1.0.0
     *
     * @apiDescription 科目修改
     *
     * @apiParam {Number} id  科目id
     * @apiParam {String} title  科目标题
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"", "id" : 1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function modify(Request $request)
    {
        $input = $request->post();
        if (empty($input['id']) || empty($input['title'])) {
            return payload(error(-1, '参数不完整'));
        }
        $data = [
            'title' => $input['title']
        ];
        $check = ModelSubject::check([$input['title']], intval($input['id']));
        if (!$check) {
            return payload(error(-1, '科目名已存在'));
        }
        $res = ModelSubject::update(['id' => $input['id']], $data);
        if (!$res) {
            return payload(error(-1, '操作失败'));
        }
        return payload(['id' => $input['id']]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/subject/watch 科目设置人员
     * @apiGroup Exam-Subject
     * @apiName sort5
     * @apiVersion 1.0.0
     *
     * @apiDescription 科目设置人员
     *
     * @apiParam {Number} id  科目id
     * @apiParam {String[]} watch  查看人员
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"", "id" : 1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function watch(Request $request)
    {
        $input = $request->post();
        if (empty($input['id']) || empty($input['watch'])) {
            return payload(error(-1, '参数不完整'));
        }
        $data = [
            'department' => $input['watch']['department'],
            'user' => $input['watch']['user']
        ];
        $res = ModelSubject::watch(['id' => $input['id']], $data);
        if (!$res) {
            return payload(error(-1, '人员设置失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/subject/delete 科目删除
     * @apiGroup Exam-Subject
     * @apiName sort4
     * @apiVersion 1.0.0
     *
     * @apiDescription 科目删除
     *
     * @apiParam {String} type  single 单删  batch 批量删除
     * @apiParam {String} ids  批量删除用,隔开
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"", "id" : 1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function delete(Request $request)
    {
        $input = $request->post();
        if (empty($input['ids']) || empty($input['type'])) {
            return payload(error(-1, '参数不完整'));
        }
        if ($input['type'] == 'batch') {
            $ids = implode(',', $input['ids']);
            $knowledge = Knowledge::search(['subjectId' => $ids]);
        } else {
            $ids = (string)$input['ids'];
            $knowledge = Knowledge::search(['subjectIds' => $ids]);
        }
        if (!empty($knowledge)) {
            return payload(error(-1, '该科目下有知识点，请先删除知识点'));
        }
        $res = ModelSubject::delete($input['type'], $ids);
        if (!$res) {
            return payload(error(-1, '操作失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     */
    public function import(Request $request)
    {
        $input = $request->post();
        if (empty($input['src'])) {
            return payload(error(-10,'参数不完整'));
        }
        $result = ModelSubject::import(App::getRootPath().'public/'.$input['src']);
        if (!empty($result)) {
            return payload(['dataSet' => ['error' => $result]]);
        }
        return payload();
    }
}