package com.bonus.sgzb.base.controller;

import com.bonus.sgzb.base.domain.MaHouse;
import com.bonus.sgzb.base.service.IhouseService;
import com.bonus.sgzb.common.core.web.controller.BaseController;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "仓库货架管理")
@RequestMapping("/base/house")
public class MaHouseController extends BaseController {

    @Autowired
    private IhouseService houseService;

    /**
     * 查询仓库列表
     * @param house
     * @return
     */
    @ApiOperation(value = "查询仓库货架列表")
    @GetMapping("/list")
    public AjaxResult list(MaHouse house)
    {
        List<MaHouse> list = houseService.selectHouseList(house);
        return AjaxResult.success(list);
    }

    /**
     * 查询仓库组织树列表
     * @param house
     * @return
     */
    @ApiOperation(value = "查询仓库组织树列表")
    @GetMapping("/tree")
    public AjaxResult tree(MaHouse house)
    {
        return success(houseService.getHouseTree(house));
    }

    /**
     * 获取仓库管理ma_house_info详细信息
     */
    @GetMapping(value = "/{houseId}")
    public AjaxResult getInfo(@PathVariable("houseId") Long houseId)
    {
        return success(houseService.selectMaHouseByHouseId(houseId));
    }

    /**
     * 新增仓库货架
     */
    @ApiOperation(value = "新增仓库货架")
    @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
     */
    @ApiOperation(value = "修改仓库货架")
    @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
     */
    @ApiOperation(value = "删除仓库货架")
    @DeleteMapping("/{houseId}")
    public AjaxResult delete(@PathVariable("houseId") Long houseId){
        if (houseService.hasChildByHouseId(houseId))
        {
            return warn("存在下级仓库列表,不允许删除");
        }
        return toAjax(houseService.deleteHouseById(houseId));
    }

}
