package yangtz.cs.liu.campus.controller.assetsType;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.domain.assetsType.SchoolAssetsType;
import yangtz.cs.liu.campus.service.assetsType.ISchoolAssetsTypeService;
import yangtz.cs.liu.campus.vo.assetsType.SchoolAssetsTypeVo;

import java.util.List;

@RestController
@RequestMapping("/schoolAssetsType")
public class SchoolAssetsTypeController extends BaseController {

    @Autowired
    private ISchoolAssetsTypeService typeService;

    /**查询资产分类列表*/
    @GetMapping("/list")
    public AjaxResult list(SchoolAssetsType type){
        List<SchoolAssetsTypeVo> types = typeService.selectTypeList(type);
        return AjaxResult.success(types);
    }

    /**根据id查询单个*/
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable Long id){
        return AjaxResult.success(typeService.getInfo(id));
    }

    /**新增*/
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolAssetsType type){
       Boolean flag = typeService.checkIsExist(type);
       //存在
        if (flag) {
            throw new ServiceException("该资产分类已存在，请勿重复添加");
        }
        SchoolAssetsType assetsType = typeService.getById(type.getPid());
        //这种情况父节点为0，查不出来东西
        if(StringUtils.isNull(assetsType)){
            type.setAncestors(type.getPid().toString());
        }
        if (StringUtils.isNotNull(assetsType)){
            type.setAncestors(assetsType.getAncestors() + "," + type.getPid());
        }
        type.insert();
        return toAjax(typeService.save(type));
    }

    /**修改*/
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolAssetsType type){
        if(StringUtils.isNull(type.getId())){
            throw new ServiceException("id为空");
        }
        Boolean flag = typeService.checkIsExist(type);
        //存在
        if (flag) {
            throw new ServiceException("该资产分类已存在，请勿重复添加");
        }
        if(type.getPid().equals(type.getId())){
            return AjaxResult.error("修改资产分类'" + type.getTypeName() + "'失败，上级不能是自己");
        }
        type.update();
        return toAjax(typeService.updateType(type));
    }

    /**删除*/
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id){
        if(typeService.hasChildById(id)){
            return AjaxResult.error("存在下级资产,不允许删除");
        }
        return toAjax(typeService.removeById(id));
    }

    /**资产分类树列表*/
    @GetMapping("/typeTree")
    public AjaxResult typeTree(SchoolAssetsType type){
        return AjaxResult.success(typeService.selectTypeTreeList(type));
    }
}
