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.*;

/**
 * @Description: 试验人员
 * @Author: jeecg-boot
 * @Date: 2024-08-30
 * @Version: V1.0
 */
@Tag(name = "试验人员")
@RestController
@RequestMapping("/database/experimentUser")
@Slf4j
public class ExperimentUserController extends JeecgController<ExperimentUser, IExperimentUserService> {
    @Autowired
    private IExperimentUserService experimentUserService;

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

    @Autowired
    private IExperimentService experimentService;

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

    /**
     * 添加
     *
     * @param experimentUser
     * @return
     */
    @AutoLog(value = "试验人员-添加")
    @Operation(summary = "试验人员-添加")
    @RequiresPermissions("database:experiment_user:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExperimentUser experimentUser, HttpServletRequest request) {
        String experimentId = experimentUser.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)) {
            return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
        }
        experimentUserService.save(experimentUser);
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experimentUser.getExperimentId());
        experimentLog.setLogContent("添加试验人员");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "试验人员-批量添加")
    @Operation(summary = "试验人员-批量添加")
    @RequiresPermissions("database:experiment_user:add")
    @PostMapping(value = "/batchAdd")
    public Result<String> batchAdd(@RequestBody List<ExperimentUser> experimentUserList, HttpServletRequest request) {
        for (ExperimentUser v : experimentUserList) {
            String experimentId = v.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)) {
                return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
            }
            experimentUserService.save(v);
        }
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experimentUserList.get(0).getExperimentId());
        experimentLog.setLogContent("添加试验人员");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param experimentUser
     * @return
     */
    @AutoLog(value = "试验人员-编辑")
    @Operation(summary = "试验人员-编辑")
    @RequiresPermissions("database:experiment_user:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExperimentUser experimentUser, HttpServletRequest request) {
        experimentUserService.updateById(experimentUser);
        ExperimentUser byId = experimentUserService.getById(experimentUser.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)) {
            return Result.error("试验状态:[" + dbExperiment.getStatus() + "]不能进行修改！");
        }
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(byId.getExperimentId());
        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_user:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id, HttpServletRequest request) {
        ExperimentUser experimentUser = experimentUserService.getById(id);
        String experimentId = experimentUser.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)) {
            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);
        experimentUserService.removeById(id);

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

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

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

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

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

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExperimentUser experimentUser) {
        return super.exportXls(request, experimentUser, ExperimentUser.class, "试验人员");
    }

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

}
