package com.cf.imes.module.system.service.process;

import com.cf.imes.module.system.controller.admin.process.vo.process.ProcessPageReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.process.ProcessSaveReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.process.ProcessUserRespVO;
import com.cf.imes.module.system.controller.admin.process.vo.process.ProcessUserSaveReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.processUser.ProcessAndUserSaveReqVO;
import com.cf.imes.module.system.dal.dataobject.process.ProcessUserDO;
import com.cf.imes.module.system.dal.mysql.process.ProcessUserMapper;
import com.cf.imes.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import com.cf.imes.module.system.dal.dataobject.process.ProcessDO;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;

import com.cf.imes.module.system.dal.mysql.process.ProcessMapper;

import java.util.Arrays;
import java.util.List;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;

import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;


/**
 * 工序信息表 process Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class ProcessServiceImpl implements ProcessService {

    @Resource
    private ProcessMapper processMapper;

    @Resource
    private ProcessUserService processUserService;

    @Resource
    private AdminUserService adminUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProcess(ProcessUserSaveReqVO createReqVO) {
        // 插入
        ProcessDO process = BeanUtils.toBean(createReqVO, ProcessDO.class);
        processMapper.insert(process);
        if (createReqVO.getUsers() != "") {
            Long processID = process.getId();
            String[] usersId = createReqVO.getUsers().split(",");
            for (String user : usersId) {
                ProcessAndUserSaveReqVO processAndUserSaveReqVO = new ProcessAndUserSaveReqVO();
//                if (adminUserService.getUser(Long.parseLong(user)) != null){
                processAndUserSaveReqVO.setProcessId(processID);
                processAndUserSaveReqVO.setUserId(Long.parseLong(user));
                processUserService.createProcessUser(processAndUserSaveReqVO);
//                }
            }
        }
        // 返回
        return process.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcess(ProcessUserSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessExists(updateReqVO.getId());
        ProcessDO updateProcess = BeanUtils.toBean(updateReqVO, ProcessDO.class);

        processUserService.deleteProcessUserByProcess(updateReqVO.getId());
        // 确保updateReqVO不是null，避免NullPointerException
        if (updateReqVO != null && (updateReqVO.getUsers() != null || updateReqVO.getUsers() != "")) {
            String[] usersId = updateReqVO.getUsers().split(",");
            for (String user : usersId) {
                // 增加了对无法解析的用户ID的异常处理
                try {
                    // 增加了对空字符串和仅包含空白字符的用户ID的验证
                    if (!user.trim().isEmpty()) {
                        ProcessAndUserSaveReqVO processAndUserSaveReqVO = new ProcessAndUserSaveReqVO();
                        processAndUserSaveReqVO.setProcessId(updateProcess.getId());
                        processAndUserSaveReqVO.setUserId(Long.parseLong(user));
                        processUserService.createProcessUser(processAndUserSaveReqVO);
                    }
                } catch (NumberFormatException e) {
                    // 处理NumberFormatException异常，例如记录日志
                    System.err.println("用户ID " + user + " 无法解析为长整型。");
                }
            }
        }
        processMapper.updateById(updateProcess);
    }

    @Override
    public void deleteProcess(Long id) {
        // 校验存在
        validateProcessExists(id);
        // 删除
        processMapper.deleteById(id);

    }

    private void validateProcessExists(Long id) {
        if (processMapper.selectById(id) == null) {
            throw exception(PROCESS_NOT_EXISTS);
        }
    }

    @Override
    public ProcessUserRespVO getProcess(Long id) {
        // 校验存在
        validateProcessExists(id);
        ProcessDO process = processMapper.selectById(id);
        StringBuilder userIdBuilder = new StringBuilder();
        List<ProcessUserDO> userIdListsByProcessId = processUserService.getProcessUser(id);
        if (userIdListsByProcessId != null) {
            for (ProcessUserDO processUser : userIdListsByProcessId) {
                if (processUser != null && processUser.getUserId() != null) {
                    if (adminUserService.getUser(processUser.getUserId()) != null)
                        userIdBuilder.append(",").append(processUser.getUserId());
                }
            }
        }
        String userId = userIdBuilder.length() > 0 ? userIdBuilder.substring(1) : "";
        ProcessUserRespVO processUserRespVO = BeanUtils.toBean(process, ProcessUserRespVO.class);
        processUserRespVO.setUsers(userId);
        return processUserRespVO;

    }

    @Override
    public PageResult<ProcessDO> getProcessPage(ProcessPageReqVO pageReqVO) {
        return processMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ProcessDO> getAllProcess() {
        List<ProcessDO> processDOList = processMapper.selectAll();
        return processDOList;
    }

}