package com.bonus.sgzb.machine.controller;

import com.bonus.sgzb.common.core.web.controller.BaseController;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.core.web.page.TableDataInfo;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.machine.damain.MaHouse;
import com.bonus.sgzb.machine.service.IhouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/house")
public class MaHouseController extends BaseController {

    @Autowired
    private IhouseService houseService;

    /**
     * 查询仓库列表
     * @param house
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(MaHouse house)
    {
        startPage();
        List<MaHouse> list = houseService.selectHouseList(house);
        return getDataTable(list);
    }

    /**
     * 新增仓库货架
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody MaHouse house){
        if (!houseService.checkHouseNameUnique(house)) {
            return error("新增工程项目名称'" + house.getHouseName() + "'失败，工程项目名称已存在");
        }
        house.setCreateBy(SecurityUtils.getUsername());
        return toAjax(houseService.insertHouse(house));
    }

    /**
     * 修改仓库货架
     * @param house
     * @return
     */
    @PutMapping
    public AjaxResult update(@Validated @RequestBody MaHouse house){
        Long houseId = house.getHouseId();
        if (!houseService.checkHouseNameUnique(house)) {
            return error("修改工程项目名称'" + house.getHouseName() + "'失败，工程项目名称已存在");
        } else if (house.getParentId().equals(houseId)) {
            return error("修改失败'" + house.getHouseName() + "'失败，上级部门不能是自己");
        }
        house.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(houseService.updatetHouse(house));
    }

    /**
     * 删除仓库货架
     * @param houseId
     * @return
     */
    @DeleteMapping("/{houseId}")
    public AjaxResult delete(@PathVariable("houseId") Long houseId){
        if (houseService.hasChildByHouseId(houseId))
        {
            return warn("存在下级仓库列表,不允许删除");
        }
        return toAjax(houseService.deleteHouseById(houseId));
    }

}
