package org.jeecg.modules.database.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.database.constant.ExperimentDocType;
import org.jeecg.modules.database.entity.ExperimentDoc;
import org.jeecg.modules.database.service.IExperimentDocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @Description: 试验文档
 * @Author: jeecg-boot
 * @Date: 2024-08-30
 * @Version: V1.0
 */
@Tag(name = "试验文档")
@RestController
@RequestMapping("/database/experimentDoc")
@Slf4j
public class ExperimentDocController extends JeecgController<ExperimentDoc, IExperimentDocService> {
    @Autowired
    private IExperimentDocService experimentDocService;

    /**
     * 分页列表查询
     *
     * @param experimentDoc
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "试验文档-分页列表查询")
    @Operation(summary = "试验文档-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExperimentDoc>> queryPageList(ExperimentDoc experimentDoc,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<ExperimentDoc> queryWrapper = QueryGenerator.initQueryWrapper(experimentDoc, req.getParameterMap());
        Page<ExperimentDoc> page = new Page<ExperimentDoc>(pageNo, pageSize);
        IPage<ExperimentDoc> pageList = experimentDocService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param experimentDoc
     * @return
     */
    @AutoLog(value = "试验文档-添加")
    @Operation(summary = "试验文档-添加")
    @RequiresPermissions("database:experiment_doc:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExperimentDoc experimentDoc) {
        experimentDoc.setVersion(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
        experimentDocService.save(experimentDoc);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param experimentDoc
     * @return
     */
    @AutoLog(value = "试验文档-编辑")
    @Operation(summary = "试验文档-编辑")
    @RequiresPermissions("database:experiment_doc:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExperimentDoc experimentDoc) {
        experimentDocService.updateById(experimentDoc);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "试验文档-通过id删除")
    @Operation(summary = "试验文档-通过id删除")
    @RequiresPermissions("database:experiment_doc:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        experimentDocService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "试验文档-批量删除")
    @Operation(summary = "试验文档-批量删除")
    @RequiresPermissions("database:experiment_doc:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.experimentDocService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "试验文档-通过id查询")
    @Operation(summary = "试验文档-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExperimentDoc> queryById(@RequestParam(name = "id", required = true) String id) {
        ExperimentDoc experimentDoc = experimentDocService.getById(id);
        if (experimentDoc == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(experimentDoc);
    }

    /**
     * 通过实验id查询
     *
     * @param experimentId
     * @return
     */
    //@AutoLog(value = "试验评定-通过id查询")
    @Operation(summary = "试验报告-通过实验ID查询")
    @GetMapping(value = "/queryByExperimentId")
    public Result<List<ExperimentDoc>> queryByExperimentId(@RequestParam(name = "experimentId", required = true) String experimentId) {
        List<ExperimentDoc> result = new ArrayList<>();
        for (ExperimentDocType value : ExperimentDocType.values()) {
            ExperimentDoc doc = experimentDocService.getByExperimentId(experimentId, value.getType());
            if (Objects.isNull(doc)) {
                doc = experimentDocService.generate(experimentId, value.getType());
            }
            if (Objects.isNull(doc)) {
                doc = new ExperimentDoc();
                doc.setId(IdUtil.simpleUUID());
                doc.setExperimentId(experimentId);
                doc.setDocType(value.getType());
            }
            result.add(doc);
        }
        return Result.OK(result);
    }

    @Operation(summary = "试验报告-通过实验ID查询所有版本文档")
    @GetMapping(value = "/queryHistoryByExperimentId")
    public Result<Map<String, List<ExperimentDoc>>> queryHistoryByExperimentId(
            @RequestParam(name = "experimentId", required = true) String experimentId) {
        Map<String, List<ExperimentDoc>> result = new HashMap<>();
        for (ExperimentDocType value : ExperimentDocType.values()) {
            List<ExperimentDoc> docList = experimentDocService.getHistoryByExperimentId(experimentId, value.getType());
            result.put(value.getType(), docList);
        }
        return Result.OK(result);
    }

    /**
     * 试验文档下载
     *
     * @param experimentId
     * @return
     */
    //@AutoLog(value = "试验评定-通过id查询")
    @Operation(summary = "试验文档下载", parameters = {@Parameter(name = "experimentId", description = "实验id", required = true),
            @Parameter(name = "type", description = "文档类型(辐照试验计划表,设备使用记录表,试验报告评审表,试验报告,辐照试验总结单)",
                    required = true),})
    @GetMapping(value = "/download")
    public Result<ExperimentDoc> download(@RequestParam(name = "experimentId", required = true) String experimentId,
                                          @RequestParam(name = "type", required = true) String type, HttpServletResponse response) {
        LambdaQueryWrapper<ExperimentDoc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExperimentDoc::getExperimentId, experimentId);
        queryWrapper.eq(ExperimentDoc::getDocType, type);
        ExperimentDoc doc = experimentDocService.getOne(queryWrapper);
        if (Objects.isNull(doc)) {
            doc = experimentDocService.generate(experimentId, type);
        }
        if (Objects.isNull(doc)) {
            return Result.error("试验文档生成失败");
        }
        return Result.OK(doc);
    }

    /**
     * 重新生成试验文档
     *
     * @param experimentId
     * @param type
     * @return
     */
    @Operation(summary = "重新生成试验文档", parameters = {@Parameter(name = "experimentId", description = "实验id", required = true),
            @Parameter(name = "type", description = "文档类型", required = true),})
    @GetMapping(value = "/generate")
    public Result<ExperimentDoc> generate(@RequestParam(name = "experimentId", required = true) String experimentId,
                                          @RequestParam(name = "type", required = true) String type) {
        ExperimentDoc experimentReview = experimentDocService.generate(experimentId, type);
        if (Objects.isNull(experimentReview)) {
            return Result.error("试验文档生成失败");
        }
        return Result.OK(experimentReview);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param experimentDoc
     */

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExperimentDoc experimentDoc) {
        return super.exportXls(request, experimentDoc, ExperimentDoc.class, "试验文档");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("database:experiment_doc:add")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ExperimentDoc.class);
    }

}
