package com.pangu.base.controller;

import com.pangu.base.domain.Region;
import com.pangu.base.service.IRegionService;
import com.pangu.common.core.controller.BaseController;
import com.pangu.common.core.domain.AjaxResult;
import com.pangu.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 区域管理Controller
 * @author pangu
 */
@RestController
@RequestMapping("/api/region")
public class RegionController extends BaseController {

    @Autowired
    private IRegionService regionService;

    /**
     * 获取区域树
     */
    @GetMapping("/tree")
    public AjaxResult tree() {
        List<Region> list = regionService.selectRegionTree();
        return success(list);
    }

    /**
     * 获取区域列表（树形结构）
     */
    @GetMapping("/list")
    public AjaxResult list(Region region) {
        List<Region> list = regionService.selectRegionTree();
        return success(list);
    }

    /**
     * 获取区域详情
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long regionId) {
        return success(regionService.selectRegionById(regionId));
    }

    /**
     * 新增区域
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Region region) {
        region.setCreateBy("admin");
        return toAjax(regionService.insertRegion(region));
    }

    /**
     * 修改区域
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Region region) {
        if (region.getRegionId().equals(region.getParentId())) {
            return error("父级区域不能选择自己");
        }
        region.setUpdateBy("admin");
        return toAjax(regionService.updateRegion(region));
    }

    /**
     * 删除区域
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long regionId) {
        // 检查是否有子区域
        if (regionService.hasChildRegion(regionId)) {
            return error("存在下级区域，不能删除");
        }
        // TODO: 检查是否被学校引用
        return toAjax(regionService.deleteRegionById(regionId));
    }
}
