package org.dromara.controller.asset;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.web.core.BaseController;
import org.dromara.domain.asset.bo.AssetTypeBo;
import org.dromara.domain.asset.vo.AssetTypeVo;
import org.dromara.service.IAssetTypeService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.dromara.common.core.constant.Constants.ONE;

/**
 * 资产类型
 *
 * @author boman
 * @date 2025-04-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wuYe/assetType")
public class AssetTypeController extends BaseController {

    private final IAssetTypeService assetTypeService;

    /**
     * 查询资产类型列表
     */
    /*@SaCheckPermission("wuYe:assetType:list")
    @GetMapping("/list")
    public TableDataInfo<AssetTypeVo> list(AssetTypeBo bo, PageQuery pageQuery) {
        return assetTypeService.queryPageList(bo, pageQuery);
    }*/

    /**
     * 查询资产类型列表(不分页)
     */
    @SaCheckPermission("wuYe:assetType:list")
    @GetMapping("/list")
    public List<AssetTypeVo> list(AssetTypeBo bo) {
        return assetTypeService.queryList(bo);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @SaCheckPermission("wuYe:assetType:list")
    @GetMapping("/list/exclude/{assetId}")
    public R<List<AssetTypeVo>> excludeChild(@PathVariable Long assetId)
    {
        List<AssetTypeVo> assetTypes = assetTypeService.queryList(new AssetTypeBo());
        assetTypes.removeIf(d -> d.getAssetId().intValue() == assetId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), assetId + ""));
        return R.ok(assetTypes);
    }


    /**
     * 导出资产类型列表
     */
    @SaCheckPermission("wuYe:assetType:export")
    @Log(title = "资产类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(AssetTypeBo bo, HttpServletResponse response) {
        List<AssetTypeVo> list = assetTypeService.queryList(bo);
        ExcelUtil.exportExcel(list, "资产类型", AssetTypeVo.class, response);
    }

    /**
     * 获取资产类型详细信息
     *
     * @param assetId 主键
     */
    @SaCheckPermission("wuYe:assetType:query")
    @GetMapping("/{assetId}")
    public R<AssetTypeVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long assetId) {
        return R.ok(assetTypeService.queryById(assetId));
    }

    /**
     * 新增资产类型
     */
    @SaCheckPermission("wuYe:assetType:add")
    @Log(title = "资产类型", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody AssetTypeBo bo) {
        if (!assetTypeService.checkAssetTypeNameUnique(bo))
        {
            return R.fail("新增资产'" + bo.getAssetName() + "'失败，资产名称已存在");
        }
        return toAjax(assetTypeService.insertByBo(bo));
    }

    /**
     * 修改资产类型
     */
    @SaCheckPermission("wuYe:assetType:edit")
    @Log(title = "资产类型", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/put")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody AssetTypeBo bo) {
        Long assetId = bo.getAssetId();
        if (!assetTypeService.checkAssetTypeNameUnique(bo))
        {
            return R.fail("新增资产'" + bo.getAssetName() + "'失败，资产名称已存在");
        }
        else if (bo.getParentId().equals(assetId))
        {
            return R.fail("修改资产'" + bo.getAssetName() + "'失败，上级资产不能是自己");
        }
        else if (StringUtils.equals(ONE, bo.getStatus()) && assetTypeService.selectNormalChildrenAssetById(assetId) > 0)
        {
            return R.fail("该部门包含未停用的子部门！");
        }
        return toAjax(assetTypeService.updateByBo(bo));
    }

    /**
     * 删除资产类型
     *
     * @param assetIds 主键串
     */
    @SaCheckPermission("wuYe:assetType:remove")
    @Log(title = "资产类型", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{assetIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] assetIds) {
        for (Long assetId : assetIds) {
            if (assetTypeService.hasChildByAssetId(assetId))
            {
                return R.warn("存在下级资产,不允许删除");
            }
        }
        return toAjax(assetTypeService.deleteWithValidByIds(List.of(assetIds), true));
    }

    /**
     * 获取资产分类树列表
     */
    @SaCheckPermission("wuYe:assetType:deptTree")
    @GetMapping("/deptTree")
    public R<List<Tree<Long>>> deptTree(AssetTypeBo bo)
    {
        return assetTypeService.selectAssetTypeTreeList(bo);
    }

}
