package org.springblade.system.controller;


import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.annotation.RequiresPermissions;
import org.springblade.common.annotation.SysLog;
import org.springblade.common.core.controller.BaseController;
import org.springblade.common.core.domain.AjaxResult;
import org.springblade.common.core.domain.R;
import org.springblade.common.core.page.TableDataInfo;
import org.springblade.common.enums.OperaType;
import org.springblade.common.utils.sql.SqlUtil;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.system.domain.ArchivalCatalogueDto;
import org.springblade.system.domain.SelectDto;
import org.springblade.system.domain.vo.ArchivalCatalogueVo;
import org.springblade.system.mapper.ArchiveMapper;
import org.springblade.system.service.ArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 档案目录管理
 * @Author: lc
 * @Date: 2025/10/31
 */
@RestController
@RequestMapping("/archive")
@Slf4j
@NonDS
public class ArchiveController extends BaseController {

    @Autowired
    private ArchiveService service;

    @Resource
    private ArchiveMapper archiveMapper;

    @PostMapping("getArchivalCatalogueTree")
    @SysLog(title = "档案目录", module = "档案管理->档案目录管理", businessType = OperaType.QUERY, details = "查询档案目录", logType = 1)
    @RequiresPermissions("archive:catalogue:list")
    public R<List<ArchivalCatalogueDto>> getArchivalCatalogueTree(@RequestBody ArchivalCatalogueDto dto) {
        try {
            List<ArchivalCatalogueDto> list = service.getArchivalCatalogueTree(dto);
            return R.ok(list);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("getArchivalCatalogue")
    @SysLog(title = "第四级档案目录", module = "档案管理->档案目录管理", businessType = OperaType.QUERY, details = "查询第四级档案目录", logType = 1)
    @RequiresPermissions("archive:catalogue:list")
    public TableDataInfo getArchivalCatalogue(@RequestBody ArchivalCatalogueDto dto) {
        try {
			// 直接使用 dto 中的分页参数
			PageHelper.startPage(dto.getPageNum() != null ? dto.getPageNum() : 1,
					dto.getPageSize() != null ? dto.getPageSize() : 10,
					SqlUtil.escapeOrderBySql(dto.getOrderBy()))
				.setReasonable(dto.getReasonable() != null ? dto.getReasonable() : true);

            List<ArchivalCatalogueDto> list = service.getArchivalCatalogue(dto);
            return getDataTable(list);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return getDataTable(new ArrayList<>());
        }
    }

    @PostMapping("addRight")
    @SysLog(title = "新增档案右侧目录", module = "档案管理->档案目录管理", businessType = OperaType.INSERT, details = "新增档案右侧目录", logType = 1)
    @RequiresPermissions("archive:catalogue:add")
    public R saveArchivalCatalogue(@RequestBody @Validated ArchivalCatalogueDto dto) {
        try {
            if (dto.getParentId() == null) {
                return R.fail("父级有误");
            }
            if (dto.getLevel() == null) {
                return R.fail("级别有误");
            }
            return service.saveArchivalCatalogue(dto);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("addLeft")
    @SysLog(title = "新增档案左侧目录", module = "档案管理->档案目录管理", businessType = OperaType.INSERT, details = "新增档案左侧目录", logType = 1)
    @RequiresPermissions("archive:catalogue:add")
    public R saveArchivalCatalogue(@RequestBody @Validated ArchivalCatalogueVo vo) {
        try {
            if (vo.getParentId() == null) {
                return R.fail("父级有误");
            }
            if (vo.getLevel() == null) {
                return R.fail("级别有误");
            }
            Integer num = service.geMaxSort(vo.getParentId().toString());
            if (num == null) {
                num = 0;
            }
            if (vo.getSort() <= num) {
                return R.fail("排序序号需大于" + num);
            }
            return service.saveArchivalCatalogue(vo);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("getArchivalCatalogueById")
    @SysLog(title = "查询单个档案记录", module = "档案管理->档案目录管理", businessType = OperaType.QUERY, details = "查询单个档案记录", logType = 1)
    @RequiresPermissions("archive:catalogue:query")
    public R<ArchivalCatalogueDto> getArchivalCatalogueById(@RequestBody ArchivalCatalogueDto dto) {
        try {
            ArchivalCatalogueDto archivalCatalogueDto = service.getArchivalCatalogueById(dto);
            return R.ok(archivalCatalogueDto);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("editRight")
    @SysLog(title = "修改档案目录", module = "档案管理->档案目录管理", businessType = OperaType.UPDATE, details = "修改档案目录", logType = 1)
    @RequiresPermissions("archive:catalogue:edit")
    public R editArchivalCatalogue(@RequestBody @Validated ArchivalCatalogueDto dto) {
        try {
            return service.editArchivalCatalogue(dto);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("editLeft")
    @SysLog(title = "修改档案目录", module = "档案管理->档案目录管理", businessType = OperaType.UPDATE, details = "修改档案目录", logType = 1)
    @RequiresPermissions("archive:catalogue:edit")
    public R editArchivalCatalogue(@RequestBody @Validated ArchivalCatalogueVo vo) {
        try {
            ArchivalCatalogueDto dto = new ArchivalCatalogueDto();
            dto.setId(vo.getId());
            // 如果子集有数据 无法修改
            Integer child = archiveMapper.getchild(dto);
            if (child > 0){
                return R.fail("该节点下存在子节点或该节点下存在档案文件，无法修改");
            }
            Integer num = service.geMaxSort(vo.getParentId().toString());
            if (num == null) {
                num = 0;
            }
            int sort = service.getSortById(vo.getId());
            if (sort != vo.getSort() && vo.getSort() <= num) {
                return R.fail("排序序号需大于" + num);
            }
            return service.editArchivalCatalogue(vo);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("del")
    @SysLog(title = "删除档案目录", module = "档案管理->档案目录管理", businessType = OperaType.DELETE, details = "删除档案目录", logType = 1)
    @RequiresPermissions("archive:catalogue:del")
    public R<List<ArchivalCatalogueDto>> delArchivalCatalogue(@RequestBody ArchivalCatalogueDto dto) {
        try {
            Integer i = service.delArchivalCatalogue(dto);
            if (i > 0) {
                return R.ok();
            } else {
                return R.fail("该节点下存在子节点或该节点下存在档案文件，无法删除");
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return R.fail("请求出错了");
        }
    }

    @PostMapping("getFilesClassifyMarkSelect")
    @SysLog(title = "档案分类标记下拉", module = "档案管理->档案分类标记下拉", businessType = OperaType.QUERY, details = "档案分类标记下拉", logType = 1)
    public AjaxResult getFilesClassifyMarkSelect(@RequestBody ArchivalCatalogueDto dto) {
        try {
            List<SelectDto> list = service.getFilesClassifyMarkSelect(dto);
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return AjaxResult.error("请求出错了");
        }
    }

    @PostMapping("geMaxSort")
    @SysLog(title = "查询最大sort", module = "档案管理->查询最大sort", businessType = OperaType.QUERY, details = "查询最大sort", logType = 1)
    public AjaxResult geMaxSort(@RequestBody ArchivalCatalogueDto dto) {
        try {
            Integer num = service.geMaxSort(dto.getParentId().toString());
            if (num == null) {
                num = 0;
             }
            return AjaxResult.success(num);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return AjaxResult.error("请求出错了");
        }
    }

}
