package cn.toesbieya.jxc.controller.sys;
import cn.toesbieya.jxc.model.entity.SysLocation;
import cn.toesbieya.jxc.model.vo.UserVo;
import cn.toesbieya.jxc.model.vo.search.LocationSearch;
import cn.toesbieya.jxc.service.sys.SysLocationService;
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/location")
public class LocationController {
    @Resource
    private SysLocationService service;

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

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

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

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

    private String validateCreateParam(SysLocation location) {
        if (StringUtils.isEmpty(location.getName())) return "货位名称不能为空";
        return null;
    }

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

