<?php

declare(strict_types=1);

namespace app\control\controller\exam;

use app\BaseController;
use app\common\model\account\Department;
use app\common\model\account\Duty;
use app\common\model\Base;
use app\common\model\exam\Knowledge;
use app\common\model\core\Excel;
use app\common\model\exam\Paper;
use app\common\model\exam\paper\Record;
use app\common\model\exam\Question;
use app\Request;
use mb\helper\Collection;
use think\Exception;
use think\response\Json;

/**
 * Class Score
 * @package app\control\controller\exam
 */
class Score extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     * @api {post} /exam/score/search 成绩管理
     * @apiGroup Exam-score
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 成绩管理
     *
     * @apiParam {String} type 考试类型<br>competition -- 竞赛级别<br>promote -- 提升级<br>beginner -- 入门级<br>simulate -- 模拟考
     * @apiParam {Number} [current]  页码
     * @apiParam {Number} [pageSize]  页数
     *
     * @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)
    {
        $input = $request->post();
        $pageIndex = empty($input['current']) ? 1 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        $total = 0;
        $filters = [];
//        $type = empty($input['type']) ? 'competition' : $input['type'];
//        $filters['type'] = $type;
        if (!empty($input['title'])) {
            $filters['title'] = $input['title'];
        }
        if (!empty($input['timeStart'])) {
            $filters['timeStart'] = $input['timeStart'];
        }
        if (!empty($input['timeEnd'])) {
            $filters['timeEnd'] = $input['timeEnd'];
        }
        $dataSet = Paper::search($filters, $pageIndex, $pageSize, $total);
        $dataSet = array_map(
            function ($val) {
                $val['avg'] = Record::score(['paper' => $val['id']], 'avg');
                unset($val['questionType']);
                return $val;
            },
            $dataSet
        );
        return payload(['dataSet' => $dataSet, 'total' => $total]);
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /exam/score/scoreDetail 成绩列表
     * @apiGroup Exam-score
     * @apiName sort2
     * @apiVersion 1.0.0
     *
     * @apiDescription 成绩列表
     *
     * @apiParam {Number} id  试卷id
     * @apiParam {Number} [current]  页码
     * @apiParam {Number} [pageSize]  页数
     * @apiParam {Number} [export]  是否导出 1 - 导出
     * @apiParam {Number} [fields]  导出字段 id,uid,pass,score,gender,department,duty,name
     *
     * @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 scoreDetail(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $pageIndex = empty($input['current']) ? 1 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        if (!empty($input['export'])) {
            $pageIndex = 1;
            $pageSize = 99999999;
        }
        $total = 0;
        $filters = [];
        $filters['paperId'] = intval($input['id']);
        $filters['status'] = 'end';
        $departmentId = !empty($input['departmentId']) ? $input['departmentId'] : 0;
        if (!empty($input['departmentId'])) {
            $filters['departmentId'] = intval($input['departmentId']);
        }
        if (!empty($input['uid'])) {
            $filters['uid'] = $input['uid'];
        }
        if (!empty($input['name'])) {
            $filters['name'] = $input['name'];
        }
        if (!empty($input['dutyId'])) {
            $filters['dutyId'] = intval($input['dutyId']);
        }
        if (
            !empty($input['symbol']) && !empty($input['score'])
            && (in_array($input['symbol'], ['<', '<=', '=', '>=', '>']))
        ) {
            $filters['symbol'] = $input['symbol'];
            $filters['score'] = $input['score'];
        }
        $paper = Paper::fetch(intval($input['id']));
        $throughPoints = $paper['through_points']; //通过分数
        $avg = Record::score(['paper' => intval($input['id']), 'department' => $departmentId], 'avg');
        $max = Record::score(['paper' => intval($input['id']), 'department' => $departmentId], 'max');
        $min = Record::score(['paper' => intval($input['id']), 'department' => $departmentId], 'min');
        $passNum = Record::examPass(['paper' => intval($input['id']), 'department' => $departmentId]); // 通过人数
        $dataSet = Record::search($filters, $pageIndex, $pageSize, $total);
        foreach ($dataSet as &$item) {
            if ($item['score'] > $throughPoints) {
                $item['pass'] = true;
            } else {
                $item['pass'] = false;
            }
            $department = Department::fetch($item['department']);
            if (!empty($department['title'])) {
                $item['department'] = $department['title'];
            } else {
                $item['department'] = '';
            }
            $duty = Duty::fetch($item['duty']);
            if (!empty($duty['title'])) {
                $item['duty'] = $duty['title'];
            } else {
                $item['duty'] = '';
            }
            unset($item['result'], $item['question']);
        }
        $passPoint = 0;
        if (($passNum != 0) && ($total != 0)) {
            $passPoint = sprintf("%.2f", ($passNum / $total) * 100);
        }
        if (!empty($input['export'])) {
            $excelData = [];
            foreach ($dataSet as $v) {
                $v[''] = '';
                $v['pass'] = empty($v['pass']) ? '未通过' : '通过';
                $v['gender'] = (!empty($v['gender']) && $v['gender'] = 1) ? '男' : '女';
                if (!empty($excelData[$v['userId']])) {
                    if ($excelData[$v['userId']]['score'] < $v['score']) {
                        $excelData[$v['userId']] = $v;
                    }
                } else {
                    $excelData[$v['userId']] = $v;
                }
            }
            $input['fields'] = ',' . $input['fields'] . ',company,pass';
            self::export($excelData, $input, Record::EXPORT_FIELDS);
            exit;
        }
        return payload(
            [
                'dataSet' => $dataSet,
                'total' => $total,
                'passNum' => $passNum,
                'avg' => $avg,
                'max' => $max,
                'min' => $min,
                'passPoint' => $passPoint
            ]
        );
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /exam/score/knowledge 知识点
     * @apiGroup Exam-score
     * @apiName sort3
     * @apiVersion 1.0.0
     *
     * @apiDescription 知识点
     *
     * @apiParam {Number} id  试卷id
     * @apiParam {Number} [export]  是否导出 1 - 导出
     *
     * @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 knowledge(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $paper = Paper::fetch(intval($input['id']));
        $filters = [];
        $filters['paperId'] = intval($input['id']);
        $filters['status'] = 'end';
        $total = 0;
        $records = Record::search($filters, 0, 0, $total);
        $strategies = unserialize($paper['strategies']);
        $questionType = unserialize($paper['question_type']);
        $questionType = array_map(
            function ($q) {
                $q = $q['point'];
                return $q;
            },
            $questionType
        ); //题型对应分值
        $knowledge = [];
        foreach ($strategies as $val) {
            $knowledge[$val['knowledge']][] = $val;
        }
        $newKnowledge = [];
        foreach ($knowledge as $k) {
            if (!isset($newKnowledge[$k[0]['knowledge']])) {
                $newKnowledge[$k[0]['knowledge']] = [
                    'knowledge' => $k[0]['knowledge'],
                    'subject' => $k[0]['subject'],
                    'knowledgeTitle' => $k[0]['knowledgeTitle'],
                    'subjectTitle' => $k[0]['subjectTitle'],
                    'num' => 0,
                    'score' => 0,
                    'point' => 0
                ];
                foreach ($k as $v) {
                    if ($paper['mode'] == 'hand') {
                        $num = count($v['strategy']);
                    } else {
                        $num = array_sum($v['strategy']);
                    }
                    $newKnowledge[$k[0]['knowledge']]['num'] += $num;
                    $score = $num * $questionType[$v['type']];
                    $newKnowledge[$k[0]['knowledge']]['score'] += $score;
                }
            }
        }
        if ($total == 0) {
            if (!empty($input['export'])) {
                $newKnowledge = array_map(
                    function ($last) {
                        $last['point'] .= "%";
                        return $last;
                    },
                    $newKnowledge
                );
                $input['fields'] = implode(',', Base::exchangeKey(Knowledge::EXPORT_FIELDS));
                self::export($newKnowledge, $input, Knowledge::EXPORT_FIELDS, '知识点统计');
                exit;
            }
            return payload(['dataSet' => array_values($newKnowledge)]);
        }
        $records = array_map(
            function ($r) {
                $r = unserialize($r['result']);
                $arr = [];
                foreach ($r as $value) {
                    $arr = array_merge($arr, $value);
                }
                return $arr;
            },
            $records
        ); //所有考卷的结果
        $recordPoint = []; //所有考卷每个知识点的题目数量和正确数量
        foreach ($records as $k => $rec) {
            if (!isset($recordPoint[$k])) {
                $recordPoint[$k] = [];
            }
            foreach ($rec as $know) {
                if (!isset($recordPoint[$k][$know['knowledge']])) {
                    $recordPoint[$k][$know['knowledge']] = ['num' => 0, 'pass' => 0];
                }
                if ($know['score'] > 0) {
                    $recordPoint[$k][$know['knowledge']]['pass']++;
                }
                $recordPoint[$k][$know['knowledge']]['num']++;
            }
        }
        $recordPoint = array_map(
            function ($r) {
                $r = array_map(
                    function ($p) {
                        $p['point'] = sprintf("%.2f", $p['pass'] / $p['num']) * 100;
                        return $p;
                    },
                    $r
                );
                return $r;
            },
            $recordPoint
        );
        $knowledgePoints = [];
        foreach ($recordPoint as $point) {
            foreach ($point as $key => $res) {
                if (!isset($knowledgePoints[$key])) {
                    $knowledgePoints[$key] = 0;
                }
                $knowledgePoints[$key] += $res['point'];
            }
        }
        $newKnowledge = array_map(
            function ($last) use ($knowledgePoints, $total) {
                $last['point'] = sprintf("%.1f", $knowledgePoints[$last['knowledge']] / $total);
                return $last;
            },
            $newKnowledge
        );
        if (!empty($input['export'])) {
            $newKnowledge = array_map(
                function ($last) {
                    $last['point'] .= "%";
                    return $last;
                },
                $newKnowledge
            );
            $input['fields'] = implode(',', Base::exchangeKey(Knowledge::EXPORT_FIELDS));
            self::export($newKnowledge, $input, Knowledge::EXPORT_FIELDS, '知识点统计');
            exit;
        }
        return payload(['dataSet' => array_values($newKnowledge)]);
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /exam/score/type 题型
     * @apiGroup Exam-score
     * @apiName sort4
     * @apiVersion 1.0.0
     *
     * @apiDescription 题型
     *
     * @apiParam {Number} id  试卷id
     *
     * @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 type(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $paper = Paper::fetch(intval($input['id']));
        $filters = [];
        $filters['paperId'] = intval($input['id']);
        $filters['status'] = 'end';
        $total = 0;
        $records = Record::search($filters, 0, 0, $total);
        $questionType = unserialize($paper['question_type']);
        $questionType = array_map(
            function ($q) {
                $q = [
                    'type' => $q['type'],
                    'point' => $q['point'],
                    'questionNum' => $q['questionNum'],
                    'score' => $q['point'] * $q['questionNum'],
                    'avg' => 0,
                    'percent' => 0
                ];
                return $q;
            },
            $questionType
        ); //题型对应分值
        if ($total == 0) {
            if (!empty($input['export'])) {
                $questionType = array_map(
                    function ($item) {
                        $item['type'] = empty(Question::TYPE[$item['type']]) ? '' : Question::TYPE[$item['type']];
                        $item['percent'] .= "%";
                        return $item;
                    },
                    $questionType
                );
                $input['fields'] = implode(',', Base::exchangeKey(Question::EXPORT_TYPE_FIELDS));
                self::export($questionType, $input, Question::EXPORT_TYPE_FIELDS, '题型统计');
                exit;
            }
            return payload(['dataSet' => array_values($questionType)]);
        }
        $records = array_map(
            function ($rec) {
                $rec = unserialize($rec['result']);
                return $rec;
            },
            $records
        );
        $typeRecord = [];
        foreach ($records as $key => $val) {
            if (!isset($typeRecord[$key])) {
                $typeRecord[$key] = [];
            }
            foreach ($val as $k => $t) {
                if (!isset($typeRecord[$key][$k])) {
                    $typeRecord[$key][$k] = ['type' => $k, 'pass' => 0];
                }
                foreach ($t as $item) {
                    if ($item['score'] > 0) {
                        $typeRecord[$key][$k]['pass']++;
                    }
                }
            }
        }
        $typeRecord = array_map(
            function ($rec) use ($questionType) {
                $rec = array_map(
                    function ($t) use ($questionType) {
                        $t['score'] = $questionType[$t['type']]['point'] * $t['pass'];
                        $t['percent'] = sprintf('%.1f', $t['pass'] / $questionType[$t['type']]['questionNum']) * 100;
                        unset($t['pass']);
                        return $t;
                    },
                    $rec
                );
                return $rec;
            },
            $typeRecord
        );
        $type = array_keys($questionType);
        $res = [];
        foreach ($type as $val) {
            if (!isset($res[$val])) {
                $res[$val] = ['score' => 0, 'percent' => 0];
            }
        }
        foreach ($typeRecord as $r) {
            foreach ($r as $spec) {
                $res[$spec['type']]['score'] += $spec['score'];
                $res[$spec['type']]['percent'] += $spec['percent'];
            }
        }
        $questionType = array_map(
            function ($last) use ($total, $res) {
                $last['avg'] = sprintf('%.1f', $res[$last['type']]['score'] / $total);
                $last['percent'] = sprintf('%.1f', $res[$last['type']]['percent'] / $total);
                unset($last['point']);
                return $last;
            },
            $questionType
        );
        //判断是否导出
        if (!empty($input['export'])) {
            $questionType = array_map(
                function ($item) {
                    $item['type'] = empty(Question::TYPE[$item['type']]) ? '' : Question::TYPE[$item['type']];
                    $item['percent'] .= "%";
                    return $item;
                },
                $questionType
            );
            $input['fields'] = implode(',', Base::exchangeKey(Question::EXPORT_TYPE_FIELDS));
            self::export($questionType, $input, Question::EXPORT_TYPE_FIELDS, '题型统计');
            exit;
        }
        return payload(['dataSet' => array_values($questionType)]);
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /exam/score/question 试题
     * @apiGroup Exam-score
     * @apiName sort5
     * @apiVersion 1.0.0
     *
     * @apiDescription 试题
     *
     * @apiParam {Number} id  试卷id
     * @apiParam {bool} [export]  true 导出
     * @apiParam {bool} [fields]  导出字段 type,name,answer,percent,A,B,C,D,E,F
     *
     * @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 question(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $paper = Paper::fetch(intval($input['id']));
        $filters = [];
        $filters['paperId'] = intval($input['id']);
        $filters['status'] = 'end';
        $total = 0;
        $records = Record::search($filters, 0, 0, $total);
        $questionIds = [];
        if (($paper['way'] == 'question') && empty($total)) {
            return payload(['dataSet' => []]);
        }
        if ($paper['way'] != 'question') { //题序固定、题序随机
            $questions = unserialize($paper['question']);
            foreach ($questions as $v) {
                $questionIds = array_merge($questionIds, $v);
            }
        } else { //试题随机
            $recordsQuestion = array_map(
                function ($r) {
                    $tmp = [];
                    $r = unserialize($r['question']);
                    foreach ($r as $item) {
                        $tmp = array_merge($tmp, $item);
                    }
                    return $tmp;
                },
                $records
            );
            foreach ($recordsQuestion as $req) {
                $questionIds = array_merge($questionIds, $req);
            }
        }
        $questionArr = Question::search(['ids' => $questionIds], 0);
        $questionArr = Collection::key($questionArr, 'id');
        $dataSet = array_map(
            function ($val) {
                $val = Collection::elements(['name', 'type', 'answer'], $val);
                $val['pass'] = 0;
                $val['percent'] = 0;
                $val['show'] = 0;
                $val['A'] = 0;
                $val['B'] = 0;
                $val['C'] = 0;
                $val['D'] = 0;
                $val['E'] = 0;
                $val['F'] = 0;
                return $val;
            },
            $questionArr
        ); //最后返回数据
        $records = array_map(
            function ($row) {
                $row = unserialize($row['result']);
                return $row;
            },
            $records
        );
        foreach ($records as $num) {
            foreach ($num as $t => $val) {
                foreach ($val as $que) {
                    if (!isset($dataSet[$que['id']])) {
                        continue;
                    }
                    $dataSet[$que['id']]['show']++;
                    if ($que['score'] > 0) {
                        $dataSet[$que['id']]['pass']++;
                    }
                    if (in_array($t, ['choices', 'choice'])) {
                        if ($t == 'choices') {
                            if (!empty($que['answer'])) {
                                foreach ($que['answer'] as $v) {
                                    $dataSet[$que['id']][$v]++;
                                }
                            }
                        } elseif (!empty($que['answer'])) {
                            $dataSet[$que['id']][$que['answer']]++;
                        }
                    }
                }
            }
        }
        $choice = [];
        $choices = [];
        foreach ($dataSet as $k => &$last) {
            if (!empty($last['show'])) {
                $last['percent'] = sprintf('%.1f', $last['pass'] / $last['show']) * 100;
            }
            unset($last['pass']);
            if (in_array($last['type'], ['choices', 'choice'])) {
                if (!empty($last['show'])) {
                    $last['A'] = sprintf('%.1f', $last['A'] / $last['show']) * 100;
                    $last['B'] = sprintf('%.1f', $last['B'] / $last['show']) * 100;
                    $last['C'] = sprintf('%.1f', $last['C'] / $last['show']) * 100;
                    $last['D'] = sprintf('%.1f', $last['D'] / $last['show']) * 100;
                    $last['E'] = sprintf('%.1f', $last['E'] / $last['show']) * 100;
                    $last['F'] = sprintf('%.1f', $last['F'] / $last['show']) * 100;
                }
                if ($last['type'] == 'choices') {
                    array_push($choices, $last);
                } else {
                    array_push($choice, $last);
                }
                unset($dataSet[$k]);
            }
        }
        $newDataSet = array_merge(array_values($choice), array_values($choices), array_values($dataSet));
        //判断是否导出
        if (!empty($input['export'])) {
            $input['fields'] = implode(',', Base::exchangeKey(Question::EXPORT_FIELDS));
            $newDataSet = array_map(
                function ($item) {
                    $item['type'] = empty(Question::TYPE[$item['type']]) ? '' : Question::TYPE[$item['type']];
                    if (is_array($item['answer'])) {
                        $item['answer'] = implode('', $item['answer']);
                    }
                    if ($item['type'] == Question::TYPE['judge']) {
                        $item['answer'] = empty($item['answer']) ? '错' : '对';
                    }
                    return $item;
                },
                $newDataSet
            );
            self::export($newDataSet, $input, Question::EXPORT_FIELDS);
            exit;
        }
        return payload(['dataSet' => $newDataSet]);
    }


    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     */
    public function questions(Request $request)
    {
        $input = $request->param();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $paper = Paper::fetch(intval($input['id']));
        $filters = [];
        $filters['paperId'] = intval($input['id']);
        $filters['status'] = 'end';
        $total = 0;
        $records = Record::search($filters, 0, 0, $total);
        $questionIds = [];
        if (($paper['way'] == 'question') && empty($total)) {
            return payload(['dataSet' => []]);
        }
        if ($paper['way'] != 'question') { //题序固定、题序随机
            $questions = unserialize($paper['question']);
            foreach ($questions as $v) {
                $questionIds = array_merge($questionIds, $v);
            }
        } else { //试题随机
            $recordsQuestion = array_map(
                function ($r) {
                    $tmp = [];
                    $r = unserialize($r['question']);
                    foreach ($r as $item) {
                        $tmp = array_merge($tmp, $item);
                    }
                    return $tmp;
                },
                $records
            );
            foreach ($recordsQuestion as $req) {
                $questionIds = array_merge($questionIds, $req);
            }
        }
        $questionArr = Question::search(['ids' => $questionIds], 0);
        $questionArr = Collection::key($questionArr, 'id');
        $dataSet = array_map(
            function ($val) {
                $val = Collection::elements(['name', 'type', 'answer'], $val);
                $val['pass'] = 0;
                $val['percent'] = 0;
                $val['show'] = 0;
                $val['A'] = 0;
                $val['B'] = 0;
                $val['C'] = 0;
                $val['D'] = 0;
                $val['E'] = 0;
                $val['F'] = 0;
                return $val;
            },
            $questionArr
        ); //最后返回数据
        $records = array_map(
            function ($row) {
                $row = unserialize($row['result']);
                return $row;
            },
            $records
        );
        foreach ($records as $num) {
            foreach ($num as $t => $val) {
                foreach ($val as $que) {
                    if (!isset($dataSet[$que['id']])) {
                        continue;
                    }
                    $dataSet[$que['id']]['show']++;
                    if ($que['score'] > 0) {
                        $dataSet[$que['id']]['pass']++;
                    }
                    if (in_array($t, ['choices', 'choice'])) {
                        if ($t == 'choices') {
                            if (!empty($que['answer'])) {
                                foreach ($que['answer'] as $v) {
                                    $dataSet[$que['id']][$v]++;
                                }
                            }
                        } elseif (!empty($que['answer'])) {
                            $dataSet[$que['id']][$que['answer']]++;
                        }
                    }
                }
            }
        }
        $choice = [];
        $choices = [];
        foreach ($dataSet as $k => &$last) {
            if (!empty($last['show'])) {
                $last['percent'] = sprintf('%.1f', $last['pass'] / $last['show']) * 100;
            }
            unset($last['pass']);
            if (in_array($last['type'], ['choices', 'choice'])) {
                if (!empty($last['show'])) {
                    $last['A'] = sprintf('%.1f', $last['A'] / $last['show']) * 100;
                    $last['B'] = sprintf('%.1f', $last['B'] / $last['show']) * 100;
                    $last['C'] = sprintf('%.1f', $last['C'] / $last['show']) * 100;
                    $last['D'] = sprintf('%.1f', $last['D'] / $last['show']) * 100;
                    $last['E'] = sprintf('%.1f', $last['E'] / $last['show']) * 100;
                    $last['F'] = sprintf('%.1f', $last['F'] / $last['show']) * 100;
                }
                if ($last['type'] == 'choices') {
                    array_push($choices, $last);
                } else {
                    array_push($choice, $last);
                }
                unset($dataSet[$k]);
            }
        }
        $newDataSet = array_merge(array_values($choice), array_values($choices), array_values($dataSet));
        //判断是否导出
        if (!empty($input['export'])) {
            $input['fields'] = implode(',', Base::exchangeKey(Question::EXPORT_FIELDS));
            $newDataSet = array_map(
                function ($item) {
                    $item['type'] = empty(Question::TYPE[$item['type']]) ? '' : Question::TYPE[$item['type']];
                    if (is_array($item['answer'])) {
                        $item['answer'] = implode('', $item['answer']);
                    }
                    if ($item['type'] == Question::TYPE['judge']) {
                        $item['answer'] = empty($item['answer']) ? '错' : '对';
                    }
                    return $item;
                },
                $newDataSet
            );
            self::export($newDataSet, $input, Question::EXPORT_FIELDS);
            exit;
        }
        return payload(['dataSet' => $newDataSet]);
    }



    /**
     * 导出excel
     * dataSet 数据集
     * input 提交的参数
     * model_fields 模型里定义的fields
     * @param $dataSet
     * @param $input
     * @param $model_fields
     * @param string $title
     * @return Json
     */
    public static function export($dataSet, $input, $model_fields, $title = '成绩管理')
    {
        $tmp = $input['fields'];
        if (empty($tmp)) {
            return payload(error(-21, '参数错误'));
        }
        //分割传入进来的字段
        $fields = explode(',', $tmp);
        if (empty($fields)) {
            return payload(error(-21, '参数错误'));
        }
        $headers = [];
        //excel headers
        $headers[] = '';
        //格式化传入导出列表 修改成中文
        foreach ($fields as $v) {
            if (!empty($model_fields[$v])) {
                $headers[] = $model_fields[$v];
            }
        }
        $excelSet = [];
        //生成EXCEL表格
        foreach ($dataSet as $k => $v) {
            //过滤不需要导出列
            $excelSet[] = Collection::elements($fields, $v);
        }
        Excel::write($title, $headers, $excelSet);
    }
}