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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.module.executor.api.orderProcess.OrderProcessApi;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganSimpleRespVO;
import com.cf.imes.module.system.controller.admin.process.vo.group.ProcessGroupPageReqVO;
import com.cf.imes.module.system.controller.admin.process.vo.group.ProcessGroupRespVO;
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.organ.OrganizationDO;
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;

    @Resource
    private OrderProcessApi orderProcessApi;

    @Override
    public Long createProcessGroup(ProcessGroupSaveReqVO createReqVO) {
        // 校验名称存在
        validateProcessGroupNameUnique(createReqVO.getName());
        // 插入
        ProcessGroupDO processGroup = BeanUtils.toBean(createReqVO, ProcessGroupDO.class);
        processGroup.setItems(checkProcessGroupExists(createReqVO.getItems()));
        processGroupMapper.insert(processGroup);
        if (createReqVO.getIsDefault()) {
            processGroupMapper.updateIsDefault(processGroup.getId(), OrganContextHolder.getOrganId());
        }
        // 返回
        return processGroup.getId();
    }

    private void validateProcessGroupNameUnique(String name) {
        if (name != null) {
            if (!name.isEmpty()) {
                if (processGroupMapper.selectCount(new LambdaQueryWrapper<ProcessGroupDO>()
                        .eq(ProcessGroupDO::getName, name)
                        .eq(ProcessGroupDO::getDeleted, false)
                        .eq(ProcessGroupDO::getOrganId, OrganContextHolder.getOrganId())) > 0) {
                    throw exception(PROCESS_GROUP_NAME_EXISTS);
                }
            }
        }
    }

    private void validateProcessGroupNameUnique(String name,Long id) {
        if (name != null) {
            if (!name.isEmpty()) {
                if (processGroupMapper.selectCount(new LambdaQueryWrapper<ProcessGroupDO>()
                        .ne(ProcessGroupDO::getId, id)
                        .eq(ProcessGroupDO::getName, name)
                        .eq(ProcessGroupDO::getDeleted, false)
                        .eq(ProcessGroupDO::getOrganId, OrganContextHolder.getOrganId())) > 0) {
                    throw exception(PROCESS_GROUP_NAME_EXISTS);
                }
            }
        }
    }

    @Override
    public void updateProcessGroup(ProcessGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessGroupExists(updateReqVO.getId());
        // 名称存在
        validateProcessGroupNameUnique(updateReqVO.getName(),updateReqVO.getId());
        // 更新
        ProcessGroupDO updateObj = BeanUtils.toBean(updateReqVO, ProcessGroupDO.class);
        updateObj.setItems(checkProcessGroupExists(updateReqVO.getItems()));
        processGroupMapper.updateById(updateObj);
        if (updateReqVO.getIsDefault()) {
            processGroupMapper.updateIsDefault(updateReqVO.getId(), OrganContextHolder.getOrganId());
        }
    }

    @Override
    public void deleteProcessGroup(Long id) {
        // 校验存在
        validateProcessGroupExists(id);
        // 判断是否在生产中使用这个加工组，如果使用则不能删除
        checkProcessGroupUsed(id);
        // 删除
        processGroupMapper.deleteById(id);
    }

    // 判断是否在生产中使用这个加工组
    private void checkProcessGroupUsed(Long id) {
        if (orderProcessApi.getOrderProcessByProcessGroupId(id) != null){
            throw exception(PROCESS_GROUP_USED);
        }
    }
    private void validateProcessGroupExists(Long id) {
        if (processGroupMapper.selectById(id) == null) {
            throw exception(PROCESS_GROUP_NOT_EXISTS);
        }
    }

    @Override
    public ProcessListSaveReqVO getProcessGroup(Long id) {
        // 校验存在
        validateProcessGroupExists(id);
        ProcessGroupDO processGroup = processGroupMapper.selectById(id);
        ProcessListSaveReqVO processListSaveReqVO = BeanUtils.toBean(processGroup, ProcessListSaveReqVO.class);
        if (processGroup.getItems() == null) {
            return processListSaveReqVO;
        }
        String[] items = processGroup.getItems().split("(?<!^),,(?!$)|,\\s*");

        // 移除由于连续逗号产生的前后空字符串
        List<String> itemsList = Arrays.stream(items)
                .filter(item -> !item.isEmpty())
                .collect(Collectors.toList());

        System.err.println(itemsList.size());
        List<ProcessRespVO> lists = new ArrayList<>();
//        判断items是否为空
        if (itemsList.size() == 0) {
            return processListSaveReqVO;
        }
        for (int i = 0; i < itemsList.size(); i++) {
            if (processMapper.selectById(Long.valueOf(itemsList.get(i))) != null)
                lists.add(BeanUtils.toBean(processMapper.selectById(itemsList.get(i)), ProcessRespVO.class));
        }
        processListSaveReqVO.setLists(lists);
        return processListSaveReqVO;

    }

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

    @Override
    public List<ProcessGroupRespVO> getProcessGroupList(String name) {
        List<ProcessGroupDO> processGroupDOList = processGroupMapper.selectList(new LambdaQueryWrapperX<ProcessGroupDO>()
                .likeIfPresent(ProcessGroupDO::getName, name)
                .eq(ProcessGroupDO::getOrganId, OrganContextHolder.getOrganId())
                .select(ProcessGroupDO::getId, ProcessGroupDO::getName,
                        ProcessGroupDO::getIsDefault, ProcessGroupDO::getSort, ProcessGroupDO::getDescription,
                        ProcessGroupDO::getItems, ProcessGroupDO::getCreateTime, ProcessGroupDO::getUpdateTime));
        return BeanUtils.toBean(processGroupDOList, ProcessGroupRespVO.class);
    }


    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(Long.valueOf(itemId));
                if (item != null) {
                    // 优化字符串拼接
                    itemsBuilder.append(itemId).append(",");
                } else {
                    // 将不存在的项的ID累积到missingItemsBuilder中
                    if (missingItemsBuilder.length() > 0) {
                        missingItemsBuilder.append(",");
                    }
                    missingItemsBuilder.append(itemId);
                }
            } catch (Exception e) {
                throw exception(PROCESS_ID_IS_NULL);
            }
        });

        // 判断是否存在不存在的项，并一次性抛出异常
        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() : "[]";
    }

    //    批量更新工序组默认
    public void updateProcessGroupIsDefault(Long processGroupId, Long organId) {
        processGroupMapper.updateIsDefault(processGroupId, organId);
    }

}