package com.jd.lightapplication.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.model.InspectionProject;
import com.jd.lightapplication.model.dto.InspectionProjectQueryDto;
import com.jd.lightapplication.service.InspectionProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;


@Slf4j
@RestController()
@RequestMapping("/api/inspection/project")
@Api(tags = "巡检项目表")
public class InspectionProjectController {

    @Resource
    private InspectionProjectService inspectionProjectService;

    @GetMapping("/list")
    @ApiOperation(value = "1、分页查询")
    public R queryPageBean(Page page, InspectionProjectQueryDto inspectionProjectQueryDto) {
        LambdaQueryWrapper<InspectionProject> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(inspectionProjectQueryDto.getName())) {
            wrapper.like(InspectionProject::getName, inspectionProjectQueryDto.getName());
        }
        wrapper.orderByDesc(InspectionProject::getCreateTime);
        return R.success(inspectionProjectService.page(page, wrapper));
    }

    @PostMapping("/addBean")
    @ApiOperation(value = "2、新增")
    public R addBean(@RequestBody InspectionProject inspectionProject) {
        this.checkProjectNameExists(inspectionProject.getName());
        inspectionProjectService.save(inspectionProject.setCreateTime(DateUtil.now()));
        return R.success();
    }

    @PostMapping("/updateBean")
    @ApiOperation(value = "3、修改")
    public R updateBean(@RequestBody InspectionProject inspectionProject) {
        this.checkProjectNameExists(inspectionProject.getName());
        inspectionProjectService.updateById(inspectionProject.setUpdateTime(DateUtil.now()));
        return R.success();
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "4、删除")
    public R deleteById(long id) {
        inspectionProjectService.removeById(id);
        return R.success();
    }

    /**
     * 验证巡检项目名称是否存在
     * @param projectName
     */
    private void checkProjectNameExists(String projectName) {
        //先判断名称是否存在，如果存在抛异常
        LambdaQueryWrapper<InspectionProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InspectionProject::getName, projectName);
        if (inspectionProjectService.list(wrapper).size() > 0) {
            throw new RuntimeException("【" + projectName + "】已存在！");
        }
    }
}