package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.SysAreaBo;
import org.dromara.system.domain.vo.SysAreaVo;
import org.dromara.system.service.ISysAreaService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 区域信息
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/area")
public class SysAreaController extends BaseController {

    private final ISysAreaService areaService;

    /**
     * 获取区域列表
     */
    @SaCheckPermission("system:area:list")
    @GetMapping("/list")
    public R<List<SysAreaVo>> list(SysAreaBo area) {
        List<SysAreaVo> areas = areaService.selectAreaList(area);
        return R.ok(areas);
    }

    /**
     * 查询区域列表（排除节点）
     *
     * @param areaId 区域ID
     */
    @SaCheckPermission("system:area:list")
    @GetMapping("/list/exclude/{areaId}")
    public R<List<SysAreaVo>> excludeChild(@PathVariable(value = "areaId", required = false) Long areaId) {
        List<SysAreaVo> areas = areaService.selectAreaList(new SysAreaBo());
        areas.removeIf(d -> d.getAreaId().equals(areaId)
            || StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(areaId)));
        return R.ok(areas);
    }

    /**
     * 根据区域编号获取详细信息
     *
     * @param areaId 区域ID
     */
    @SaCheckPermission("system:area:query")
    @GetMapping(value = "/{areaId}")
    public R<SysAreaVo> getInfo(@PathVariable Long areaId) {
        areaService.checkAreaDataScope(areaId);
        return R.ok(areaService.selectAreaById(areaId));
    }

    /**
     * 新增区域
     */
    @SaCheckPermission("system:area:add")
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysAreaBo area) {
        if (!areaService.checkAreaNameUnique(area)) {
            return R.fail("新增区域'" + area.getAreaName() + "'失败，区域名称已存在");
        }
        return toAjax(areaService.insertArea(area));
    }

    /**
     * 修改区域
     */
    @SaCheckPermission("system:area:edit")
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody SysAreaBo area) {
        Long areaId = area.getAreaId();
        areaService.checkAreaDataScope(areaId);
        if (!areaService.checkAreaNameUnique(area)) {
            return R.fail("修改区域'" + area.getAreaName() + "'失败，区域名称已存在");
        } else if (area.getParentId().equals(areaId)) {
            return R.fail("修改区域'" + area.getAreaName() + "'失败，上级区域不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, area.getStatus())) {
            if (areaService.selectNormalChildrenAreaById(areaId) > 0) {
                return R.fail("该区域包含未停用的子区域!");
            } else if (areaService.checkAreaExistUser(areaId)) {
                return R.fail("该区域下存在已分配用户，不能禁用!");
            }
        }
        return toAjax(areaService.updateArea(area));
    }

    /**
     * 删除区域
     *
     * @param areaId 区域ID
     */
    @SaCheckPermission("system:area:remove")
    @Log(title = "区域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{areaId}")
    public R<Void> remove(@PathVariable Long areaId) {
        if (areaService.hasChildByAreaId(areaId)) {
            return R.warn("存在下级区域,不允许删除");
        }
        if (areaService.checkAreaExistUser(areaId)) {
            return R.warn("区域存在用户,不允许删除");
        }
        areaService.checkAreaDataScope(areaId);
        return toAjax(areaService.deleteAreaById(areaId));
    }

    /**
     * 获取区域选择框列表
     *
     * @param areaIds 区域ID串
     */
    @SaCheckPermission("system:area:query")
    @GetMapping("/optionselect")
    public R<List<SysAreaVo>> optionselect(@RequestParam(required = false) Long[] areaIds) {
        return R.ok(areaService.selectAreaByIds(areaIds == null ? null : List.of(areaIds)));
    }

}
