package com.ruoyi.web.controller.learn;

import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.content.VistorContextHolder;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.dz.domain.DzControl;
import com.ruoyi.dz.service.IDzControlService;
import com.ruoyi.learn.domain.LearnQuestions;
import com.ruoyi.learn.service.ILearnQuestionsService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.service.CommService;
import com.ruoyi.web.service.PaperService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.learn.domain.LearnPaper;
import com.ruoyi.learn.service.ILearnPaperService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 试卷Controller
 *
 * @author ruoyi
 * @date 2025-09-18
 */
@RestController
@RequestMapping("/learn/paper")
@Api(tags = "后台-学习 - 卷")
public class LearnPaperController extends BaseController
{
    @Autowired
    private ILearnPaperService learnPaperService;

    @Autowired
    private PaperService paperService;
    @Autowired
    private CommService commService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IDzControlService dzControlService;

    /**
     * 查询试卷列表
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:list')")
    @GetMapping("/list")
    public TableDataInfo list(LearnPaper learnPaper)

    {
        startPage();
        List<LearnPaper> list = learnPaperService.selectLearnPaperList(learnPaper);
        return getDataTable(list);
    }

    /**
     * 导出试卷列表
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:export')")
    @Log(title = "试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LearnPaper learnPaper)
    {
        List<LearnPaper> list = learnPaperService.selectLearnPaperList(learnPaper);
        ExcelUtil<LearnPaper> util = new ExcelUtil<LearnPaper>(LearnPaper.class);
        util.exportExcel(response, list, "试卷数据");
    }

    /**
     * 获取试卷详细信息
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(learnPaperService.selectLearnPaperById(id));
    }

    /**
     * 新增试卷
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:add')")
    @Log(title = "试卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LearnPaper learnPaper)
    {
        return toAjax(learnPaperService.insertLearnPaper(learnPaper));
    }

    /**
     * 修改试卷
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:edit')")
    @Log(title = "试卷", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LearnPaper learnPaper)
    {
        return toAjax(learnPaperService.updateLearnPaper(learnPaper));
    }

    /**
     * 删除试卷
     */
    @PreAuthorize("@ss.hasPermi('learn:paper:remove')")
    @Log(title = "试卷", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(learnPaperService.deleteLearnPaperByIds(ids));
    }


    @GetMapping(value = "/buildAll")
    @ApiOperation("批量生成模拟卷一套")
    @Anonymous
    public AjaxResult buildAll(@ApiParam("序号") @RequestParam Integer seq)
    {
        DzControl dzControl = dzControlService.selectDzControl(VistorContextHolder.getContext());
        paperService.buildAllPapers(dzControl.getPlanYear(), seq, false);
        return success();
    }

    @ApiOperation("下载试卷")
    @PreAuthorize("@ss.hasPermi('learn:paper:download')")
    @RequestMapping(value = "download", method = {RequestMethod.GET, RequestMethod.POST})
    public void download(HttpServletResponse response, Long paperId) {
        Boolean isRemote = Boolean.parseBoolean(configService.selectConfigByKey("is.remote", "false"));
        if (isRemote) {
            downloadRemote(response, paperId);
        } else {
            commService.download(response, paperId);
        }
    }

    @ApiOperation("下载试卷（远程）")
    @RequestMapping(value = "downloadRemote", method = {RequestMethod.GET, RequestMethod.POST})
    @Anonymous
    public void downloadRemote(HttpServletResponse response, Long paperId) {
        String url = configService.selectConfigByKey("download.paper.url", "https://www.dz1kt.com/prod-api");
        commService.downloadRemote(response, paperId,url);
    }

    @ApiOperation("通用：下载试卷")
    @RequestMapping(value = "downloadPaper", method = {RequestMethod.GET, RequestMethod.POST})
    @Anonymous
    public void downloadPaper(HttpServletResponse response, String paperName, String ques) {
        List<LearnQuestions> questions = JSONArray.parseArray(ques, LearnQuestions.class);
        commService.download(response, paperName, questions);
    }
}
