package org.springblade.system.service.impl;

import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.core.domain.AjaxResult;
import org.springblade.common.core.domain.entity.SysDept;
import org.springblade.common.core.domain.entity.SysRole;
import org.springblade.common.utils.DateUtils;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.system.domain.DaKyProFilesContentsDto;
import org.springblade.system.domain.ProSelectDto;
import org.springblade.system.domain.TransferApplyDto;
import org.springblade.system.domain.TransferFileDto;
import org.springblade.system.mapper.TransferApplyMapper;
import org.springblade.system.service.TransferApplyService;
import org.springblade.system.tool.TreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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



/**
 * @Author：liang.chao
 * @Date：2025/9/15 - 11:27
 */
@Service
public class TransferApplyServiceImpl implements TransferApplyService {
    @Resource
    private TransferApplyMapper transferApplyMapper;

    @Override
    public List<TransferApplyDto> list(TransferApplyDto dto) {
        if (dto.getDeptId() != null) {
            // 查询该部门下所有子部门
            List<String> deptIds = transferApplyMapper.getDeptList(dto);
            dto.setDeptIds(deptIds);
        }
        return transferApplyMapper.list(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(TransferApplyDto dto) {
        try {
            dto.setAuditStatus("0");
            dto.setApplyUser(AuthUtil.getUser().getUserId().toString());
            dto.setApplyTime(DateUtils.getDate());
            dto.setCreateUserId(AuthUtil.getUser().getUserId());
            dto.setCreateUserName(AuthUtil.getUser().getUserName());
            dto.setUpdateUserId(AuthUtil.getUser().getUserId());
            dto.setUpdateUserName(AuthUtil.getUser().getUserName());
            String proName = transferApplyMapper.getProNameById(dto);
            dto.setProName(proName);
            Integer i = transferApplyMapper.insert(dto);
            List<TransferFileDto> transferFileDtos = dto.getTransferFileDtos();
            for (TransferFileDto transferFileDto : transferFileDtos) {
                transferFileDto.setTransferApplyId(Integer.parseInt(dto.getId()));
                transferApplyMapper.insertTransferFile(transferFileDto);
            }
            return i > 0 ? AjaxResult.success("保存成功") : AjaxResult.error("保存失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    @Override
    public TransferApplyDto getTransferApply(TransferApplyDto dto) {
        TransferApplyDto transferApply = transferApplyMapper.getTransferApply(dto);
        if (transferApply != null) {
            transferApply.setTransferFileDtos(transferApplyMapper.getTransferFile(dto));
            return transferApply;
        } else {
            return new TransferApplyDto();
        }
    }

    @Override
    public AjaxResult edit(TransferApplyDto dto) {
        try {
            dto.setAuditStatus("0");
            dto.setUpdateUserId(AuthUtil.getUser().getUserId());
            dto.setUpdateUserName(AuthUtil.getUser().getUserName());
            transferApplyMapper.edit(dto);
            // 先删后增
            Integer i = transferApplyMapper.delTransferFiles(dto);
            List<TransferFileDto> transferFileDtos = dto.getTransferFileDtos();
            for (TransferFileDto transferFileDto : transferFileDtos) {
                transferFileDto.setTransferApplyId(Integer.parseInt(dto.getId()));
                transferApplyMapper.insertTransferFile(transferFileDto);
            }
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
        } catch (Exception e) {
            return AjaxResult.error("接口异常");
        }
    }

    @Override
    public AjaxResult del(TransferApplyDto dto) {
        Integer i = transferApplyMapper.delTransferFiles(dto);
        if (i > 0) {
            Integer i2 = transferApplyMapper.delRecord(dto);
            Integer i1 = transferApplyMapper.del(dto);
            return i1 > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } else {
            return AjaxResult.error("档案删除失败");
        }
    }

    @Override
    public AjaxResult audit(TransferApplyDto dto) {
		String roleName = AuthUtil.getUser().getRoleName();
//        if (roleName.equals("档案管理员")) {
            dto.setAuditUser(AuthUtil.getUser().getUserId().toString());
            dto.setAuditUserName(AuthUtil.getUser().getUserName());
            Integer i = transferApplyMapper.audit(dto);
            if (i > 0) {
                transferApplyMapper.addTransferAuditRecord(dto);
                return AjaxResult.success("审核成功");
            }
            return AjaxResult.error("审核失败");
//        } else {
//            return AjaxResult.error("您没有权限审核");
//        }
    }

    @Override
    public List<SysDept> getDeptSelect(TransferApplyDto dto) {
        List<SysDept> deptSelect = transferApplyMapper.getDeptSelect(dto);
        // 构建树
        List<SysDept> tree = TreeBuilder.buildDeptTree(deptSelect);
        return tree;
    }

    @Override
    public List<ProSelectDto> getProSelect(TransferApplyDto dto) {
        return transferApplyMapper.getProSelect(dto);
    }

    @Override
    public List<DaKyProFilesContentsDto> getTransferApplyFiles(TransferApplyDto dto) {
        List<String> contents = transferApplyMapper.getTransferApplyFilesContents(dto);
        List<DaKyProFilesContentsDto> list = new ArrayList<>();
        for (String content : contents) {
            dto.setParentId(content);
            List<DaKyProFilesContentsDto> dtos = transferApplyMapper.getTransferApplyFiles(dto);
            list.addAll(dtos);
        }
        return list;
    }

    @Override
    public List<TransferFileDto> getTransferRecordFiles(TransferFileDto dto) {
        return transferApplyMapper.getTransferRecordFiles(dto);
    }

    @Override
    public AjaxResult updateTransferRecordFile(TransferFileDto dto) {
        Integer i = transferApplyMapper.updateTransferRecordFile(dto);
        return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    @Override
    public List<DaKyProFilesContentsDto> getTransferApplyFilesByApplyId(TransferApplyDto dto) {
        return transferApplyMapper.getTransferApplyFilesByApplyId(dto);
    }

    @Override
    public AjaxResult transferReceive(TransferFileDto dto) {
        try {
            Integer i = transferApplyMapper.transferReceive(dto);
            // 查询该申请下，是否所有文件都已接收
            Integer num = transferApplyMapper.isAllReceive(dto);
            if (num == 1) {
                transferApplyMapper.updateReceiveStatus(dto);
            }
            // 如果该项目下所有文件都已接收，则修改项目移交状态
            Integer allReceiveByProject = transferApplyMapper.isAllReceiveByProject(dto);
            if (allReceiveByProject == 1) {
                transferApplyMapper.updateProjectFileStatus(dto);
            }
            if (i > 0) {
                return AjaxResult.success("接收成功");
            } else {
                return AjaxResult.error("接收失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("接口异常");
        }
    }

    @Override
    public AjaxResult updateTransferRecordFilesStatus(TransferFileDto dto) {
        // 修改档案移交状态
        Integer i = transferApplyMapper.updateTransferRecordFilesStatus(dto);
        // 查询申请表中有没有移交时间，没有的话设置第一次移交时间
        String transferApplyTransferTime = transferApplyMapper.getTransferApplyTransferTime(dto);
        if (StringUtils.isBlank(transferApplyTransferTime)) {
            transferApplyMapper.setTransferTime(dto);
        }
        // 查询该申请下，是否所有文件都已移交
        Integer num = transferApplyMapper.getAllTransferStatus(dto);
        if (num == 1) {
            transferApplyMapper.updateTransferStatus(dto);
        }
        return i > 0 ? AjaxResult.success("移交成功") : AjaxResult.error("移交失败");
    }
}
