package org.jeecg.modules.database.controller;

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.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.system.util.JwtUtil;
import org.jeecg.modules.database.constant.ExperimentStatus;
import org.jeecg.modules.database.entity.*;
import org.jeecg.modules.database.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Objects;

/**
 * @Description: 测试过程
 * @Author: jeecg-boot
 * @Date: 2024-10-15
 * @Version: V1.0
 */
@Tag(name = "测试过程")
@RestController
@RequestMapping("/database/experimentTestProcess")
@Slf4j
public class ExperimentTestProcessController extends JeecgController<ExperimentTestProcess, IExperimentTestProcessService> {
    @Autowired
    private IExperimentTestProcessService experimentTestProcessService;

    @Autowired
    private IExperimentLogService experimentLogService;
    @Autowired
    private ISysUserService       userService;

    @Autowired
    private IExperimentService experimentService;

    @Autowired
    private IExperimentSampleInfoService experimentSampleInfoService;

    /**
     * 分页列表查询
     *
     * @param experimentTestProcess
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "测试过程-分页列表查询")
    @Operation(summary = "测试过程-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExperimentTestProcess>> queryPageList(ExperimentTestProcess experimentTestProcess,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        QueryWrapper<ExperimentTestProcess> queryWrapper = QueryGenerator.initQueryWrapper(experimentTestProcess, req.getParameterMap());
        Page<ExperimentTestProcess> page = new Page<ExperimentTestProcess>(pageNo, pageSize);
        IPage<ExperimentTestProcess> pageList = experimentTestProcessService.page(page, queryWrapper);
        pageList.getRecords().forEach(v -> experimentTestProcessService.assembleDetails(v));
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param experimentTestProcess
     * @return
     */
    @AutoLog(value = "测试过程-添加")
    @Operation(summary = "测试过程-添加")
    @RequiresPermissions("database:experiment_test_process:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExperimentTestProcess experimentTestProcess, HttpServletRequest request) {
        String experimentId = experimentTestProcess.getExperimentId();
        if (StringUtils.isBlank(experimentId)) {
            return Result.error("试验数据不存在！");
        }
        Experiment dbExperiment = experimentService.getById(experimentId);
        if (Objects.isNull(dbExperiment)) {
            return Result.error("试验数据不存在！");
        }
        if (StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.COMPLETED)||StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.REVIEWED)) {
            return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
        }
        experimentTestProcess.setId(null);

        experimentService.changeStatus(experimentId, ExperimentStatus.PROGRESSING);

        experimentTestProcessService.saveWithDetails(experimentTestProcess);

        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experimentTestProcess.getExperimentId());
        experimentLog.setLogContent("添加测试过程");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param experimentTestProcess
     * @return
     */
    @AutoLog(value = "测试过程-编辑")
    @Operation(summary = "测试过程-编辑")
    @RequiresPermissions("database:experiment_test_process:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExperimentTestProcess experimentTestProcess, HttpServletRequest request) {
        ExperimentTestProcess byId = experimentTestProcessService.getById(experimentTestProcess.getId());
        String experimentId = byId.getExperimentId();
        if (StringUtils.isBlank(experimentId)) {
            return Result.error("试验数据不存在！");
        }
        Experiment dbExperiment = experimentService.getById(experimentId);
        if (Objects.isNull(dbExperiment)) {
            return Result.error("试验数据不存在！");
        }
        if (StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.COMPLETED)||StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.REVIEWED)) {
            return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
        }

        experimentService.changeStatus(experimentId, ExperimentStatus.PROGRESSING);

        experimentTestProcessService.saveWithDetails(experimentTestProcess);

        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experimentId);
        experimentLog.setLogContent("编辑测试过程");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);

        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "测试过程-通过id删除")
    @Operation(summary = "测试过程-通过id删除")
    @RequiresPermissions("database:experiment_test_process:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id, HttpServletRequest request) {
        ExperimentTestProcess experimentTestProcess = experimentTestProcessService.getById(id);

        String experimentId = experimentTestProcess.getExperimentId();
        if (StringUtils.isBlank(experimentId)) {
            return Result.error("试验数据不存在！");
        }
        Experiment dbExperiment = experimentService.getById(experimentId);
        if (Objects.isNull(dbExperiment)) {
            return Result.error("试验数据不存在！");
        }
        if (StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.COMPLETED)||StringUtils.equals(dbExperiment.getStatus(), ExperimentStatus.REVIEWED)) {
            return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
        }
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experimentId);
        experimentLog.setLogContent("删除测试过程");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);

        experimentTestProcessService.removeById(id);

        return Result.OK("删除成功!");
    }

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

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

    /**
     * 通过实验id查询
     *
     * @param experimentalId
     * @return
     */
    //@AutoLog(value = "试验评定-通过id查询")
    @Operation(summary = "测试过程-通过实验ID查询")
    @GetMapping(value = "/queryByExperimentId")
    public Result<ExperimentTestProcess> queryByExperimentalId(
            @RequestParam(name = "experimentId", required = true) String experimentalId) {
        LambdaQueryWrapper<ExperimentTestProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExperimentTestProcess::getExperimentId, experimentalId);
        ExperimentTestProcess experimentReview = experimentTestProcessService.getOne(queryWrapper);
        if (experimentReview == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(experimentReview);
    }

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

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExperimentTestProcess experimentTestProcess) {
        return super.exportXls(request, experimentTestProcess, ExperimentTestProcess.class, "测试过程");
    }

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

}
