package cn.iocoder.yudao.module.relations.service.turnover;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.employee.api.EmployeeApi;
import cn.iocoder.yudao.module.employee.api.dto.EmployeeRespDTO;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.relations.api.turnover.dto.RelationsTurnoverCreateReqDTO;
import cn.iocoder.yudao.module.relations.controller.admin.turnover.vo.RelationsTurnoverPageReqVO;
import cn.iocoder.yudao.module.relations.controller.admin.turnover.vo.RelationsTurnoverRespVO;
import cn.iocoder.yudao.module.relations.controller.admin.turnover.vo.RelationsTurnoverSaveReqVO;
import cn.iocoder.yudao.module.relations.dal.dataobject.turnover.RelationsTurnoverDO;
import cn.iocoder.yudao.module.relations.dal.mysql.turnover.RelationsTurnoverMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.relations.enums.ErrorCodeConstants.RELATIONS_TURNOVER_NOT_EXISTS;

/**
 * 离职信息 Service 实现类
 *
 * @author zhaopq
 */
@Service
@Validated
public class RelationsTurnoverServiceImpl implements RelationsTurnoverService {

    @Resource
    private RelationsTurnoverMapper turnoverMapper;
    @Resource
    private FileApi fileApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private EmployeeApi employeeApi;

    @Override
    public Long createTurnover(RelationsTurnoverSaveReqVO createReqVO) {
        // 获取用户信息和租户ID
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
//        Long tenantId = user != null && user.getTenantId() != null ? user.getTenantId() : 0L;
        Long userId = user != null && user.getId() != null ? user.getId() : 0L;
//        createReqVO.setTenantId(tenantId);
        // 插入
        String infoId = IdUtil.fastSimpleUUID();
        createReqVO.setTurnoverId(infoId);
        // 离职人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(createReqVO.getEmployeeId());
        createReqVO.setEmployeeId(employee.getId());
        createReqVO.setEmployeeName(employee.getName());
        createReqVO.setEmployeePhone(employee.getPhone());
        createReqVO.setDeptId(employee.getDeptId());
        createReqVO.setPosition(employee.getPosition());
        RelationsTurnoverDO turnover = BeanUtils.toBean(createReqVO, RelationsTurnoverDO.class);
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(userId);// 判空检查
        if (loginEmployee != null) {
            turnover.setCreatorEmployeeId(loginEmployee.getId());
            turnover.setCreatorEmployeeName(loginEmployee.getName());
        }
        turnoverMapper.insert(turnover);
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(createReqVO.getFileIdList(), infoId);
        // 返回
        return turnover.getId();
    }

    @Override
    public Long createTurnoverInfoAfterAudit(RelationsTurnoverCreateReqDTO turnoverCreateReqDTO) {
        RelationsTurnoverDO relationsTurnoverDO = BeanUtils.toBean(turnoverCreateReqDTO, RelationsTurnoverDO.class);
        turnoverMapper.insert(relationsTurnoverDO);
        return relationsTurnoverDO.getId();
    }

    @Override
    public void updateTurnover(RelationsTurnoverSaveReqVO updateReqVO) {
        // 校验存在
        validateTurnoverExists(updateReqVO.getId());
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(updateReqVO.getFileIdList(), updateReqVO.getTurnoverId());
        // 离职人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(updateReqVO.getEmployeeId());
        updateReqVO.setEmployeeId(employee.getId());
        updateReqVO.setEmployeeName(employee.getName());
        updateReqVO.setEmployeePhone(employee.getPhone());
        updateReqVO.setDeptId(employee.getDeptId());
        updateReqVO.setPosition(employee.getPosition());
        // 更新
        RelationsTurnoverDO updateObj = BeanUtils.toBean(updateReqVO, RelationsTurnoverDO.class);
        turnoverMapper.updateById(updateObj);
    }

    @Override
    public void deleteTurnover(Long id) {
        // 校验存在
        validateTurnoverExists(id);
        // 删除
        turnoverMapper.deleteById(id);
    }

    private void validateTurnoverExists(Long id) {
        if (turnoverMapper.selectById(id) == null) {
            throw exception(RELATIONS_TURNOVER_NOT_EXISTS);
        }
    }

    @Override
    public RelationsTurnoverDO getTurnover(Long id) {
        return turnoverMapper.selectById(id);
    }

    @Override
    public RelationsTurnoverRespVO getById(Long id) {
        // 第一步：检查ID是否为空
        if (id == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
        // 第二步：从数据库获取数据
        RelationsTurnoverDO turnoverDO = turnoverMapper.selectById(id);
        if (turnoverDO == null) {
            throw exception(RELATIONS_TURNOVER_NOT_EXISTS);
        }
        // 第三步：将DO对象转换为VO对象
        RelationsTurnoverRespVO respVO = BeanUtils.toBean(turnoverDO, RelationsTurnoverRespVO.class);
        if (respVO == null) {
            // 理论上BeanUtils.toBean不应该返回null，但为了安全起见，还是检查一下
            throw new RuntimeException("Failed to convert DO to VO");
        }
        // 第四步：获取附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(turnoverDO.getTurnoverId());
        if (fileList != null) {
            // 如果fileList不为null，则设置到VO对象中
            respVO.setFileList(fileList);
            List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
            respVO.setFileIdList(fileIdList);
        }
        // 部门
        if (turnoverDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(turnoverDO.getDeptId());
            respVO.setDeptName(dept.getName());
            if (dept != null && StringUtils.isNotBlank(dept.getName())) {
                respVO.setDeptName(dept.getName());
            }
        }
        // 第五步：返回VO对象
        return respVO;
    }

    @Override
    public PageResult<RelationsTurnoverDO> getTurnoverPage(RelationsTurnoverPageReqVO pageReqVO) {
        return turnoverMapper.selectPage(pageReqVO);
    }

}