package com.ruoyi.web.controller.exam;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.excel.ExportExcel;
import com.ruoyi.common.utils.excel.ImportExcel;
import com.ruoyi.system.domain.qu.ElQu;
import com.ruoyi.system.domain.qu.dto.export.QuExportDTO;
import com.ruoyi.system.domain.qu.dto.ext.QuDetailDTO;
import com.ruoyi.system.domain.qu.dto.request.QuQueryReqDTO;
import com.ruoyi.web.controller.manager.QuManager;
import com.ruoyi.web.controller.manager.RepoManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * packageName com.ruoyi.web.controller.examination
 *
 * @author wangxy
 * @version JDK 8
 * @className QuController
 * @date 2024/6/27
 * @description 试题
 */
@Api("试题")
@Controller
@RequestMapping("/system/qu")
public class QuController extends BaseController {

    private String prefix = "system/elExam/qu";

    @Resource
    private QuManager quManager;

    @Resource
    private RepoManager elRepoManager;


    @ApiOperation("试题")
    @RequiresPermissions("system:qu:view")
    @GetMapping()
    public String qu() {
        return prefix + "/qu";
    }


    @ApiOperation("试题")
    @RequiresPermissions("system:qu:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QuQueryReqDTO qu) {
        startPage();
        List<ElQu> list = quManager.selectQuList(qu);
        return getDataTable(list);
    }

    /**
     * 新增
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("repo",elRepoManager.getList());
        return prefix + "/add";
    }


    @ApiOperation("新增")
    @RequiresPermissions("system:qu:add")
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody @Validated QuDetailDTO reqDTO) {
        return toAjax(quManager.saveOrUpdate(reqDTO));
    }


    @ApiOperation("修改")
    @RequiresPermissions("system:qu:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("repo",elRepoManager.getList());
        mmap.put("detailDTO", quManager.detail(id));
        mmap.put("detailid",id);
        return prefix + "/edit";
    }

    @ApiOperation("试题修改")
    @RequiresPermissions("system:qu:edit")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody @Validated QuDetailDTO reqDTO) {
        return toAjax(quManager.saveOrUpdate(reqDTO));
    }


    @ApiOperation("删除")
    @RequiresPermissions("system:qu:remove")
    @Log(title = "试题", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(quManager.deleteQuByIds(ids));
    }


    @ApiOperation("详情")
    @GetMapping ("/detail")
    @ResponseBody
    public AjaxResult detail(@RequestParam String quId) {
        return success(quManager.detail(quId));
    }


    @ApiOperation("下载导入试题数据模板")
    @ResponseBody
    @GetMapping("/template")
    public AjaxResult importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "试题导入模板.xlsx";
            List<QuExportDTO> list = Lists.newArrayList();
            QuExportDTO l1 = new QuExportDTO();
            l1.setNo("正式导入，请删除此说明行：数字，相同的数字表示同一题的序列");
            l1.setQContent("问题内容");
            l1.setQAnalysis("整个问题的解析");
            l1.setQuType("只能填写1、2、3、4；1表示单选题，2表示多选题，3表示判断题，4表示主观题");
            l1.setQImage("题目图片，完整URL，多个用逗号隔开，限制10个");
            l1.setQVideo("题目视频，完整URL，只限一个");
            l1.setAImage("答案图片，完整URL，只限一个");
            l1.setRepoList(Arrays.asList(new String[]{"已存在题库的ID，多个用逗号隔开，题库ID错误无法导入"}));
            l1.setAContent("候选答案1");
            l1.setAIsRight("只能填写0或1，0表示否，1表示是");
            l1.setAAnalysis("这个项是正确的");

            QuExportDTO l2 = new QuExportDTO();
            l2.setQContent("找出以下可以被2整除的数（多选）");
            l2.setQAnalysis("最基本的数学题，不做过多解析");
            l2.setQuType("2");
            l2.setNo("1");
            l2.setAIsRight("1");
            l2.setAContent("数字：2");
            l2.setAAnalysis("2除以2=1，对的");

            QuExportDTO l3 = new QuExportDTO();
            l3.setNo("1");
            l3.setAIsRight("0");
            l3.setAContent("数字：3");
            l3.setAAnalysis("3除以2=1.5，不能被整除");
            QuExportDTO l4 = new QuExportDTO();
            l4.setNo("1");
            l4.setAIsRight("1");
            l4.setAContent("数字：6");
            l4.setAAnalysis("6除以2=3，对的");

            list.add(l1);
            list.add(l2);
            list.add(l3);
            list.add(l4);

            new ExportExcel("试题数据", QuExportDTO.class, 1).setDataList(list).write(response, fileName).dispose();
            return success();
        } catch (Exception e) {
            return error("导入模板下载失败！失败信息："+e.getMessage());
        }
    }


    @RequiresPermissions("system:qu:import")
    @GetMapping("/toImport")
    public String toImport() {
        return prefix + "/toImport";
    }

    @ApiOperation("导入Excel")
    @ResponseBody
    @PostMapping( "/import")
    public AjaxResult importFile(@RequestParam("file") MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ImportExcel ei = new ImportExcel(file,inputStream, 1, 0);
            List<QuExportDTO> list = ei.getDataList(QuExportDTO.class);
            // 导入数据条数
            quManager.importExcel(list);
            // 导入成功
            return success("导入成功");
        } catch (IOException | InvalidFormatException | IllegalAccessException | InstantiationException e) {
            logger.info(e.getMessage());
        }finally {
            IOUtils.closeQuietly(inputStream);
        }
        return error("导入失败");
    }









}
