package org.jeecg.modules.database.controller;

import cn.hutool.core.collection.CollUtil;
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.List;

/**
 * @Description: 试验管理
 * @Author: jeecg-boot
 * @Date: 2024-08-30
 * @Version: V1.0
 */
@Tag(name = "试验管理")
@RestController
@RequestMapping("/database/experiment")
@Slf4j
public class ExperimentController extends JeecgController<Experiment, IExperimentService> {
    @Autowired
    private IExperimentService                 experimentService;
    @Autowired
    private IExperimentLogService              experimentLogService;
    @Autowired
    private IExperimentAnnealProcessService    experimentAnnealProcessService;
    @Autowired
    private IExperimentRadiationProcessService experimentRadiationProcessService;
    @Autowired
    private IExperimentTestProcessService      experimentTestProcessService;
    @Autowired
    private ISysUserService                    userService;
    @Autowired
    private IExperimentUserService             experimentUserService;
    @Autowired
    private IExperimentSequenceService         experimentSequenceService;

    @Autowired
    private IExperimentSampleInfoService         experimentSampleInfoService;
    @Autowired
    private IExperimentDeviationConditionService experimentDeviationConditionService;
    @Autowired
    private IExperimentDeviationEquipmentService experimentDeviationEquipmentService;
    @Autowired
    private IExperimentIrradiationBoardService   experimentIrradiationBoardService;
    @Autowired
    private IExperimentFileService               experimentFileService;

    /**
     * 分页列表查询
     *
     * @param experiment
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "试验管理-分页列表查询")
    @Operation(summary = "试验管理-分页列表查询")
    @GetMapping(value = "/list")
    //    @PermissionData(pageComponent="experiment/manage/ExperimentList")
    public Result<IPage<Experiment>> queryPageList(Experiment experiment, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<Experiment> queryWrapper = QueryGenerator.initQueryWrapper(experiment, req.getParameterMap());
        Page<Experiment> page = new Page<>(pageNo, pageSize);
        IPage<Experiment> pageList = experimentService.page(page, queryWrapper);
        pageList.getRecords().forEach(v -> experimentService.fetchExperimentDetail(v));
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param experiment
     * @return
     */
    @AutoLog(value = "试验管理-添加")
    @Operation(summary = "试验管理-添加",
            description = "添加试验,传sampleInfoList,deviationConditionList,deviationEquipmentList,irradiationBoardList,不用传fileList. </br> "
                    + "experimentUser 用,隔开")
    @RequiresPermissions("database:experiment:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Experiment experiment, HttpServletRequest request) {
        String experimentNo = experiment.getExperimentNo();
        if (!StringUtils.startsWith(experimentNo, "KC")) {
            return Result.error("实验编号格式不正确！");
        }
        experiment.setStatus(ExperimentStatus.PRE_TEST);
        experimentService.saveWithDetail(experiment);

        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experiment.getId());
        experimentLog.setLogContent("新建实验");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);

        String[] split = experimentNo.split("-", 4);
        ExperimentSequence seq = new ExperimentSequence();
        seq.setSequenceYear(split[1]);
        seq.setSequenceValue(Integer.parseInt(split[3]));
        experimentSequenceService.save(seq);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param experiment
     * @return
     */
    @AutoLog(value = "试验管理-编辑")
    @Operation(summary = "试验管理-编辑",
            description = "编辑试验,传sampleInfoList,deviationConditionList,deviationEquipmentList,irradiationBoardList,不用传fileList \n "
                    + "experimentUser 用逗号隔开,无修改的字段可不传")
    @RequiresPermissions("database:experiment:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Experiment experiment, HttpServletRequest request) {
        if (StringUtils.containsAny(experiment.getStatus(), ExperimentStatus.COMPLETED, ExperimentStatus.REPORT_AUDITING)) {
            return Result.error("试验状态:[" + experiment.getStatus() + "]不能进行修改！");
        }
        experimentService.saveWithDetail(experiment);
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experiment.getId());
        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:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        experimentService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "试验管理-试验复制")
    @Operation(summary = "试验管理-试验复制")
    //@RequiresPermissions("database:experiment:delete")
    @PostMapping(value = "/copy")
    public Result<String> copy(@RequestParam(name = "id", required = true) String id) {
        Experiment old = experimentService.getById(id);
        experimentService.fetchExperimentDetail(old);
        Experiment copied = experimentService.copy(old);

        List<ExperimentAnnealProcess> experimentAnnealProcess = experimentAnnealProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentAnnealProcess)) {
            experimentAnnealProcess.forEach(v -> experimentAnnealProcessService.save(v.copy(copied.getId())));
        }
        List<ExperimentRadiationProcess> experimentRadiationProcess = experimentRadiationProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentRadiationProcess)) {
            experimentRadiationProcess.forEach(v -> experimentRadiationProcessService.save(v.copy(copied.getId())));
        }
        List<ExperimentTestProcess> experimentTestProcess = experimentTestProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentTestProcess)) {
            experimentTestProcess.forEach(v -> experimentTestProcessService.save(v.copy(copied.getId())));
        }
        return Result.OK("复制成功!");
    }

    @AutoLog(value = "试验管理-完成试验")
    @Operation(summary = "试验管理-完成试验")
    @PostMapping(value = "/complete")
    public Result<String> complete(@RequestParam(name = "id", required = true) String id) {
        experimentService.changeStatus(id, ExperimentStatus.COMPLETED);
        return Result.OK("试验已完成!");
    }

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

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

    /**
     * 导出excel
     *
     * @param request
     * @param experiment
     */
    @RequiresPermissions("database:experiment:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Experiment experiment) {
        return super.exportXls(request, experiment, Experiment.class, "试验管理");
    }

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

}
