package cn.toesbieya.jxc.controller.sys;

import cn.toesbieya.jxc.model.entity.SysEquipment;
import cn.toesbieya.jxc.model.vo.UserVo;
import cn.toesbieya.jxc.model.vo.search.EquipmentSearch;
import cn.toesbieya.jxc.service.sys.SysEquipmentService;
import cn.toesbieya.jxc.model.vo.R;
import cn.toesbieya.jxc.util.SessionUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("system/equipment")
public class EquipmentController {
    @Resource
    private SysEquipmentService service;

    @PostMapping("search")
    public R search(@RequestBody EquipmentSearch vo) {
        return R.success(service.search(vo));
    }

    @PostMapping("add")
    public R add(@RequestBody SysEquipment equipment) {
        String errMsg = validateCreateParam(equipment);
        if (errMsg != null) return R.fail("添加失败，" + errMsg);
        UserVo user = SessionUtil.get();
        equipment.setId(null);
        equipment.setCreateTime(System.currentTimeMillis());
        equipment.setCreatorId(user.getId());
        equipment.setCreatorName(user.getNickName());
        return service.add(equipment);
    }

    @PostMapping("update")
    public R update(@RequestBody SysEquipment equipment) {
        String errMsg = validateUpdateParam(equipment);
        return errMsg == null ? service.update(equipment) : R.fail("修改失败，" + errMsg);
    }

    @PostMapping("del")
    public R del(@RequestBody SysEquipment equipment) {
        if (equipment.getId() == null) return R.fail("删除失败，参数错误");
        return service.del(equipment);
    }

    private String validateCreateParam(SysEquipment equipment) {
        if (StringUtils.isEmpty(equipment.getName())) return "设备名称不能为空";
        return null;
    }

    private String validateUpdateParam(SysEquipment equipment) {
        if (equipment.getId() == null) return "参数错误";
        return validateCreateParam(equipment);
    }
}

