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

import com.cf.imes.module.system.controller.admin.process.vo.group.ProcessGroupPageReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.group.ProcessGroupSaveReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.group.ProcessListSaveReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.process.ProcessRespVO;
import com.cf.imes.module.system.dal.dataobject.process.ProcessDO;
import com.cf.imes.module.system.dal.mysql.process.ProcessMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import com.cf.imes.module.system.dal.dataobject.process.ProcessGroupDO;
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.ProcessGroupMapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

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

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

/**
 * 工序组表 process_group Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class ProcessGroupServiceImpl implements ProcessGroupService {

    @Resource
    private ProcessGroupMapper processGroupMapper;

    @Resource
    private ProcessMapper processMapper;

    @Override
    public Long createProcessGroup(ProcessGroupSaveReqVO createReqVO) {
        // 插入
        ProcessGroupDO processGroup = BeanUtils.toBean(createReqVO, ProcessGroupDO.class);
        processGroup.setItems(checkProcessGroupExists(createReqVO.getItems()));
        processGroupMapper.insert(processGroup);
        // 返回
        return processGroup.getId();
    }

    @Override
    public void updateProcessGroup(ProcessGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessGroupExists(updateReqVO.getId());
        // 更新
        ProcessGroupDO updateObj = BeanUtils.toBean(updateReqVO, ProcessGroupDO.class);
        updateObj.setItems(checkProcessGroupExists(updateReqVO.getItems()));
        processGroupMapper.updateById(updateObj);
    }

    @Override
    public void deleteProcessGroup(Long id) {
        // 校验存在
        validateProcessGroupExists(id);
        // 删除
        processGroupMapper.deleteById(id);
    }

    private void validateProcessGroupExists(Long id) {
        if (processGroupMapper.selectById(id) == null) {
            throw exception(PROCESS_GROUP_NOT_EXISTS);
        }
    }

    @Override
    public ProcessListSaveReqVO getProcessGroup(Long id) {
        if (processGroupMapper.selectById(id) == null) {
            throw exception(PROCESS_GROUP_NOT_EXISTS);
        } else {
            ProcessGroupDO processGroup = processGroupMapper.selectById(id);
            ProcessListSaveReqVO processListSaveReqVO = BeanUtils.toBean(processGroup, ProcessListSaveReqVO.class);
            String[] items = processGroup.getItems().split(",");
            List<ProcessRespVO> lists = new ArrayList<>();
            for (int i = 0; i < items.length; i++) {
                lists.add(BeanUtils.toBean(processMapper.selectById(items[i]), ProcessRespVO.class));
                System.out.println("each List " + BeanUtils.toBean(processMapper.selectById(items[i]), ProcessRespVO.class));
            }
            System.out.println("processGroupSaveReqVO = " + processListSaveReqVO);
            processListSaveReqVO.setLists(lists);
            return processListSaveReqVO;
        }

    }

    @Override
    public PageResult<ProcessGroupDO> getProcessGroupPage(ProcessGroupPageReqVO pageReqVO) {
        return processGroupMapper.selectPage(pageReqVO);
    }


    private String checkProcessGroupExists(String userLists) {
        // 检查输入是否为空或仅包含空白字符
        if (userLists == null || userLists.trim().isEmpty()) {
            return "[]"; // 统一返回空列表格式化字符串
        }

        List<String> itemsList = Arrays.stream(userLists.split(","))
                .map(String::trim) // 去除每个项两端的空白字符
                .filter(item -> item != null && !item.isEmpty()) // 过滤空字符串和null
                .collect(Collectors.toList());

        // 如果列表为空，直接返回空字符串，表示没有有效的进程ID
        if (itemsList.isEmpty()) {
            return "[]";
        }

        StringBuilder itemsBuilder = new StringBuilder();
        StringBuilder missingItemsBuilder = new StringBuilder(); // 使用StringBuilder累积不存在的项的ID

        itemsList.forEach(itemId -> {
            try {
                Object item = processMapper.selectById(itemId);
                if (item != null) {
                    // 优化字符串拼接
                    itemsBuilder.append(itemId).append(",");
                } else {
                    // 将不存在的项的ID累积到missingItemsBuilder中
                    if (missingItemsBuilder.length() > 0) {
                        missingItemsBuilder.append(",");
                    }
                    missingItemsBuilder.append(itemId);
                }
            } catch (Exception e) {
                // 处理可能的异常，例如数据库查询异常
                // 可以记录日志或者转换为业务异常等
                // 此处为简化仅打印异常，实际应用中应更详细处理
                System.err.println("Error processing item: " + e.getMessage());
            }
        });

        // 判断是否存在不存在的项，并一次性抛出异常
        if (missingItemsBuilder.length() > 0) {
            throw exception(PROCESS_NOT_EXISTS, "Items with IDs " + missingItemsBuilder.toString() + " do not exist.");
        }

        // 移除itemsBuilder最后的逗号
        if (itemsBuilder.length() > 0) {
            itemsBuilder.setLength(itemsBuilder.length() - 1);
        }

        // 返回格式化的列表字符串
        return itemsBuilder.length() > 0 ? itemsBuilder.toString() : "[]";
    }
}