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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.module.system.controller.admin.process.vo.process.*;
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.ProcessGroupMapper;
import com.cf.imes.module.system.enums.ErrorCodeConstants;
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.List;
import java.util.Objects;

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

import static com.cf.imes.module.executor.enums.ErrorCodeConstants.CUSTOM_ORDER_EXISTS;
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 ProcessGroupMapper processGroupMapper;

    @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);
        // 名称相同判断
        validateNameNoExists(process.getName());
        processMapper.insert(process);
        if (createReqVO.getUsers() != "" && createReqVO.getUsers() != null) {
            Long processID = process.getId();
            String[] usersId = createReqVO.getUsers().split(",");
            for (String user : usersId) {
                ProcessAndUserSaveReqVO processAndUserSaveReqVO = new ProcessAndUserSaveReqVO();
                try{
                    if (adminUserService.getUser(Long.parseLong(user)) == null){
                        throw exception(USER_NOT_EXISTS);
                    }

                    processAndUserSaveReqVO.setProcessId(processID);
                    processAndUserSaveReqVO.setUserId(Long.parseLong(user));
                    processUserService.createProcessUser(processAndUserSaveReqVO);
                }catch (Exception e){
                    throw exception(ERR);
                }

            }
        }
        // 返回
        return process.getId();
    }

    private void validateNameNoExists(String name) {
        if (name != null) {
            if (!name.isEmpty()) {
                if (processMapper.selectCount(new LambdaQueryWrapper<ProcessDO>()
                        .eq(ProcessDO::getName, name)
                        .eq(ProcessDO::getDeleted, false)
                        .eq(ProcessDO::getOrganId, OrganContextHolder.getOrganId())) > 0) {
                    throw exception(PROCESS_NAME_EXISTS);
                }
            }
        }
    }

    private void validateNameNoExists(String name,Long id) {
        if (name != null) {
            if (!name.isEmpty()) {
                if (processMapper.selectCount(new LambdaQueryWrapper<ProcessDO>()
                        .ne(ProcessDO::getId, id)
                        .eq(ProcessDO::getName, name)
                        .eq(ProcessDO::getDeleted, false)
                        .eq(ProcessDO::getOrganId, OrganContextHolder.getOrganId())) > 0) {
                    throw exception(PROCESS_NAME_EXISTS);
                }
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcess(ProcessUserSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessExists(updateReqVO.getId());
        if (!updateReqVO.getIsEnabled()) {//调为禁用
            if (isProcessUsed(String.valueOf(updateReqVO.getId()))){
                throw exception(PROCESS_IS_ENABLED);
            }
        }

        // 校验名称存在
        validateNameNoExists(updateReqVO.getName(),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) {

                    throw exception(ERR);
                }
            }
        }
        processMapper.updateById(updateProcess);
    }

//    判断此工序是否已在工序组中使用
    public boolean isProcessUsed(String items) {
//        System.out.println("processGroupMapper.selectListByItems(items) " + processGroupMapper.selectListByItems(items));
//        System.out.println(processGroupMapper.selectListByItems(items).size());
        if (processGroupMapper.selectListByItems(items).size() == 0) // 没有使用
            return false;
        return true;
    }

    @Override
    public void deleteProcess(Long id) {
        // 校验存在
        validateProcessExists(id);
        if (isProcessUsed(String.valueOf(id))){
            throw exception(PROCESS_IS_ENABLED);
        }
        // 删除
        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.setOrganId(OrganContextHolder.getOrganId()).setIsDealer(false));
    }

    @Override
    public PageResult<ProcessRespVO> getProcessPageAll(ProcessPageReqVO pageReqVO) {
        PageDTO<ProcessDO> page = new PageDTO<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<ProcessDO> processRespVOPageResult = processMapper.selectProcessPage(page,BeanUtils.toBean(pageReqVO, ProcessPageReqVO.class).setOrganId(OrganContextHolder.getOrganId()));
        return new PageResult<ProcessRespVO>(BeanUtils.toBean(processRespVOPageResult.getRecords(), ProcessRespVO.class), processRespVOPageResult.getTotal());
    }

    @Override
    public List<ProcessDO> getAllProcess() {
//        获取组织id
        Long organId = OrganContextHolder.getOrganId();
        List<ProcessDO> processDOList = processMapper.selectAll(organId);
        return processDOList;
    }


    @Override
    public List<ProcessDO> getUserProcess(Long userId) {

        // 获取组织id
        Long organId = OrganContextHolder.getOrganId();
        return processMapper.selectProcessList(organId,userId);
    }


}