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.InReadPaperDTO;
import com.yunzhupaas.dto.OutExamRecordsDetailDTO;
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.trainexamrecords.*;
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-06
 */
@Slf4j
@RestController
@Tag(name = "考试记录", description = "train")
@RequestMapping("/api/train/TrainExamRecords")
public class TrainExamRecordsController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TrainExamRecordsService trainExamRecordsService;

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

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

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

    /**
     * 创建
     *
     * @param trainExamRecordsForm
     * @return
     */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid TrainExamRecordsForm trainExamRecordsForm) {
        String b = trainExamRecordsService.checkForm(trainExamRecordsForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            trainExamRecordsService.saveOrUpdate(trainExamRecordsForm, 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 {
        TrainExamRecordsEntity entity = trainExamRecordsService.getInfo(id);
        if (entity != null) {
            // 主表数据删除
            trainExamRecordsService.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 trainExamRecordsForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,
            @RequestBody @Valid TrainExamRecordsForm trainExamRecordsForm,
            @RequestParam(value = "isImport", required = false) boolean isImport) {
        TrainExamRecordsEntity entity = trainExamRecordsService.getInfo(id);
        if (entity != null) {
            trainExamRecordsForm.setId(String.valueOf(entity.getId()));

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

            try {
                trainExamRecordsService.saveOrUpdate(trainExamRecordsForm, 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) {
        TrainExamRecordsEntity entity = trainExamRecordsService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> trainExamRecordsMap = JsonUtil.entityToMap(entity);
        trainExamRecordsMap.put("id", trainExamRecordsMap.get("f_id"));
        // 副表数据
        // 子表数据
        List<TrainLibrarySingleEntity> trainLibrarySingleList = entity.getTrainLibrarySingle();
        trainExamRecordsMap.put("tableField103",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        trainExamRecordsMap.put("trainLibrarySingleList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibrarySingleList)));
        List<TrainLibraryMoreEntity> trainLibraryMoreList = entity.getTrainLibraryMore();
        trainExamRecordsMap.put("tableField131",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        trainExamRecordsMap.put("trainLibraryMoreList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryMoreList)));
        List<TrainLibraryJudgmentEntity> trainLibraryJudgmentList = entity.getTrainLibraryJudgment();
        trainExamRecordsMap.put("tableField147",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        trainExamRecordsMap.put("trainLibraryJudgmentList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryJudgmentList)));
        List<TrainLibraryEssayQuestionEntity> trainLibraryEssayQuestionList = entity.getTrainLibraryEssayQuestion();
        trainExamRecordsMap.put("tableField180",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        trainExamRecordsMap.put("trainLibraryEssayQuestionList",
                JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(trainLibraryEssayQuestionList)));
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin"));
        trainExamRecordsMap = generaterSwapUtil.swapDataDetail(trainExamRecordsMap,
                TrainExamRecordsConstant.getFormData(), "623544962406941445", isPc ? false : false);
        // 子表数据
        trainExamRecordsMap.put("trainLibrarySingleList", trainExamRecordsMap.get("tableField103"));
        trainExamRecordsMap.put("trainLibraryMoreList", trainExamRecordsMap.get("tableField131"));
        trainExamRecordsMap.put("trainLibraryJudgmentList", trainExamRecordsMap.get("tableField147"));
        trainExamRecordsMap.put("trainLibraryEssayQuestionList", trainExamRecordsMap.get("tableField180"));
        return ActionResult.success(trainExamRecordsMap);
    }

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

    @Operation(summary = "考试记录详情")
    @GetMapping("/examRecordsDetail/{id}")
    public ActionResult<OutExamRecordsDetailDTO> examRecordsDetail(@PathVariable("id") String id) {
        return trainExamRecordsService.examRecordsDetail(id);
    }

    @Operation(summary = "阅卷")
    @PostMapping("/readPaper")
    public ActionResult readPaper(@RequestBody InReadPaperDTO in) {
        return trainExamRecordsService.readPaper(in);
    }

}
