package org.jeecg.modules.database.controller;

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.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.database.constant.ExperimentFileType;
import org.jeecg.modules.database.entity.ExperimentFile;
import org.jeecg.modules.database.service.IExperimentFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @Description: 试验文件
 * @Author: jeecg-boot
 * @Date: 2024-12-09
 * @Version: V1.0
 */
@Tag(name = "试验文件")
@RestController
@RequestMapping("/database/experimentFile")
@Slf4j
public class ExperimentFileController extends JeecgController<ExperimentFile, IExperimentFileService> {

    @Value(value = "${jeecg.uploadType}")
    private String uploadType;

    @Autowired
    private IExperimentFileService experimentFileService;

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

    /**
     * 添加
     *
     * @param experimentFile
     * @return
     */
    @AutoLog(value = "试验文件-添加")
    @Operation(summary = "试验文件-添加")
    @RequiresPermissions("database:experiment:edit")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExperimentFile experimentFile) {
        experimentFileService.save(experimentFile);
        return Result.OK("添加成功！");
    }

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

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

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

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

    /**
     * 导出excel
     *
     * @param request
     * @param experimentFile
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExperimentFile experimentFile) {
        return super.exportXls(request, experimentFile, ExperimentFile.class, "试验文件");
    }

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

    /**
     * 通过实验id查询
     *
     * @param experimentId
     * @return
     */
    //@AutoLog(value = "试验评定-通过id查询")
    @Operation(summary = "试验报告-通过实验ID查询", description = "根据实验ID查询,返回List结构")
    @GetMapping(value = "/queryByExperimentId")
    public Result<List<ExperimentFile>> queryByExperimentId(@RequestParam(name = "experimentId", required = true) String experimentId) {
        List<ExperimentFile> byExperimentId = experimentFileService.getByExperimentId(experimentId);
        return Result.OK(byExperimentId);
    }

    @Operation(summary = "试验报告-通过实验ID分类查询", description = "根据分类查询,返回Map结构")
    @GetMapping(value = "/queryByType")
    public Result<Map<String, List<ExperimentFile>>> queryByType(
            @RequestParam(name = "experimentId", required = true) String experimentId) {
        Map<String, List<ExperimentFile>> result = new HashMap<>();
        for (ExperimentFileType value : ExperimentFileType.values()) {
            List<ExperimentFile> fileList = experimentFileService.getByType(experimentId, value.getType());
            result.put(value.getType(), fileList);
        }
        return Result.OK(result);
    }

    @Operation(summary = "试验管理-上传试验文件", description =
            "fileType 选传, 值为 ['辐照试验委托书','试验大纲','沟通记录表','合同/委托书评审表','试验大纲评审表','试验流程检查单','辐照试验更改申请表','满意度调查表','其他文件'],不传默认 '其他文件',"
                    + "</br> experimentId 选传,上传完成后自动保存到试验管理,不传则不保存")
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(name = "experimentId", required = false) String experimentId,
                            @RequestParam(name = "fileType", required = false) String fileType) throws Exception {
        Result<ExperimentFile> result = new Result<>();
        if (StringUtils.isBlank(fileType)) {
            fileType = ExperimentFileType.qtwj.getType();
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");

        //update-begin-author:taoyan date:20200814 for:文件上传改造
        String savePath = CommonUtils.upload(file, "experiment_file", uploadType);

        ExperimentFile ossFile = new ExperimentFile();
        ossFile.setFileName(file.getOriginalFilename());
        ossFile.setFileUrl(savePath);
        ossFile.setFileType(fileType);
        if (StringUtils.isNotBlank(experimentId)) {
            ossFile.setExperimentId(experimentId);
            experimentFileService.save(ossFile);
        }
        result.setResult(ossFile);

        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

}
