package com.yunzhupaas.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.dto.OnlineExamSubmitDTO;
import com.yunzhupaas.dto.OutOnlineExamDTO;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.service.*;
import com.yunzhupaas.entity.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.model.traintestpaperlibrary.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunzhupaas.flowable.entity.TaskEntity;
import jakarta.validation.Valid;

import java.util.*;

import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.excel.ExcelExportStyler;
import com.yunzhupaas.excel.ExcelHelper;
import com.yunzhupaas.annotation.YunzhupaasField;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.base.entity.ProvinceEntity;

import java.io.IOException;
import java.util.stream.Collectors;

import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.model.visualJson.UploaderTemplateModel;
import com.yunzhupaas.base.util.FormExecelUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 在线考试
 *
 * @版本： V5.2.0
 * @版权： Copyright @ 2025
 * @作者： 浙江尖峰集团股份有限公司
 * @日期： 2024-11-05
 */
@Slf4j
@RestController
@Tag(name = "在线考试", description = "train")
@RequestMapping("/api/train/TrainTestPaperLibrary")
public class TrainTestPaperLibraryController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TrainTestPaperLibraryService trainTestPaperLibraryService;

    @Autowired
    private TrainLibrarySingleService trainLibrarySingleService;
    @Autowired
    private TrainLibraryMoreService trainLibraryMoreService;
    @Autowired
    private TrainLibraryJudgmentService trainLibraryJudgmentService;
    @Autowired
    private TrainLibraryEssayQuestionService trainLibraryEssayQuestionService;

    /**
     * 列表
     *
     * @param trainTestPaperLibraryPagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody TrainTestPaperLibraryPagination trainTestPaperLibraryPagination)
            throws Exception {
        List<TrainTestPaperLibraryEntity> list = trainTestPaperLibraryService.getList(trainTestPaperLibraryPagination);
        List<Map<String, Object>> realList = new ArrayList<>();
        for (TrainTestPaperLibraryEntity entity : list) {
            Map<String, Object> trainTestPaperLibraryMap = JsonUtil.entityToMap(entity);
            trainTestPaperLibraryMap.put("id", trainTestPaperLibraryMap.get("f_id"));
            // 副表数据
            // 子表数据
            List<TrainLibrarySingleEntity> trainLibrarySingleList = entity.getTrainLibrarySingle();
            trainTestPaperLibraryMap.put("tableField103",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
            trainTestPaperLibraryMap.put("trainLibrarySingleList",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
            List<TrainLibraryMoreEntity> trainLibraryMoreList = entity.getTrainLibraryMore();
            trainTestPaperLibraryMap.put("tableField131",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
            trainTestPaperLibraryMap.put("trainLibraryMoreList",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
            List<TrainLibraryJudgmentEntity> trainLibraryJudgmentList = entity.getTrainLibraryJudgment();
            trainTestPaperLibraryMap.put("tableField147",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
            trainTestPaperLibraryMap.put("trainLibraryJudgmentList",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
            List<TrainLibraryEssayQuestionEntity> trainLibraryEssayQuestionList = entity.getTrainLibraryEssayQuestion();
            trainTestPaperLibraryMap.put("tableField180",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
            trainTestPaperLibraryMap.put("trainLibraryEssayQuestionList",
                    JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
            realList.add(trainTestPaperLibraryMap);
        }
        // 数据转换
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin"));
        realList = generaterSwapUtil.swapDataList(realList, TrainTestPaperLibraryConstant.getFormData(),
                TrainTestPaperLibraryConstant.getColumnData(), trainTestPaperLibraryPagination.getModuleId(),
                isPc ? false : false);

        // 返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(trainTestPaperLibraryPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    /**
     * 创建
     *
     * @param trainTestPaperLibraryForm
     * @return
     */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid TrainTestPaperLibraryForm trainTestPaperLibraryForm) {
        String b = trainTestPaperLibraryService.checkForm(trainTestPaperLibraryForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            trainTestPaperLibraryService.saveOrUpdate(trainTestPaperLibraryForm, null, true);
        } catch (Exception e) {
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id,
            @RequestParam(name = "forceDel", defaultValue = "false") boolean forceDel) throws Exception {
        TrainTestPaperLibraryEntity entity = trainTestPaperLibraryService.getInfo(id);
        if (entity != null) {
            // 主表数据删除
            trainTestPaperLibraryService.delete(entity);
            QueryWrapper<TrainLibrarySingleEntity> queryWrapperTrainLibrarySingle = new QueryWrapper<>();
            queryWrapperTrainLibrarySingle.lambda().eq(TrainLibrarySingleEntity::getFbankId, entity.getId());
            // 子表数据删除
            trainLibrarySingleService.remove(queryWrapperTrainLibrarySingle);
            QueryWrapper<TrainLibraryMoreEntity> queryWrapperTrainLibraryMore = new QueryWrapper<>();
            queryWrapperTrainLibraryMore.lambda().eq(TrainLibraryMoreEntity::getFbankId, entity.getId());
            // 子表数据删除
            trainLibraryMoreService.remove(queryWrapperTrainLibraryMore);
            QueryWrapper<TrainLibraryJudgmentEntity> queryWrapperTrainLibraryJudgment = new QueryWrapper<>();
            queryWrapperTrainLibraryJudgment.lambda().eq(TrainLibraryJudgmentEntity::getFbankId, entity.getId());
            // 子表数据删除
            trainLibraryJudgmentService.remove(queryWrapperTrainLibraryJudgment);
            QueryWrapper<TrainLibraryEssayQuestionEntity> queryWrapperTrainLibraryEssayQuestion = new QueryWrapper<>();
            queryWrapperTrainLibraryEssayQuestion.lambda().eq(TrainLibraryEssayQuestionEntity::getFbankId,
                    entity.getId());
            // 子表数据删除
            trainLibraryEssayQuestionService.remove(queryWrapperTrainLibraryEssayQuestion);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 批量删除
     *
     * @param obj
     * @return
     */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody Object obj) {
        Map<String, Object> objectMap = JsonUtil.entityToMap(obj);
        List<String> idList = JsonUtil.getJsonToList(objectMap.get("ids"), String.class);
        String errInfo = "";
        List<String> successList = new ArrayList<>();
        for (String allId : idList) {
            try {
                this.delete(allId, false);
                successList.add(allId);
            } catch (Exception e) {
                errInfo = e.getMessage();
            }
        }
        if (successList.size() == 0 && StringUtil.isNotEmpty(errInfo)) {
            return ActionResult.fail(errInfo);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 编辑
     *
     * @param id
     * @param trainTestPaperLibraryForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,
            @RequestBody @Valid TrainTestPaperLibraryForm trainTestPaperLibraryForm,
            @RequestParam(value = "isImport", required = false) boolean isImport) {
        TrainTestPaperLibraryEntity entity = trainTestPaperLibraryService.getInfo(id);
        if (entity != null) {
            trainTestPaperLibraryForm.setId(String.valueOf(entity.getId()));

            if (!isImport) {
                String b = trainTestPaperLibraryService.checkForm(trainTestPaperLibraryForm, 1);
                if (StringUtil.isNotEmpty(b)) {
                    return ActionResult.fail(b);
                }
            }

            try {
                trainTestPaperLibraryService.saveOrUpdate(trainTestPaperLibraryForm, id, false);
            } catch (Exception e) {
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 表单信息(详情页)
     * 详情页面使用-转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id) {
        TrainTestPaperLibraryEntity entity = trainTestPaperLibraryService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> trainTestPaperLibraryMap = JsonUtil.entityToMap(entity);
        trainTestPaperLibraryMap.put("id", trainTestPaperLibraryMap.get("f_id"));
        // 副表数据
        // 子表数据
        List<TrainLibrarySingleEntity> trainLibrarySingleList = entity.getTrainLibrarySingle();
        trainTestPaperLibraryMap.put("tableField103",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        trainTestPaperLibraryMap.put("trainLibrarySingleList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        List<TrainLibraryMoreEntity> trainLibraryMoreList = entity.getTrainLibraryMore();
        trainTestPaperLibraryMap.put("tableField131",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        trainTestPaperLibraryMap.put("trainLibraryMoreList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        List<TrainLibraryJudgmentEntity> trainLibraryJudgmentList = entity.getTrainLibraryJudgment();
        trainTestPaperLibraryMap.put("tableField147",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        trainTestPaperLibraryMap.put("trainLibraryJudgmentList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        List<TrainLibraryEssayQuestionEntity> trainLibraryEssayQuestionList = entity.getTrainLibraryEssayQuestion();
        trainTestPaperLibraryMap.put("tableField180",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        trainTestPaperLibraryMap.put("trainLibraryEssayQuestionList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin"));
        trainTestPaperLibraryMap = generaterSwapUtil.swapDataDetail(trainTestPaperLibraryMap,
                TrainTestPaperLibraryConstant.getFormData(), "623132689079205957", isPc ? false : false);
        // 子表数据
        trainTestPaperLibraryMap.put("trainLibrarySingleList", trainTestPaperLibraryMap.get("tableField103"));
        trainTestPaperLibraryMap.put("trainLibraryMoreList", trainTestPaperLibraryMap.get("tableField131"));
        trainTestPaperLibraryMap.put("trainLibraryJudgmentList", trainTestPaperLibraryMap.get("tableField147"));
        trainTestPaperLibraryMap.put("trainLibraryEssayQuestionList", trainTestPaperLibraryMap.get("tableField180"));
        return ActionResult.success(trainTestPaperLibraryMap);
    }

    /**
     * 获取详情(编辑页)
     * 编辑页面使用-不转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        TrainTestPaperLibraryEntity entity = trainTestPaperLibraryService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> trainTestPaperLibraryMap = JsonUtil.entityToMap(entity);
        trainTestPaperLibraryMap.put("id", trainTestPaperLibraryMap.get("f_id"));
        // 副表数据
        // 子表数据
        List<TrainLibrarySingleEntity> trainLibrarySingleList = entity.getTrainLibrarySingle();
        trainTestPaperLibraryMap.put("tableField103",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        trainTestPaperLibraryMap.put("trainLibrarySingleList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        List<TrainLibraryMoreEntity> trainLibraryMoreList = entity.getTrainLibraryMore();
        trainTestPaperLibraryMap.put("tableField131",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        trainTestPaperLibraryMap.put("trainLibraryMoreList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        List<TrainLibraryJudgmentEntity> trainLibraryJudgmentList = entity.getTrainLibraryJudgment();
        trainTestPaperLibraryMap.put("tableField147",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        trainTestPaperLibraryMap.put("trainLibraryJudgmentList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        List<TrainLibraryEssayQuestionEntity> trainLibraryEssayQuestionList = entity.getTrainLibraryEssayQuestion();
        trainTestPaperLibraryMap.put("tableField180",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        trainTestPaperLibraryMap.put("trainLibraryEssayQuestionList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        trainTestPaperLibraryMap = generaterSwapUtil.swapDataForm(trainTestPaperLibraryMap,
                TrainTestPaperLibraryConstant.getFormData(), TrainTestPaperLibraryConstant.TABLEFIELDKEY,
                TrainTestPaperLibraryConstant.TABLERENAMES);
        return ActionResult.success(trainTestPaperLibraryMap);
    }

    @Operation(summary = "在线考试详情")
    @GetMapping("/onlineExam/{id}")
    public ActionResult<OutOnlineExamDTO> getOnlineExam(@PathVariable("id") String id) {
        TrainTestPaperLibraryEntity entity = trainTestPaperLibraryService.getInfo(id);

        OutOnlineExamDTO outOnlineExamDTO = new OutOnlineExamDTO();
        outOnlineExamDTO.setId(id).setEndTime(entity.getFendTime()).setStartTime(entity.getFstartTime())
                .setExaminationDuration(entity.getFexaminationDuration());
        List<TrainLibrarySingleEntity> singleEntities = trainLibrarySingleService.getListByParentId(id);
        singleEntities.forEach(item -> item.setFanswer(null));
        List<TrainLibraryMoreEntity> moreEntities = trainLibraryMoreService.getListByParentId(id);
        moreEntities.forEach(item -> item.setFanswer(null));
        List<TrainLibraryJudgmentEntity> judgmentEntities = trainLibraryJudgmentService.getListByParentId(id);
        judgmentEntities.forEach(item -> item.setFanswer(null));
        List<TrainLibraryEssayQuestionEntity> essayQuestionEntities = trainLibraryEssayQuestionService
                .getListByParentId(id);
        essayQuestionEntities.forEach(item -> item.setFanswer(null));
        outOnlineExamDTO.setSingleEntities(singleEntities)
                .setMoreEntities(moreEntities)
                .setJudgmentEntities(judgmentEntities)
                .setEssayQuestionEntities(essayQuestionEntities);
        return ActionResult.success(outOnlineExamDTO);
    }

    @Operation(summary = "在线考试提交")
    @PostMapping("/onlineExam/submit")
    public ActionResult onlineExamSubmit(@RequestBody OnlineExamSubmitDTO onlineExamSubmitDTO) {
        return trainTestPaperLibraryService.onlineExamSubmit(onlineExamSubmitDTO);
    }
}
