package com.foreverwin.mesnac.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreverwin.mesnac.common.service.CommonService;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.mapper.OperationMapper;
import com.foreverwin.mesnac.meapi.model.Operation;
import com.foreverwin.mesnac.meapi.model.WorkCenter;
import com.foreverwin.mesnac.meapi.model.WorkCenterMember;
import com.foreverwin.mesnac.meapi.service.WorkCenterMemberService;
import com.foreverwin.mesnac.meapi.service.WorkCenterService;
import com.foreverwin.modular.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional(rollbackFor = Exception.class)
public class CommonServiceImpl implements CommonService {
    @Autowired
    private WorkCenterMemberService workCenterMemberService;
    @Autowired
    private WorkCenterService workCenterService;
    @Autowired
    private OperationMapper operationMapper;

    @Override
    public String getWorkShopBo(String workCenterBo) {
        if (StrUtil.isBlank(workCenterBo)) {
            return null;
        }
        WorkCenterMember workCenterMember = new WorkCenterMember();
        workCenterMember.setWorkCenterOrResourceGbo(workCenterBo);
        QueryWrapper<WorkCenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(workCenterMember);
        List<WorkCenterMember> workCenterMembers = workCenterMemberService.list(queryWrapper);
        if (workCenterMembers.size() == 0) {
            return null;
        }
        if (workCenterMembers.size() > 1) {
            throw BusinessException.build("资源或工作中心"+ StringUtil.trimHandle(workCenterBo) +"不能属于多个产线");
        }
        workCenterMember = workCenterMembers.get(0);
        if (workCenterMember != null) {
            WorkCenter workCenter = workCenterService.getById(workCenterMember.getWorkCenterBo());
            if ("LEVEL4".equals(workCenter.getWcCategory())) {
                return workCenter.getHandle();
            } else {
                return getWorkShopBo(workCenter.getHandle());
            }
        }
        return null;
    }
    @Override
    public Operation getOperationBySfcBo(String sfcBo) {
        Operation operation = operationMapper.selectOperationBySfcBo(sfcBo, LocaleContextHolder.getLocale().getLanguage());
        return operation;
    }
}
