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

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.conversion.dto.RelationsConversionCreateReqDTO;
import cn.iocoder.yudao.module.relations.controller.admin.conversion.vo.RelationsConversionPageReqVO;
import cn.iocoder.yudao.module.relations.controller.admin.conversion.vo.RelationsConversionRespVO;
import cn.iocoder.yudao.module.relations.controller.admin.conversion.vo.RelationsConversionSaveReqVO;
import cn.iocoder.yudao.module.relations.dal.dataobject.conversion.RelationsConversionDO;
import cn.iocoder.yudao.module.relations.dal.mysql.conversion.RelationsConversionMapper;
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_CONVERSION_NOT_EXISTS;

/**
 * 转正信息 Service 实现类
 *
 * @author zhaopq
 */
@Service
@Validated
public class RelationsConversionServiceImpl implements RelationsConversionService {

    @Resource
    private RelationsConversionMapper conversionMapper;
    @Resource
    private FileApi fileApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private EmployeeApi employeeApi;

    @Override
    public Long createConversion(RelationsConversionSaveReqVO 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);
        // 转正人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(createReqVO.getEmployeeId());
        createReqVO.setEmployeeId(employee.getId());
        createReqVO.setEmployeeName(employee.getName());
        createReqVO.setEmployeePhone(employee.getPhone());
        createReqVO.setDeptId(employee.getDeptId());
        createReqVO.setPostId(employee.getPostId());
        createReqVO.setPosition(employee.getPosition());
        // 插入
        String infoId = IdUtil.fastSimpleUUID();
        createReqVO.setConversionId(infoId);
        RelationsConversionDO conversion = BeanUtils.toBean(createReqVO, RelationsConversionDO.class);
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(userId);// 判空检查
        if (loginEmployee != null) {
            conversion.setCreatorEmployeeId(loginEmployee.getId());
            conversion.setCreatorEmployeeName(loginEmployee.getName());
        }
        conversionMapper.insert(conversion);
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(createReqVO.getFileIdList(), infoId);
        // 返回
        return conversion.getId();
    }

    @Override
    public Long createConversionInfoAfterAudit(RelationsConversionCreateReqDTO conversionCreateReqDTO) {
        RelationsConversionDO relationsConversionDO = BeanUtils.toBean(conversionCreateReqDTO, RelationsConversionDO.class);
        conversionMapper.insert(relationsConversionDO);
        return relationsConversionDO.getId();
    }

    @Override
    public void updateConversion(RelationsConversionSaveReqVO updateReqVO) {
        // 校验存在
        validateConversionExists(updateReqVO.getId());
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(updateReqVO.getFileIdList(), updateReqVO.getConversionId());
        // 转正人信息
        EmployeeRespDTO employee = employeeApi.getEmployeeById(updateReqVO.getEmployeeId());
        updateReqVO.setEmployeeId(employee.getId());
        updateReqVO.setEmployeeName(employee.getName());
        updateReqVO.setEmployeePhone(employee.getPhone());
        updateReqVO.setDeptId(employee.getDeptId());
        updateReqVO.setPostId(employee.getPostId());
        updateReqVO.setPosition(employee.getPosition());
        // 更新
        RelationsConversionDO updateObj = BeanUtils.toBean(updateReqVO, RelationsConversionDO.class);
        conversionMapper.updateById(updateObj);
    }

    @Override
    public void deleteConversion(Long id) {
        // 校验存在
        validateConversionExists(id);
        // 删除
        conversionMapper.deleteById(id);
    }

    private void validateConversionExists(Long id) {
        if (conversionMapper.selectById(id) == null) {
            throw exception(RELATIONS_CONVERSION_NOT_EXISTS);
        }
    }

    @Override
    public RelationsConversionDO getConversion(Long id) {
        return conversionMapper.selectById(id);
    }

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

    @Override
    public PageResult<RelationsConversionDO> getConversionPage(RelationsConversionPageReqVO pageReqVO) {
        return conversionMapper.selectPage(pageReqVO);
    }

}