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

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.renew.dto.RelationsRenewCreateReqDTO;
import cn.iocoder.yudao.module.relations.controller.admin.renew.vo.RelationsRenewPageReqVO;
import cn.iocoder.yudao.module.relations.controller.admin.renew.vo.RelationsRenewRespVO;
import cn.iocoder.yudao.module.relations.controller.admin.renew.vo.RelationsRenewSaveReqVO;
import cn.iocoder.yudao.module.relations.dal.dataobject.renew.RelationsRenewDO;
import cn.iocoder.yudao.module.relations.dal.mysql.renew.RelationsRenewMapper;
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_RENEW_NOT_EXISTS;

/**
 * 续签信息 Service 实现类
 *
 * @author zhaopq
 */
@Service
@Validated
public class RelationsRenewServiceImpl implements RelationsRenewService {

    @Resource
    private RelationsRenewMapper renewMapper;
    @Resource
    private FileApi fileApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private EmployeeApi employeeApi;

    @Override
    public Long createRenew(RelationsRenewSaveReqVO 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.setRenewId(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());
        RelationsRenewDO renew = BeanUtils.toBean(createReqVO, RelationsRenewDO.class);
        // 登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(userId);// 判空检查
        if (loginEmployee != null) {
            renew.setCreatorEmployeeId(loginEmployee.getId());
            renew.setCreatorEmployeeName(loginEmployee.getName());
        }
        renewMapper.insert(renew);
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(createReqVO.getFileIdList(), infoId);
        // 返回
        return renew.getId();
    }

    @Override
    public Long createRenewInfoAfterAudit(RelationsRenewCreateReqDTO renewCreateReqDTO) {
        RelationsRenewDO relationsRenewDO = BeanUtils.toBean(renewCreateReqDTO, RelationsRenewDO.class);
        renewMapper.insert(relationsRenewDO);
        return relationsRenewDO.getId();
    }

    @Override
    public void updateRenew(RelationsRenewSaveReqVO updateReqVO) {
        // 校验存在
        validateRenewExists(updateReqVO.getId());
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(updateReqVO.getFileIdList(), updateReqVO.getRenewId());
        // 续签人信息
        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());
        // 更新
        RelationsRenewDO updateObj = BeanUtils.toBean(updateReqVO, RelationsRenewDO.class);
        renewMapper.updateById(updateObj);
    }

    @Override
    public void deleteRenew(Long id) {
        // 校验存在
        validateRenewExists(id);
        // 删除
        renewMapper.deleteById(id);
    }

    private void validateRenewExists(Long id) {
        if (renewMapper.selectById(id) == null) {
            throw exception(RELATIONS_RENEW_NOT_EXISTS);
        }
    }

    @Override
    public RelationsRenewDO getRenew(Long id) {
        return renewMapper.selectById(id);
    }

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

    @Override
    public PageResult<RelationsRenewDO> getRenewPage(RelationsRenewPageReqVO pageReqVO) {
        return renewMapper.selectPage(pageReqVO);
    }

}