package cn.toesbieya.jxc.controller.sys;

import cn.toesbieya.jxc.model.entity.SysStorehouse;
import cn.toesbieya.jxc.model.vo.R;
import cn.toesbieya.jxc.model.vo.UserVo;
import cn.toesbieya.jxc.model.vo.search.StorehouseSearch;
import cn.toesbieya.jxc.service.sys.SysStorehouseService;
import cn.toesbieya.jxc.util.SessionUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("system/storehouse")
public class StorehouseController {
    @Resource
    private SysStorehouseService service;

    @GetMapping("get")
    public R get() {
        return R.success(service.get());
    }

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

    @PostMapping("add")
    public R add(@RequestBody SysStorehouse storehouse) {
        String errMsg = validateCreateParam(storehouse);
        if (errMsg != null) return R.fail("添加失败，" + errMsg);

        //添加创建人、创建时间
        UserVo user = SessionUtil.get();
        storehouse.setCreatorId(user.getId());
        storehouse.setCreatorName(user.getNickName());
        storehouse.setCreateTime(System.currentTimeMillis());
        return service.add(storehouse);
    }

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

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

    private String validateCreateParam(SysStorehouse storehouse) {
        if (StringUtils.isEmpty(storehouse.getId())) return "仓库编号不能为空";
        if (StringUtils.isEmpty(storehouse.getName())) return "仓库名称不能为空";
        if (storehouse.getLevel() == null) return "仓库级别不能为空";
        if (storehouse.getType() == null) return "仓库类型不能为空";
        return null;
    }

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


}
