package com.ruoyi.hezhi.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
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.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.hezhi.domain.TbExamSubject;
import com.ruoyi.hezhi.domain.TbExamSubjectAnswer;
import com.ruoyi.hezhi.domain.vo.TopicImportTemplateVO;
import com.ruoyi.hezhi.service.ITbExamSubjectAnswerService;
import com.ruoyi.hezhi.service.ITbExamSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.init.ResourceReader;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 考试题目Controller
 *
 * @author ruoyi
 * @date 2024-11-04
 */
@RestController
@RequestMapping("/hezhi/examSubject")
public class TbExamSubjectController extends BaseController
{
    @Autowired
    private ITbExamSubjectService tbExamSubjectService;

    @Autowired
    private ITbExamSubjectAnswerService tbExamSubjectAnswerService;

    // 本地文件路径
    private static final String FILE_PATH = "/reportForm/考试题目导入模板.xlsx";  // 替换为实际的文件路径

    /**
     * 查询考试题目列表
     */
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbExamSubject tbExamSubject)
    {
        startPage();
        List<TbExamSubject> list = tbExamSubjectService.selectTbExamSubjectList(tbExamSubject);
        return getDataTable(list);
    }

    /**
     * 导出考试题目列表
     */
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:export')")
    @Log(title = "考试题目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbExamSubject tbExamSubject)
    {
        List<TbExamSubject> list = tbExamSubjectService.selectTbExamSubjectList(tbExamSubject);
        ExcelUtil<TbExamSubject> util = new ExcelUtil<TbExamSubject>(TbExamSubject.class);
        util.exportExcel(response, list, "考试题目数据");
    }

    /**
     * 获取考试题目详细信息
     */
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:query')")
    @GetMapping(value = "/{examSubjectId}")
    public AjaxResult getInfo(@PathVariable("examSubjectId") Long examSubjectId)
    {
        TbExamSubject tbExamSubject = tbExamSubjectService.selectTbExamSubjectByExamSubjectId(examSubjectId);
        if (tbExamSubject != null) {
            tbExamSubject.setExamSubjectAnswerList(tbExamSubjectAnswerService.selectTbExamSubjectAnswerListBy(tbExamSubject.getExamSubjectNo()));
        }
        return success(tbExamSubject);
    }

    /**
     * 新增考试题目
     */
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:add')")
    @Log(title = "新增考试题目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbExamSubject tbExamSubject)
    {
        List<TbExamSubjectAnswer> examSubjectAnswerList = tbExamSubject.getExamSubjectAnswerList();
        if (tbExamSubject.getSubjectType() == 1 || tbExamSubject.getSubjectType() == 2) {
            if (examSubjectAnswerList.size() < 2) {
                return AjaxResult.error("选项数请大于1");
            }

            // 正确选项数量
            long answerCount = examSubjectAnswerList.stream().filter(p ->p.getIsAnswer().equals(1)).count();
            if (tbExamSubject.getSubjectType() == 1 && answerCount != 1) {
                return AjaxResult.error("请设置1个单选正确选项数");
            }
            if (tbExamSubject.getSubjectType() == 2 && answerCount < 2) {
                return AjaxResult.error("请设置多个多选正确选项数");
            }

        }
        if (tbExamSubject.getSubjectType() == 4) {
            if (examSubjectAnswerList.isEmpty()) {
                return AjaxResult.error("论述题匹配关键词数请大于一条");
            }
        }
        String examSubjectNo = IdUtils.fastSimpleUUID();
        tbExamSubject.setExamSubjectNo(examSubjectNo);
        tbExamSubjectService.insertTbExamSubject(tbExamSubject);

        if (!examSubjectAnswerList.isEmpty()) {
            Date nowDate = DateUtils.getNowDate();
            for (TbExamSubjectAnswer subjectAnswer : examSubjectAnswerList) {
                subjectAnswer.setExamSubjectId(tbExamSubject.getExamSubjectId());
                subjectAnswer.setExamSubjectNo(examSubjectNo);
                subjectAnswer.setSubjectType(tbExamSubject.getSubjectType());
                if (tbExamSubject.getSubjectType() == 4) {
                    subjectAnswer.setIsAnswer(1);
                }
                subjectAnswer.setCreateTime(nowDate);
            }
            tbExamSubjectAnswerService.batchInsertTbExamSubjectAnswer(examSubjectAnswerList);
        }

        if (tbExamSubject.getSubjectType() != 3) {
            Map<String, Object> answerMap = tbExamSubjectAnswerService.selectAnswerIdsAndAnswer(tbExamSubject.getExamSubjectId(), null);
            if (answerMap != null) {
                TbExamSubject updateExamSubject = new TbExamSubject();
                updateExamSubject.setExamSubjectId(tbExamSubject.getExamSubjectId());
                updateExamSubject.setAnswerIds(answerMap.get("answerIds").toString());
                if (tbExamSubject.getSubjectType() == 4) {
                    updateExamSubject.setAnswer(answerMap.get("answerNames").toString());
                } else {
                    updateExamSubject.setAnswer(answerMap.get("answers").toString());
                }
                tbExamSubjectService.updateTbExamSubject(updateExamSubject);
            }
        }

        if (tbExamSubject.getSubjectType() == 3) {
            List<TbExamSubjectAnswer> judgeSubjectAnswerList = new ArrayList<>();
            TbExamSubjectAnswer subjectAnswerA = new TbExamSubjectAnswer();
            subjectAnswerA.setExamSubjectId(tbExamSubject.getExamSubjectId());
            subjectAnswerA.setExamSubjectNo(examSubjectNo);
            subjectAnswerA.setSubjectType(tbExamSubject.getSubjectType());
            subjectAnswerA.setSubjectOption("A");
            subjectAnswerA.setSubjectName("正确");
            if ("正确".equals(tbExamSubject.getAnswer())) {
                subjectAnswerA.setIsAnswer(1);
            } else {
                subjectAnswerA.setIsAnswer(0);
            }
            judgeSubjectAnswerList.add(subjectAnswerA);

            TbExamSubjectAnswer subjectAnswerB = new TbExamSubjectAnswer();
            subjectAnswerB.setExamSubjectId(tbExamSubject.getExamSubjectId());
            subjectAnswerB.setExamSubjectNo(examSubjectNo);
            subjectAnswerB.setSubjectType(tbExamSubject.getSubjectType());
            subjectAnswerB.setSubjectOption("B");
            subjectAnswerB.setSubjectName("错误");
            if ("错误".equals(tbExamSubject.getAnswer())) {
                subjectAnswerB.setIsAnswer(1);
            } else {
                subjectAnswerB.setIsAnswer(0);
            }
            judgeSubjectAnswerList.add(subjectAnswerB);
            tbExamSubjectAnswerService.batchInsertTbExamSubjectAnswer(judgeSubjectAnswerList);
        }

        return AjaxResult.success();
    }

    /**
     * 修改考试题目
     */
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:edit')")
    @Log(title = "修改考试题目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbExamSubject tbExamSubject)
    {
        TbExamSubject examSubject = tbExamSubjectService.selectTbExamSubjectByExamSubjectId(tbExamSubject.getExamSubjectId());
        if (examSubject == null) {
            return AjaxResult.error("考试题目异常");
        }

        List<TbExamSubjectAnswer> examSubjectAnswerList = tbExamSubject.getExamSubjectAnswerList();
        if (tbExamSubject.getSubjectType() == 1 || tbExamSubject.getSubjectType() == 2) {
            if (examSubjectAnswerList.size() < 2) {
                return AjaxResult.error("选项数请大于1");
            }

            // 正确选项数量
            long answerCount = examSubjectAnswerList.stream().filter(p ->p.getIsAnswer().equals(1)).count();
            if (tbExamSubject.getSubjectType() == 1 && answerCount != 1) {
                return AjaxResult.error("请设置1个单选正确选项数");
            }
            if (tbExamSubject.getSubjectType() == 2 && answerCount < 2) {
                return AjaxResult.error("请设置多个多选正确选项数");
            }

        }
        if (tbExamSubject.getSubjectType() == 4) {
            if (examSubjectAnswerList.isEmpty()) {
                return AjaxResult.error("论述题匹配关键词数请大于一条");
            }
        }

        // 删除重新添加
        tbExamSubjectAnswerService.batchDeleteTbExamSubjectAnswerByExamSubjectNo(examSubject.getExamSubjectNo());
        if (!examSubjectAnswerList.isEmpty()) {
            Date nowDate = DateUtils.getNowDate();
            for (TbExamSubjectAnswer subjectAnswer : examSubjectAnswerList) {
                subjectAnswer.setExamSubjectId(tbExamSubject.getExamSubjectId());
                subjectAnswer.setExamSubjectNo(examSubject.getExamSubjectNo());
                subjectAnswer.setSubjectType(tbExamSubject.getSubjectType());
                if (tbExamSubject.getSubjectType() == 4) {
                    subjectAnswer.setIsAnswer(1);
                }
                subjectAnswer.setCreateTime(nowDate);
            }
        }

        if (tbExamSubject.getSubjectType() != 3) {
            Map<String, Object> answerMap = tbExamSubjectAnswerService.selectAnswerIdsAndAnswer(tbExamSubject.getExamSubjectId(), null);
            if (answerMap != null) {
                tbExamSubject.setExamSubjectId(tbExamSubject.getExamSubjectId());
                tbExamSubject.setAnswerIds(answerMap.get("answerIds").toString());
                if (tbExamSubject.getSubjectType() == 4) {
                    tbExamSubject.setAnswer(answerMap.get("answerNames").toString());
                } else {
                    tbExamSubject.setAnswer(answerMap.get("answers").toString());
                }
            }
        }

        if (tbExamSubject.getSubjectType() == 3) {
            List<TbExamSubjectAnswer> judgeSubjectAnswerList = new ArrayList<>();
            TbExamSubjectAnswer subjectAnswerA = new TbExamSubjectAnswer();
            subjectAnswerA.setExamSubjectId(tbExamSubject.getExamSubjectId());
            subjectAnswerA.setExamSubjectNo(examSubject.getExamSubjectNo());
            subjectAnswerA.setSubjectType(tbExamSubject.getSubjectType());
            subjectAnswerA.setSubjectOption("A");
            subjectAnswerA.setSubjectName("正确");
            if ("正确".equals(tbExamSubject.getAnswer())) {
                subjectAnswerA.setIsAnswer(1);
            } else {
                subjectAnswerA.setIsAnswer(0);
            }
            judgeSubjectAnswerList.add(subjectAnswerA);

            TbExamSubjectAnswer subjectAnswerB = new TbExamSubjectAnswer();
            subjectAnswerB.setExamSubjectId(tbExamSubject.getExamSubjectId());
            subjectAnswerB.setExamSubjectNo(examSubject.getExamSubjectNo());
            subjectAnswerB.setSubjectType(tbExamSubject.getSubjectType());
            subjectAnswerB.setSubjectOption("B");
            subjectAnswerB.setSubjectName("错误");
            if ("错误".equals(tbExamSubject.getAnswer())) {
                subjectAnswerB.setIsAnswer(1);
            } else {
                subjectAnswerB.setIsAnswer(0);
            }
            judgeSubjectAnswerList.add(subjectAnswerB);
            tbExamSubjectAnswerService.batchInsertTbExamSubjectAnswer(judgeSubjectAnswerList);
        }else {
            tbExamSubjectAnswerService.batchInsertTbExamSubjectAnswer(examSubjectAnswerList);
        }

        tbExamSubjectService.updateTbExamSubject(tbExamSubject);
        return AjaxResult.success();
    }

    /**
     * 删除考试题目
     */
    @PreAuthorize("@ss.hasPermi('hezhi:examSubject:remove')")
    @Log(title = "考试题目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{examSubjectIds}")
    public AjaxResult remove(@PathVariable Long[] examSubjectIds)
    {
        return toAjax(tbExamSubjectService.deleteTbExamSubjectByExamSubjectIds(examSubjectIds));
    }

    /**
     * 下载导入模板
     *
     * @param response response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception {

        tbExamSubjectService.importTemplate(response);

    }

    /**
     * 导入考试题目
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
         ExcelUtil<TopicImportTemplateVO> util = new ExcelUtil<TopicImportTemplateVO>(TopicImportTemplateVO.class);
        List<TopicImportTemplateVO> list = util.importExcel(file.getInputStream());
        String username = SecurityUtils.getUsername();
       String message= tbExamSubjectService.importData(list,username);
        return AjaxResult.success(message);
    }
}
