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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.anomaly.dto.AbnormalBillDisposeDto;
import com.foreverwin.mesnac.anomaly.dto.AbnormalBillDto;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalBillDisposeMapper;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalBillMapper;
import com.foreverwin.mesnac.anomaly.mapper.UploadPicturesMapper;
import com.foreverwin.mesnac.anomaly.model.AbnormalBill;
import com.foreverwin.mesnac.anomaly.model.AbnormalBillDispose;
import com.foreverwin.mesnac.anomaly.model.AbnormalNcCode;
import com.foreverwin.mesnac.anomaly.model.UploadPictures;
import com.foreverwin.mesnac.anomaly.service.*;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.dto.ScrapDto;
import com.foreverwin.mesnac.common.dto.SfcDispatchDto;
import com.foreverwin.mesnac.common.dto.UsrDto;
import com.foreverwin.mesnac.common.enums.AnomalyConstant;
import com.foreverwin.mesnac.common.enums.DispatchStatusEnum;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.helper.NextNumberHelper;
import com.foreverwin.mesnac.common.mapper.MessageMapper;
import com.foreverwin.mesnac.common.model.InspectionTask;
import com.foreverwin.mesnac.common.model.Message;
import com.foreverwin.mesnac.common.service.*;
import com.foreverwin.mesnac.common.util.ActiveMQUtil;
import com.foreverwin.mesnac.common.util.DateUtil;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.listener.mapper.UsrMapper;
import com.foreverwin.mesnac.meapi.dto.NcCodeDto;
import com.foreverwin.mesnac.meapi.dto.RouterStepDto;
import com.foreverwin.mesnac.meapi.dto.SfcDto;
import com.foreverwin.mesnac.meapi.dto.ShopOrderDto;
import com.foreverwin.mesnac.meapi.mapper.*;
import com.foreverwin.mesnac.meapi.model.*;
import com.foreverwin.mesnac.meapi.service.*;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.mesnac.production.dto.SplitSfcDto;
import com.foreverwin.mesnac.production.mapper.SplitSfcMapper;
import com.foreverwin.mesnac.production.model.SplitSfc;
import com.foreverwin.mesnac.production.service.SplitSfcService;
import com.foreverwin.mesnac.quality.service.SelfReportService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.meext.MEServices;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import com.sap.me.nonconformance.*;
import com.sap.me.production.SplitSerializeServiceInterface;
import com.sap.me.production.SplitSfcRequest;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 异常单 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-08-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AbnormalBillServiceImpl extends ServiceImpl<AbnormalBillMapper, AbnormalBill> implements AbnormalBillService, AnomalyService {


    @Autowired
    private AbnormalBillMapper abnormalBillMapper;

    @Autowired
    private NextNumberHelper nextNumberHelper;

    @Autowired
    private AbnormalBillDisposeService abnormalBillDisposeService;

    @Autowired
    private ResrceMapper resrceMapper;

    @Autowired
    private NwaUserService nwaUserService;

    @Autowired
    private AbnormalNcCodeService abnormalNcCodeService;

    @Autowired
    private AbnormalCauseService abnormalCauseService;

    @Autowired
    private AbnormalDutyService abnormalDutyService;

    @Autowired
    private AbnormalBillDisposeMapper abnormalBillDisposeMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private RouterService routerService;

    @Autowired
    private RouterMapper routerMapper;

    @Autowired
    private WorkCenterService workCenterService;

    @Autowired
    private DataFieldListService dataFieldListService;

    @Autowired
    private UploadPicturesService uploadPicturesService;

    @Autowired
    private SfcMapper sfcMapper;

    @Autowired
    private NcCodeMapper ncCodeMapper;

    @Autowired
    private OperationMapper operationMapper;

    @Autowired
    private MessageTypeMapper messageTypeMapper;

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private ActiveMQUtil activeMQUtil;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private SelfReportService selfReportService;

    @Autowired
    private AbnormalPlanService abnormalPlanService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private NcCodeService ncCodeService;

    @Autowired
    private DataFieldListMapper dataFieldListMapper;

    @Autowired
    private SfcDispatchCommonService sfcDispatchCommonService;

    @Autowired
    private SplitSfcService splitSfcService;

    @Autowired
    private InspectionTaskService inspectionTaskService;

    @Autowired
    private UsrMapper usrMapper;

    @Autowired
    private SplitSfcMapper splitSfcMapper;

    @Autowired
    private RouterStepService routerStepService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private WorkCenterMapper workCenterMapper;

    @Autowired
    private UploadPicturesMapper uploadPicturesMapper;

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private SfcService sfcService;

    @Autowired
    private ItemService itemService;



    @Override
    public IPage<AbnormalBill> selectPage(FrontPage<AbnormalBill> frontPage, AbnormalBill abnormalBill) {
        QueryWrapper<AbnormalBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(abnormalBill);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<AbnormalBill> selectList(AbnormalBill abnormalBill) {
        QueryWrapper<AbnormalBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(abnormalBill);
        return super.list(queryWrapper);
    }


    @Override
    public String anomalyReportOther(AbnormalBill abnormalBill,
                                     AbnormalBillDispose abnormalBillDispose,
                                     List<String> dutyCauseType,
                                     List<String> dutyType) {
        String message = this.generateAbnormalBill(abnormalBill, abnormalBillDispose, dutyCauseType, dutyType);
        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
        //发送消息
        if(Constants.NEW.equals(abnormalBill.getStatus())){
            this.anomalyCreatedAndSendMessage(abnormalBill,null);
        }
        return message;
    }

    @Override
    public String anomalyReport(AbnormalBill abnormalBill,
                                AbnormalBillDispose abnormalBillDispose,
                                List<String> ncGroupAndNcCodes,
                                List<String> dutyCauseType,
                                List<String> dutyType) {
        String message = this.generateAbnormalBill(abnormalBill, abnormalBillDispose, dutyCauseType, dutyType);
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String site = CommonMethods.getSite();
        if(StringUtils.isBlank(abnormalBill.getSfc())){
            abnormalBill.setStepId(null);
        }else if(StringUtils.isBlank(abnormalBill.getStepId())){
            throw new BaseException("根据SFC找不到StepId");
        }
        if(!StringUtils.isBlank(abnormalBill.getObjectBo())){
            if("J".equals(abnormalBill.getReportFrom())){
                abnormalBill.setObjectBo(HandleEnum.INSPECTION_TASK.getHandle(site,abnormalBill.getObjectBo()));
            }else  if("B".equals(abnormalBill.getReportFrom())){
                abnormalBill.setObjectBo(HandleEnum.SELF_REPORT.getHandle(site,abnormalBill.getObjectBo()));
            }
        }
        //生成不良代码和不良代码组,并把它放到hashMap里面，ncCode是存放在异常单里面的ncCode
        List<String> ncCode = new ArrayList<>();
        List<String> ncGroup = new ArrayList<>();
        StringBuilder ncCodes = new StringBuilder();
        for(String ncGroupAndNcCode:ncGroupAndNcCodes){
            String[] split = ncGroupAndNcCode.split("/");
            ncGroup.add(split[0]);
            ncCode.add(split[1]);
            ncCodes.append(split[1]).append(",");
        }

        ArrayList<AbnormalNcCode> abnormalNcCodes = new ArrayList<>();
        for(int i = 0; i < ncGroup.size(); i ++){
            AbnormalNcCode abnormalNcCode = new AbnormalNcCode();
            //设置异常单BO
            abnormalNcCode.setAbnormalBillBo(abnormalBill.getHandle());
            List<AbnormalNcCode> abnormalNcCodes1 = abnormalNcCodeService.selectList(abnormalNcCode);
            if(abnormalNcCodes1.size() > 0){
                QueryWrapper<AbnormalNcCode> abnormalNcCodeQueryWrapper = new QueryWrapper<>();
                abnormalNcCodeQueryWrapper.setEntity(abnormalNcCode);
                abnormalNcCodeService.remove(abnormalNcCodeQueryWrapper);
            }
            abnormalNcCode.setModifiedUser(CommonMethods.getUser());
            abnormalNcCode.setModifiedDateTime(now);
            abnormalNcCode.setCreatedUser(CommonMethods.getUser());
            abnormalNcCode.setCreatedDateTime(now);
            //设置HANDLE
            abnormalNcCode.setHandle(UUID.randomUUID().toString());
            //设置站点
            abnormalNcCode.setSite(CommonMethods.getSite());
            //设置不合格代码组
            abnormalNcCode.setNcCodeGroup(ncGroup.get(i));
            abnormalNcCode.setNcCode(ncCode.get(i));
            abnormalNcCodes.add(abnormalNcCode);
        }
        if(abnormalNcCodes.size() > 0){
            abnormalNcCodeService.saveOrUpdateBatch(abnormalNcCodes);
            abnormalBill.setNcCode(ncCodes.substring(0,ncCodes.length() - 1));
        }


        //判断是否是用户自报,如果是自报的话，调用孙豪的方法
        if(!StringUtil.isBlank(abnormalBill.getInspector()) && Constants.NEW.equals(abnormalBill.getStatus()) &&"B".equals(abnormalBill.getReportFrom())){
            //abnormalBill.setObjectBo(HandleEnum.SELF_REPORT.getHandle(abnormalBill.getSite(),abnormalBill.getObjectBo()));
            selfReportService.updateState(abnormalBill.getObjectBo(), Constants.STATE_CONFIRM);
        }


        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);

        //发送消息
        if(Constants.NEW.equals(abnormalBill.getStatus())){
            this.anomalyCreatedAndSendMessage(abnormalBill,null);
        }

        return message;
    }


    @Override
    public String anomalyReportDevice(AbnormalBill abnormalBill,AbnormalBillDispose abnormalBillDispose) {
        String message = this.generateAbnormalBill(abnormalBill, abnormalBillDispose, null, null);
        LocalDateTime now = LocalDateTime.now();
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //异常代码

        //通过设备找到异常车间
        try{
            Resrce resrce = new Resrce();
            resrce.setSite(site);
            resrce.setResrce(abnormalBill.getResrce());
            WorkCenter workCenterByResrce = workCenterMapper.findWorkCenterByResrce(resrce);
            abnormalBill.setWorkCenter(workCenterByResrce.getWorkCenter());
        }catch (Exception e){
            throw new BaseException("根据资源（设备）查找异常车间报错，请查看工作中心维护。报错信息:"+e.getMessage());
        }


        List<NcCodeDto> ncCodesAndNcGroups = ncCodeService.findNcCodeDescriptionByNcCode(abnormalBill.getNcCode());
        List<AbnormalNcCode> abnormalNcCodes = new LinkedList<>();
        for(int i = 0; i < ncCodesAndNcGroups.size(); i ++){
            AbnormalNcCode abnormalNcCode = new AbnormalNcCode();
            String uuid = UUID.randomUUID().toString();
            abnormalNcCode.setHandle(uuid);
            abnormalNcCode.setSite(abnormalBill.getSite());
            abnormalNcCode.setAbnormalBillBo(abnormalBill.getHandle());
            abnormalNcCode.setNcCodeGroup(ncCodesAndNcGroups.get(i).getNgGroup());
            abnormalNcCode.setNcCode(ncCodesAndNcGroups.get(i).getNcCode());
            abnormalNcCode.setNcQty(abnormalBill.getNcQty());
            abnormalNcCode.setCreatedUser(user);
            abnormalNcCode.setCreatedDateTime(now);
            abnormalNcCode.setModifiedUser(user);
            abnormalNcCode.setModifiedDateTime(now);
            abnormalNcCodes.add(abnormalNcCode);
        }
        if(abnormalNcCodes.size() > 0){
            abnormalNcCodeService.saveOrUpdateBatch(abnormalNcCodes);
        }
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
        this.saveOrUpdate(abnormalBill);
        /**
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         * XXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXXXX
         */

        //发送消息
        if(Constants.NEW.equals(abnormalBill.getStatus())){
            this.anomalyCreatedAndSendMessage(abnormalBill,null);
        }
        return message;
    }

    @Override
    public HashMap<String, Object> init(String type) {
        HashMap<String, Object> hashMap = new HashMap<>();
        String site = CommonMethods.getSite();

        //工作中心
        WorkCenter workCenter = new WorkCenter();
        workCenter.setWcCategory("LEVEL4");
        workCenter.setSite(site);
        List<WorkCenter> workCenterList = workCenterService.selectList(workCenter);
        hashMap.put("workCenter",workCenterList);

        /**
         * 发现环节
         */
        DataField discover = new DataField();
        discover.setSite(site);
        discover.setDataField("DISCOVER");
        List<DataField> discoverList = dataFieldListService.findDataFieldListById(discover);
        hashMap.put("discover",discoverList);

        //原因分类
        DataField ncCode = new DataField();
        ncCode.setSite(site);
        ncCode.setDataField("REASON_CATEGORY");
        List<DataField> ncCodeList = dataFieldListService.findDataFieldListById(ncCode);
        hashMap.put("causeType",ncCodeList);


        //责任部门
        DataField dataField = new DataField();
        dataField.setSite(site);
        dataField.setDataField("RESPONSIBILITY_DEPARTMENT");
        List<DataField> dutyDepartList = dataFieldListService.findDataFieldListById(dataField);
        hashMap.put("dutyDepart",dutyDepartList);


        //责任分类
        dataField.setDataField("RESPONSIBILITY_TYPE");
        List<DataField> dutyTypeList = dataFieldListService.findDataFieldListById(dataField);
        hashMap.put("dutyType",dutyTypeList);

        //产品类别
        dataField.setDataField("PRODUCT_CATEGORY");
        List<DataField> productCategory = dataFieldListService.findDataFieldListById(dataField);
        hashMap.put("productCategory",productCategory);


        //当前登录用户的fullName
        List<UsrDto> list = userService.findList(CommonMethods.getUser());
        if(list != null && list.size() > 0){
            hashMap.put("currentUser",list.get(0).getFullName());

        }
        //初始化异常单号
        if(!StringUtil.isBlank(type)){
            hashMap.put("abnormalNo",this.getNextNumber(type));
        }

        return hashMap;
    }

    @Override
    public List<AbnormalBillDto> backLog(AbnormalBillDto abnormalBillDto) {
        String user = CommonMethods.getUser();
        String site = CommonMethods.getSite();
        List<UserGroup> userGroupList = userGroupMapper.findUserGroupListByUser(site, user);
        //判断该用户组中有没有administrator,如果有的话就等于null
//        for (UserGroup userGroup : userGroupList){
//            if("ADMINISTRATORS".equals(userGroup.getUserGroup())){
//                userGroupList = null;
//                break;
//            }
//        }
        String language = LocaleContextHolder.getLocale().getLanguage();
        return abnormalBillMapper.backLog(abnormalBillDto, language,userGroupList);
    }

    @Override
    public AbnormalBillDisposeDto findAllByAbnormalNo(AbnormalBill abnormalBill) {
        String site = CommonMethods.getSite();
        String local=LocaleContextHolder.getLocale().getLanguage();
        abnormalBill.setSite(site);
        if(StringUtil.isEmpty(abnormalBill.getAbnormalNo())){
            return null;
        }
        return abnormalBillDisposeMapper.findAllByAbnormalNo(abnormalBill,local);
    }

    @Override
    public AbnormalBillDto findAllByAbnormalNoDevice(AbnormalBill abnormalBill) {
        String site = CommonMethods.getSite();
        String local=LocaleContextHolder.getLocale().getLanguage();
        abnormalBill.setSite(site);
        if(StringUtil.isEmpty(abnormalBill.getAbnormalNo())){
            return null;
        }
        DataField dataField = new DataField();
        dataField.setSite(site);
        dataField.setDataField("RERR_CANCEL_REASON");
        List<DataFieldList> dataFieldList = dataFieldListMapper.findDataFieldList(dataField);
        AbnormalBillDto abnormalBillDto = abnormalBillMapper.findAllByAbnormalNoDevice(abnormalBill, local);
        abnormalBillDto.setCancelCodeList(dataFieldList);
        return abnormalBillDto;
    }

    @Override
    public void resProcessing(AbnormalBill abnormalBill) {
        String site = CommonMethods.getSite();
        String commonUser = CommonMethods.getUser();
        String user = "";
        if(StringUtil.isBlank(abnormalBill.getResponseUser())){
            user = CommonMethods.getUser();
        }else {
            user = abnormalBill.getResponseUser() + "," + CommonMethods.getUser();
        }
        LocalDateTime now = LocalDateTime.now();
        abnormalBill.setSite(site);
        abnormalBill.setResponseUser(user);
        abnormalBill.setResponseDateTime(now);
        abnormalBill.setStatus(Constants.RESPONSE);
        this.saveOrUpdate(abnormalBill);
        //发送消息.设备异常响应暂时不会发送消息。但是会关闭消息
        if(StringUtils.notBlank(abnormalBill.getType()) && Constants.ABNORMAL_RESRCE.equals(abnormalBill.getType())){
            Message message = new Message();
            message.setSite(site);
            message.setObjectBo(abnormalBill.getHandle());
            List<Message> messages = messageService.selectList(message);
            for (int i = 0; i < messages.size(); i++) {
                messages.get(i).setStatus("Y");
                messages.get(i).setModifiedDateTime(now);
                messages.get(i).setModifiedUser(commonUser);
            }
            if(messages.size() > 0){
                messageService.saveOrUpdateBatch(messages);
            }
            return ;
        }
        this.anomalyCreatedAndSendMessage(abnormalBillMapper.selectById(abnormalBill.getHandle()),null);
    }

    @Override
    public void programConfirm(AbnormalBill abnormalBill,AbnormalBillDispose abnormalBillDispose) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));

        if(!StringUtil.isBlank(abnormalBillDispose.getRouterBo())){
            //分割该工艺路线
            String[] routerSplit = abnormalBillDispose.getRouterBo().split(",");
            //判断该返修工艺是否正确
            Router router = new Router();
            router.setSite(site);
            router.setRouter(routerSplit[1]);
            router.setRouterType(routerSplit[2]);
            router.setCurrentRevision("true");
            List<Router> routers = routerService.selectList(router);
            if(routers == null || routers.size() == 0){
                throw BusinessException.build("该返修工艺不存在");
            }
        }

        //判断返修工单是否正确
        if(!StringUtil.isBlank(abnormalBillDispose.getResolveShopOrder())){
            ShopOrder shopOrder = shopOrderMapper.selectById(HandleEnum.SHOP_ORDER.getHandle(site, abnormalBillDispose.getResolveShopOrder()));
            if(shopOrder == null){
                throw BusinessException.build("该返修工单不存在");
            }
        }


        //发送用户
        nwaUserService.checkUserGroup(site,abnormalBillDispose.getResolveSendUserGroup());


        //设置解决方案的处理时间和处理人
        abnormalBillDispose.setResolveDateTime(now);
        abnormalBillDispose.setResolveUser(user);
        abnormalBill.setStatus(Constants.PROGRAM_CONFIRM);
        abnormalBill.setProgram("true");

        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
        this.saveOrUpdate(abnormalBill);

        //保存到异常计划表
        AbnormalBill abnormalBill2 = abnormalBillMapper.selectById(abnormalBill.getHandle());
        if(Constants.ABNORMAL_QUALITY.equals(abnormalBill2.getType())){
            AbnormalBillDispose abnormalBillDispose1 = abnormalBillDisposeMapper.selectById(abnormalBillDispose.getHandle());
            abnormalPlanService.saveAbnormalPlan(abnormalBill2,abnormalBillDispose1,now);
        }
        //判断该异常解决方案是否是让步放行、配作、线下换料、试装,并且关联来源不是空，如果是,就调用孙豪的方法,并且sfc不能为空
        if((Constants.CONCESSION.equals(abnormalBillDispose.getAbnormalMethod()) ||
                Constants.MATCH.equals(abnormalBillDispose.getAbnormalMethod()) ||
                Constants.OFFLINE_REFUELING.equals(abnormalBillDispose.getAbnormalMethod()) ||
                Constants.TEST_EQUIPMENT.equals(abnormalBillDispose.getAbnormalMethod()))
                && !StringUtil.isBlank(abnormalBill2.getObjectBo())
                && StringUtil.notBlank(abnormalBill2.getSfc())){

            try{
                this.creatInspectionTask(site,abnormalBill2.getObjectBo(),abnormalBill2.getSfc(),abnormalBill2.getStepId(),AnomalyConstant.AnomalyMethod.msg(abnormalBillDispose.getAbnormalMethod()));
            }catch (Exception e){
                throw new BaseException("createInspectionTask方法报错,"+e.getMessage());
            }

        }else if(Constants.REPAIR.equals(abnormalBillDispose.getAbnormalMethod()) &&
                StringUtil.isBlank(abnormalBillDispose.getResolveShopOrder()) &&
                StringUtil.notBlank(abnormalBill2.getSfc())){
            Sfc sfc = sfcMapper.selectById(HandleEnum.SFC.getHandle(site, abnormalBill2.getSfc()));
            if(sfc.getQty() > Double.parseDouble(abnormalBill2.getNcQty())){
                //跳过啥都不做
            }else if(sfc.getQty() == Double.parseDouble(abnormalBill2.getNcQty())){
                //整批返修、批量返修
                SfcDto sfcDto = new SfcDto();
                sfcDto.setSfc(sfc.getSfc());
                sfcDto.setAbnormalNo(abnormalBill2.getAbnormalNo());
                sfcDto.setQty(sfc.getQty());
                Map map = sfcMapper.findOperationBySfc(site, sfc.getSfc());
                if(map == null || StringUtils.isBlank((String)map.get("STEP_ID"))){
                    if(StringUtils.notBlank(abnormalBill2.getStepId())){
                        sfcDto.setStepId(abnormalBill2.getStepId());
                    }else{
                        throw new BaseException("整批返修失败，根据产品条码"+sfc.getSfc()+"找不到STEP_ID(工步)");
                    }
                }else{
                    sfcDto.setStepId((String) map.get("STEP_ID"));
                }
                this.batchRepair(sfcDto);
            }
        }
        this.anomalyCreatedAndSendMessage(abnormalBill2,abnormalBillDispose);
    }

    @Override
    public void dutyConfirm(AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose,
                            List<String> dutyCauseType,
                            List<String> dutyType) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));

        //判断判责提交是否已经填写
        //AbnormalBillDispose abnormalBillDispose1 = abnormalBillDisposeMapper.selectById(abnormalBillDispose.getHandle());
        AbnormalBill abnormalBill1 = abnormalBillMapper.selectById(abnormalBill.getHandle());
        if("true".equals(abnormalBill1.getCorrection())){
            throw BusinessException.build("该异常单已经判责提交");
        }
        abnormalBill.setStatus(Constants.CORRECTION_CONFIRM);
        abnormalBill.setCorrection("true");
        abnormalBillDispose.setDutyDateTime(now);
        abnormalBillDispose.setDutyUser(user);



        nwaUserService.checkUserGroup(site,abnormalBillDispose.getDutySendUserGroup());
        //插入原因分类和责任分类
        abnormalCauseService.insertByAbnormalBill(abnormalBill,abnormalBillDispose,dutyCauseType);
        abnormalDutyService.insertByAbnormalBill(abnormalBill,abnormalBillDispose,dutyType);

        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
        this.anomalyCreatedAndSendMessage(abnormalBillMapper.selectById(abnormalBill.getHandle()),abnormalBillDispose);


    }

    @Override
    public void anomalyShutDown(AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        String local = LocaleContextHolder.getLocale().getLanguage();
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));

        if(!StringUtil.isBlank(abnormalBill.getStatus())){
            abnormalBill.setStatus(abnormalBill.getStatus());
        }else{
            abnormalBill.setStatus(Constants.SHUT_DOWN);
        }
        abnormalBillDispose.setClosedUser(user);
        abnormalBillDispose.setClosedDateTime(now);

        //上传照片
        if(!StringUtil.isBlank(abnormalBill.getFileName())){
            //放置图片,新建状态
            this.fileUpload(abnormalBill);
        }else{
            String status = "N".equals(abnormalBill.getStatus()) ? "N" : "G";
            uploadPicturesMapper.deleteById("UploadPicturesBO:"+abnormalBill.getSite()+","+abnormalBill.getAbnormalNo()+","+status);
            //UploadPicturesBO:"+abnormalBill.getSite()+","+abnormalBill.getAbnormalNo()+","+status
        }
        // this.anomalyCreatedAndSendMessage(abnormalBill,abnormalBillDispose);
        //保存到异常计划表
        if(Constants.ABNORMAL_QUALITY.equals(abnormalBill.getType())){
            AbnormalBillDisposeDto abnormalBillDisposeDto = abnormalBillDisposeMapper.findAllByAbnormalNo(abnormalBill, local);
            abnormalPlanService.saveAbnormalPlan(abnormalBillDisposeDto,now);
        }
        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
    }


    @Override
    public String generateAbnormalBill(AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose,List<String> dutyCauseType,List<String> dutyType) {
        String site = CommonMethods.getSite();
        LocalDateTime currentTime = LocalDateTime.now();
        String user = CommonMethods.getUser();

        //return 返回的消息
        String message = "提报成功";

        //设置消息类型
        if(Constants.ABNORMAL_QUALITY.equals(abnormalBill.getType())){
            abnormalBill.setMessageType(Constants.ABNORMAL_MESSAGE_QUALITY);
        }else if(Constants.ABNORMAL_RESRCE.equals(abnormalBill.getType())){
            abnormalBill.setMessageType(Constants.ABNORMAL_MESSAGE_RESOURCE);
        }else if(Constants.ABNORMAL_OTHER.equals(abnormalBill.getType())){
            abnormalBill.setMessageType(Constants.ABNORMAL_MESSAGE_OTHER);
        }

        //如果前台传过来的异常单为空的话，则抛出一个异常
        if(StringUtil.isBlank(abnormalBill.getAbnormalNo())) {
            throw BusinessException.build("异常单号不存在");
        }

        //设置异常单的handle
        abnormalBill.setHandle(HandleEnum.ABNORMAL_BILL.getHandle(site,abnormalBill.getAbnormalNo()));
        //判断该异常单是否已经提交
        if(abnormalBillMapper.selectById(abnormalBill.getHandle()) != null &&
                !Constants.SHUT_DOWN.equals(abnormalBill.getStatus())){
            throw BusinessException.build("该异常单已经提交，请清空后提交");
        }


        //设置异常单详细表的handle和abnormalBillBo
        abnormalBillDispose.setAbnormalBillBo(abnormalBill.getHandle());
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));


        //设置责任划分填报人和填报时间
        abnormalBillDispose.setDutyUser(user);
        abnormalBillDispose.setDutyDateTime(currentTime);


        //插入原因分类和责任分类
        abnormalCauseService.insertByAbnormalBill(abnormalBill,abnormalBillDispose,dutyCauseType);
        abnormalDutyService.insertByAbnormalBill(abnormalBill,abnormalBillDispose,dutyType);


        //判断工序编号是否传递错误
        if(!StringUtil.isBlank(abnormalBill.getOperation())){
            QueryWrapper<Operation> operationQueryWrapper = new QueryWrapper<Operation>();
            operationQueryWrapper.eq("OPERATION",abnormalBill.getOperation())
                    .eq("SITE",site);
            List<Operation> operations = operationMapper.selectList(operationQueryWrapper);
            if(operations == null || operations.size() == 0){
                throw BusinessException.build("工序编号传递错误");
            }
        }

        //判断设备异常提报传递的不良代码是否有误
        if(!StringUtil.isBlank(abnormalBill.getNcCode()) && Constants.ABNORMAL_RESRCE.equals(abnormalBill.getType())){
            List<String> ncCodes = Arrays.asList(abnormalBill.getNcCode().split(","));
            Integer length = ncCodeMapper.checkNcCode(ncCodes,site);
            if(ncCodes.size() != length){
                throw BusinessException.build("不良代码传递有误");
            }
        }

        /**
         * 判断SFC ，设备异常提交，sfc可以为空，质量异常提报sfc和物料编号其中一个不能为空
         * 设备编号
         * 是否为空
         */
        if(StringUtil.isBlank(abnormalBill.getSfc()) && !Constants.ABNORMAL_RESRCE.equals(abnormalBill.getType())) {
            if(Constants.ABNORMAL_QUALITY.equals(abnormalBill.getType())){
                if(StringUtil.isBlank(abnormalBill.getItemBo())){
                    throw BusinessException.build("物料编号不能为空");
                }
            }else{
                throw BusinessException.build("产品条码不能为空");
            }
        }


        //异常提报的时候，提报用户组不可以为空
        if(StringUtil.isBlank(abnormalBill.getReportSendUserGroup()) ) {
            throw BusinessException.build("提报用户组不能为空");
        }


        //判断设备异常提交的设备是否正确
        if(!StringUtil.isBlank(abnormalBill.getResrce()) && Constants.ABNORMAL_RESRCE.equals(abnormalBill.getType())){
            Resrce resrce = resrceMapper.selectById(HandleEnum.RESOURCE.getHandle(site, abnormalBill.getResrce()));
            if(resrce == null){
                throw BusinessException.build("该设备编号不存在");
            }
        }


        //判断不良品数量和问题数量是否为正整数
        try {
            if(!StringUtil.isBlank(abnormalBill.getNcQty()) && Integer.parseInt(abnormalBill.getNcQty()) < 0) {
                throw BusinessException.build("不良品数量必须大于0");
            }
            if(!StringUtil.isBlank(abnormalBill.getPbQty()) && Integer.parseInt(abnormalBill.getPbQty()) < 0){
                throw BusinessException.build("问题数量必须大于0");
            }
        }catch (NumberFormatException num){
            throw BusinessException.build("问题数量或不良品数量必须为一个正整数");
        }


        //判断输入的责任划分用户组是否正确，并返回对应的用户组下的用户
//        nwaUserService.checkUserGroup(site,abnormalBillDispose.getDutySendUserGroup());

        //只有质量异常和其他异常会上传图片
        if(!StringUtil.isBlank(abnormalBill.getFileName())){
            //放置图片,新建状态
            this.fileUpload(abnormalBill);
        }


        //判断该sfc是否已经提交过一个异常，如果已经提交，且状态不是方案确认、取消、闭环关闭则报错
        List<String> status = new ArrayList<>();
        status.add(Constants.PROGRAM_CONFIRM);
        status.add(Constants.CANCEL);
        status.add(Constants.SHUT_DOWN);
        if(!StringUtil.isBlank(abnormalBill.getSfc())) {
            List<AbnormalBill> abnormalBillList = abnormalBillMapper.findCountBySfc(abnormalBill.getSite(), abnormalBill.getType(), abnormalBill.getSfc(), status);
            String abnormalType = abnormalBill.getType().equals(Constants.ABNORMAL_QUALITY) ? "质量异常" :
                    abnormalBill.getType().equals(Constants.ABNORMAL_OTHER) ? "其他异常" : "设备异常";
            if (abnormalBillList.size() >= 1) {
                throw BusinessException.build(abnormalType + "有未处理完成的产品条码（SFC）");
            }
            //判断不良品数量是否大于SFC的数量
            Sfc sfc = sfcMapper.selectById(HandleEnum.SFC.getHandle(site, abnormalBill.getSfc()));
            if(Strings.isNotBlank(abnormalBill.getNcQty()) && Integer.parseInt(abnormalBill.getNcQty()) > sfc.getQty()){
                throw BusinessException.build("质量异常提报的不良品数量不能大于SFC的数量，SFC的数量为:"+sfc.getQty());
            }

        }


        //设置创建时间和更新时间
        if(abnormalBillMapper.selectById(abnormalBill.getHandle()) == null){
            abnormalBill.setCreatedDateTime(currentTime);
            abnormalBill.setCreatedUser(user);
            abnormalBillDispose.setCreatedDataTime(currentTime);
            abnormalBillDispose.setCreatedUser(user);
        }
        abnormalBill.setModifiedDateTime(currentTime);
        abnormalBill.setModifiedUser(user);
        abnormalBillDispose.setModifiedDateTime(currentTime);
        abnormalBillDispose.setModifiedUser(user);


//        this.anomalyCreatedAndSendMessage(abnormalBill,null);
        return message;

    }

    @Override
    public boolean cancelBrowse(String handle, String cancelBrowse,String code,String cancelSendUserGroup) {
        LocalDateTime now = LocalDateTime.now();
        AbnormalBill abnormalBill = abnormalBillMapper.selectById(handle);
        if(abnormalBill == null){
            return  false;
        }
        abnormalBill.setStatus(Constants.CANCEL);
        abnormalBill.setCancelReason(cancelBrowse);
        abnormalBill.setCancelSendUserGroup(cancelSendUserGroup);
        if(!StringUtil.isBlank(code)){
            abnormalBill.setCancelCode(code);
        }
        abnormalBill.setCancelUser(CommonMethods.getUser());
        abnormalBill.setCancelDateTime(now);
        this.saveOrUpdate(abnormalBill);
        this.anomalyCreatedAndSendMessage(abnormalBill,null);
        return  true;
    }

    @Override
    public void fileUpload(AbnormalBill abnormalBill){
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        String site = CommonMethods.getSite();
        String status = "N".equals(abnormalBill.getStatus()) ? "N" : "G";
        List<String> name = Arrays.asList(abnormalBill.getFileName().split(","));
        if(name.size() != 0){
            UploadPictures uploadPictures = new UploadPictures();
            uploadPictures.setHandle("UploadPicturesBO:"+site+","+abnormalBill.getAbnormalNo()+","+status);
            uploadPictures.setSite(site);
            uploadPictures.setPicturePath(abnormalBill.getFilePath());
            StringBuilder pictureAddress = new StringBuilder();
            for (int i = 0; i <= name.size() -1; i++) {
                if(i != name.size() -1){
                    pictureAddress.append(abnormalBill.getFilePath()).append("/").append(name.get(i)).append(",");
                }else{
                    pictureAddress.append(abnormalBill.getFilePath()).append("/").append(name.get(i));
                }
            }
            uploadPictures.setStatus(status);
            uploadPictures.setPictureAddress(pictureAddress.toString());
            uploadPictures.setObjectBo(abnormalBill.getHandle());
            uploadPictures.setNum(abnormalBill.getFileNum());
            uploadPictures.setType("ABNORMAL");
            uploadPictures.setCreatedUser(user);
            uploadPictures.setCreatedDateTime(now);
            uploadPictures.setModifiedUser(user);
            uploadPictures.setModifiedDateTime(now);
            uploadPicturesService.saveOrUpdate(uploadPictures);
        }
    }

    @Override
    public UploadPictures findUploadPictureByAbnormalBo(AbnormalBill abnormalBill) {
        String site = CommonMethods.getSite();
        UploadPictures uploadPictures = new UploadPictures();
        uploadPictures.setSite(site);
        uploadPictures.setObjectBo(abnormalBill.getHandle());
        uploadPictures.setStatus(abnormalBill.getStatus());
        List<UploadPictures> uploadPictures1 = uploadPicturesService.selectList(uploadPictures);
        if(uploadPictures1 != null && uploadPictures1.size() == 1){
            return  uploadPictures1.get(0);
        }
        return null;
    }

    @Override
    public String getNextNumber(String type){
        String site = CommonMethods.getSite();
        String abnormalNo = "";
        //生成异常单号
        if("Q".equals(type)){//其他异常
            abnormalNo = nextNumberHelper.getNextNumber(site, "ABNORMAL_OTHER", 1, null).get(0);
        }else if("Z".equals(type)){//质量异常
            abnormalNo = nextNumberHelper.getNextNumber(site, "ABNORMAL_QUALITY", 1, null).get(0);
        }else if("S".equals(type)){//设备异常
            abnormalNo = nextNumberHelper.getNextNumber(site, "ABNORMAL_DEVICE", 1, null).get(0);
        }
        return abnormalNo;
    }

    @Override
    public HashMap<String,Object> anomalyReveseRepair(AbnormalBill abnormalBill,AbnormalBillDispose abnormalBillDispose) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        if(!Constants.RESPONSE.equals(abnormalBill.getStatus())){
            throw BusinessException.build("该异常单的状态必须是响应中才能转维修");
        }

        if(StringUtil.isBlank(abnormalBillDispose.getAbnormalMethod())){
            throw BusinessException.build("转维修时方案分类必须填写");
        }
        abnormalBill.setHandle(HandleEnum.ABNORMAL_BILL.getHandle(site,abnormalBill.getAbnormalNo()));
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));
        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("abnormalBill",abnormalBillMapper.selectById(abnormalBill.getHandle()));
        hashMap.put("abnormalBillDispose",abnormalBillDisposeMapper.selectById(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo())));
        return hashMap;
    }

    @Override
    public void anomalyReveseRepairShutDown(String abnormalNo){
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        AbnormalBill abnormalBill = getById(HandleEnum.ABNORMAL_BILL.getHandle(site, abnormalNo));
        if(abnormalBill == null){
            return ;
        }
        if(!Constants.RESPONSE.equals(abnormalBill.getStatus())){
            throw new BaseException("状态不在响应中，请重新检索");
        }
        abnormalBill.setHandle(HandleEnum.ABNORMAL_BILL.getHandle(site,abnormalBill.getAbnormalNo()));
        abnormalBill.setStatus(Constants.SHUT_DOWN);
        AbnormalBillDispose abnormalBillDispose = abnormalBillDisposeMapper.selectById(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site, abnormalBill.getAbnormalNo()));
        abnormalBillDispose.setResolveUser(user);
        abnormalBillDispose.setResolveDateTime(now);
        abnormalBillDispose.setClosedUser(user);
        abnormalBillDispose.setClosedDateTime(now);
        abnormalBillDispose.setHandle(HandleEnum.ABNORMAL_BILL_DISPOSE.getHandle(site,abnormalBill.getAbnormalNo()));
        this.saveOrUpdate(abnormalBill);
        abnormalBillDisposeService.saveOrUpdate(abnormalBillDispose);
    }

    @Override
    public void createAnomalyTask(String category, String resource, String shopOrder,
                                  String sfc, String ncCodes,String position,String ncQty,
                                  String ncDescription,String userGroup) {
        String site = CommonMethods.getSite();
        LocalDateTime now = LocalDateTime.now();
        String user = CommonMethods.getUser();
        String abnormalNo = null;

        AbnormalBill abnormalBill = new AbnormalBill();
        if(Constants.ABNORMAL_RESRCE.equals(category)){
            abnormalNo = this.getNextNumber(category);
            abnormalBill.setNcCode(ncCodes);
            abnormalBill.setRepairDateTime(now);
            abnormalBill.setType(category);
        }else if(Constants.ABNORMAL_OTHER.equals(category)){
            abnormalNo = this.getNextNumber(category);
            abnormalBill.setType(category);
        }

        abnormalBill.setSite(site);
        abnormalBill.setAbnormalNo(abnormalNo);
        abnormalBill.setHandle(HandleEnum.ABNORMAL_BILL.getHandle(site,abnormalNo));
        abnormalBill.setStatus(Constants.NEW);
        abnormalBill.setSfc(sfc);
        abnormalBill.setShopOrder(shopOrder);
        //如果工单不为空，根据工单找出工作令、项目号,itemBo
        if(StringUtils.notBlank(shopOrder)){
            ShopOrderDto shopOrderDto = shopOrderService.findByShopOrderBo(shopOrder);
            if(shopOrderDto != null){
                abnormalBill.setWorkOrder(shopOrderDto.getWorkOrder());
                abnormalBill.setItemNumber(shopOrderDto.getItemNumber());
                abnormalBill.setProductCategory(shopOrderDto.getProductCategory());
            }

            ShopOrder shopOrder1 = shopOrderMapper.selectById(HandleEnum.SHOP_ORDER.getHandle(site, shopOrder));
            String itemBo = shopOrder1.getItemBo();
            if(StringUtils.notBlank(itemBo)){
                abnormalBill.setItemBo(itemBo);
            }

        }
        //如果sfc不为空，找出操作和子步骤
        if(StringUtils.notBlank(sfc)){
            Map operationAndStepId = sfcService.findOperationBySfc(sfc);
            if(operationAndStepId != null){
                String temporaryOperation = (String)operationAndStepId.get("OPERATION_BO");
                if(StringUtils.notBlank(temporaryOperation)){
                    String operation = HandleEnum.OPERATION.getPart(temporaryOperation,1);
                    abnormalBill.setOperation(operation);
                }
                abnormalBill.setStepId((String) operationAndStepId.get("STEP_ID"));
            }
        }
        abnormalBill.setPbUser(user);
        abnormalBill.setResrce(resource);
        //根据资源找出工作中心
        if(StringUtils.notBlank(resource)){
            Resrce resrce = new Resrce();
            resrce.setSite(site);
            resrce.setResrce(resource);
            WorkCenter workCenter = workCenterMapper.findWorkCenterByResrce(resrce);
            abnormalBill.setWorkCenter(workCenter.getWorkCenter());
        }

        abnormalBill.setEntityLocation(position);
        abnormalBill.setNcQty(ncQty);
        abnormalBill.setPbDescription(ncDescription);
        abnormalBill.setDiscover(Constants.SELF_MADE);
        abnormalBill.setReportFrom(Constants.REPORT);
        abnormalBill.setReportSendUserGroup(userGroup);
        AbnormalBillDispose abnormalBillDispose = new AbnormalBillDispose();

        abnormalBillDispose.setSite(site);
        abnormalBillDispose.setAbnormalBillBo(abnormalBill.getHandle());


        //判断工单，sfc，资源是否传递正确
        Sfc sfc1 = sfcMapper.selectById(HandleEnum.SFC.getHandle(site, sfc));
        if(sfc1 == null){
            throw new BaseException("sfc传递有误");
        }else {
            if(!HandleEnum.SHOP_ORDER.getHandle(site,shopOrder).equals(sfc1.getShopOrderBo())){
                throw new BaseException("工单传递有误");
            }

        }
        if(Constants.ABNORMAL_RESRCE.equals(category)){
            this.anomalyReportDevice(abnormalBill,abnormalBillDispose);
        }else if(Constants.ABNORMAL_OTHER.equals(category)){
            this.anomalyReportOther(abnormalBill,abnormalBillDispose,null,null);
        }

    }

    /**
     * 异常消息的发送
     * @param abnormalBill
     * @param abnormalBillDispose
     * @return
     */
    @Override
    public boolean anomalyCreatedAndSendMessage(AbnormalBill abnormalBill,AbnormalBillDispose abnormalBillDispose){
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        Message abnormalMessage = new Message();
        //发送消息的主键
        String handle = UUID.randomUUID().toString();
        abnormalMessage.setHandle(handle);
        //站点
        abnormalMessage.setSite(site);
        //异常单
        abnormalMessage.setObjectBo(abnormalBill.getHandle());
        //设置类型
        abnormalMessage.setType(abnormalBill.getMessageType());

        //找到对应的消息类型
        MessageType messageType = this.findMessageTypeByStatusAndUserGroup(abnormalMessage, abnormalBill, abnormalBillDispose);
        //设置消息类型
        abnormalMessage.setMessageType(messageType.getMessageType());
        //格式化消息
        String message = this.formatMessage(abnormalBill, abnormalMessage.getMessageType(), site);
        //得到消息触发的时间
        abnormalMessage.setResponseDateTime(now);
        //得到要发送的消息
        abnormalMessage.setContent(message);

        List<Message> messages = null;
        //设置发送的用户组和异常节点
        switch (abnormalBill.getStatus()){
            //新建
            case Constants.NEW:
                abnormalMessage.setSendUserGroup(abnormalBill.getReportSendUserGroup());
                abnormalMessage.setNode(Constants.ABNORMAL_MESSAGE_REPORT);
                break;

            //响应中,设置响应超时的用户的发送的用户组为提报时要升级的用户组
            case Constants.RESPONSE:
                Message abnormalMessage1 = new Message();
                abnormalMessage1.setSite(site);
                abnormalMessage1.setObjectBo(abnormalBill.getHandle());
                abnormalMessage1.setNode(Constants.ABNORMAL_MESSAGE_REPORT);
                abnormalMessage1.setGrade(Double.parseDouble("1"));
                messages = messageService.selectList(abnormalMessage1);
//                Message _abnormalMessage = messageMapper.selectOne(wrapper);
                if(messages.size() > 0) {
                    abnormalMessage.setUpUserGroup(messages.get(0).getUpUserGroup());
                    abnormalMessage.setUpMessageType(messages.get(0).getUpMessageType());
                    abnormalMessage.setGrade(messages.get(0).getGrade());
                }
                break;

            //纠纷确认
            case Constants.CORRECTION_CONFIRM:
                abnormalMessage.setSendUserGroup(abnormalBillDispose.getDutySendUserGroup());
                abnormalMessage.setNode(Constants.ABNORMAL_MESSAGE_CORRECTION_CONFIRM);
                //找到责任划分超时的，并关闭
                UpdateWrapper<Message> dutyWrapper = new UpdateWrapper<>();
                Message dutyMessage = new Message();
                dutyMessage.setStatus("Y");
                dutyWrapper.eq("STATUS","N");
                dutyWrapper.eq("OBJECT_BO",abnormalMessage.getObjectBo());
                dutyWrapper.eq("NODE",Constants.ABNORMAL_MESSAGE_RESPONSE_DUTY);
                messageService.update(dutyMessage,dutyWrapper);
                break;

            //方案确认
            case Constants.PROGRAM_CONFIRM:
                abnormalMessage.setSendUserGroup(abnormalBillDispose.getResolveSendUserGroup());
                abnormalMessage.setNode(Constants.ABNORMAL_MESSAGE_PROGRAM_CONFIRM);
                //找到方案确认超时的，并关闭
                UpdateWrapper<Message> resolveWrapper = new UpdateWrapper<>();
                Message resolveMessage = new Message();
                resolveMessage.setStatus("Y");
                resolveWrapper.eq("STATUS","N");
                resolveWrapper.eq("OBJECT_BO",abnormalMessage.getObjectBo());
                resolveWrapper.eq("NODE",Constants.ABNORMAL_MESSAGE_RESPONSE_RESOLVE);
                messageService.update(resolveMessage,resolveWrapper);
                break;

            //取消
            case Constants.CANCEL:
                abnormalMessage.setSendUserGroup(abnormalBill.getCancelSendUserGroup());
                abnormalMessage.setNode(Constants.ABNORMAL_MESSAGE_CANCEL);
                //异常取消的时候要关闭当前异常单下所有的异常信息
                UpdateWrapper<Message> messageTypeUpdateWrapper = new UpdateWrapper<>();
                Message abnormalMessage2 = new Message();
                abnormalMessage2.setStatus("Y");
                messageTypeUpdateWrapper.eq("STATUS","N");
                messageTypeUpdateWrapper.eq("OBJECT_BO",abnormalMessage.getObjectBo());
                messageService.update(abnormalMessage2,messageTypeUpdateWrapper);
                break;
            default:
                break;
        }



        //设置状态，新建是N,响应比较特殊,在下面设置
        if(Constants.ABNORMAL_MESSAGE_REPORT.equals(abnormalMessage.getNode())){
            abnormalMessage.setStatus("N");
        }else{
            abnormalMessage.setStatus("Y");
        }


        //得到升级的用户组、升级的时间和等级、升级的消息
        //新建有、响应没有、纠防确认没有、方案确认没有、取消没有、关闭没有
        if(Constants.NEW.equals(abnormalBill.getStatus()) ){
            abnormalMessage.setUpUserGroup(abnormalMessage.getSendUserGroup()+"_SJ");
            //得到升级的时间和等级
            UserGroup customFieldByGroup = userGroupMapper.getCustomFieldByGroup(site, abnormalMessage.getSendUserGroup());
            if(customFieldByGroup != null && !StringUtil.isBlank(customFieldByGroup.getMessageNoticeTime())){
                abnormalMessage.setUpDateTime(abnormalMessage.getResponseDateTime().plusMinutes(Integer.parseInt(customFieldByGroup.getMessageNoticeTime())));
            }else{
                throw new BaseException("该用户组没有维护升级的时间，请维护。");
            }

            if(!StringUtil.isBlank(customFieldByGroup.getMessageNoticeLevel())){
                abnormalMessage.setGrade(Double.parseDouble(customFieldByGroup.getMessageNoticeLevel()));
            }else{
                throw new BaseException("该用户组没有维护等级，请维护。");
            }
            MessageType messageTypeUp = messageTypeMapper.findMessageTypeByUserGroup(site, abnormalMessage.getUpUserGroup());
            //得到升级的消息类型
            if(messageTypeUp == null){
                throw new BaseException("用户组"+abnormalMessage.getSendUserGroup()+"的升级用户没有维护消息类型");
            }
            abnormalMessage.setUpMessageType(messageTypeUp.getMessageType());
        }

        abnormalMessage.setCreatedUser(user);
        abnormalMessage.setCreatedDateTime(now);
        abnormalMessage.setModifiedUser(user);
        abnormalMessage.setModifiedDateTime(now);


        //如果是响应状态的话，，并且要设置其超时时间和节点和状态，并关闭新建状态的消息
        if (Constants.RESPONSE.equals(abnormalBill.getStatus())) {
            if(messages != null && messages.size() > 0) {
                this.saveDutyMessageAndResolveMessageByNodeIsResponse(abnormalMessage,messages.get(0).getSendUserGroup());
            }
            return true;
        }
        //发送消息
        if(!Constants.ABNORMAL_MESSAGE_RESPONSE.equals(abnormalMessage.getNode())){
            List<NwaUser> nwaUsers  = nwaUserService.checkUserGroup(site,abnormalMessage.getSendUserGroup());
            if(nwaUsers != null && nwaUsers.size() <= 0){
                throw new BaseException("消息发送失败，发送的用户组下面没有用户");
            }
            List<String> customFieldByUserId = usrMapper.findCustomFieldByUserId(site, nwaUsers);
            if(customFieldByUserId != null && customFieldByUserId.size() <= 0){
                throw new BaseException("消息发送失败，发送的用户组下面的用户的自定义数据没有维护");
            }
            StringBuilder sendUsers = new StringBuilder();
            for (int i = 0; i < Objects.requireNonNull(customFieldByUserId).size(); i++) {
                if(i == (customFieldByUserId.size() - 1)){
                    sendUsers.append(customFieldByUserId.get(i));
                }else{
                    sendUsers.append(customFieldByUserId.get(i)).append("|");
                }
            }
            activeMQUtil.wechatSendMessage(sendUsers.toString(),abnormalMessage.getContent());
        }

        messageService.saveOrUpdate(abnormalMessage);
        return true;
    }
    @Override
    public String formatMessage(AbnormalBill abnormalBill, String messageType, String site) {
        //找到消息内容
        MessageType messageTypeEntity = new MessageType();
        messageTypeEntity.setSite(site);
        messageTypeEntity.setMessageType(messageType);
        QueryWrapper<MessageType> messageTypeQueryWrapper = new QueryWrapper<MessageType>();
        messageTypeQueryWrapper.setEntity(messageTypeEntity);
        MessageType sendMessageType = messageTypeMapper.selectOne(messageTypeQueryWrapper);
        if(sendMessageType == null){
            throw new BaseException("异常提报时找不到要发送的消息类型");
        }
        //找到要替换的消息
        Map<String, String> replaceMessage = abnormalBillMapper.findReplaceMessageByAbnormal(abnormalBill);
        String messageBody = sendMessageType.getBody();
        //格式化之后的消息
        return StringUtils.format(messageBody, replaceMessage);
        //查处所有要替换的消息内容
       // AbnormalBillDisposeDto messageContent = abnormalBillDisposeMapper.findAllByAbnormalNo(abnormalBill, locale);
//        //格式化消息
//        String messageBody = sendMessageType.getBody();
//        //替换消息类型中的参数
//        Map<String, String> messageMap = new HashMap<>();
//        messageMap.put("ABNORMAL_NO",messageContent.getAbnormalNo());
//        messageMap.put("STATUS", AnomalyConstant.Status.msg(messageContent.getStatus()));
//        messageMap.put("ITEM",messageContent.getItem());
//        messageMap.put("DESCRIPTION",messageContent.getItemDescription());
//        messageMap.put("TYPE",AnomalyConstant.Type.msg(messageContent.getType()));
//        messageMap.put("SFC",messageContent.getSfc());
//        messageMap.put("SHOP_ORDER",messageContent.getShopOrder());
//        messageMap.put("WORK_CENTER",messageContent.getWorkCenterDescription());
//        messageMap.put("RESRCE",messageContent.getResrceDescription());
//        messageMap.put("WORK_ORDER",messageContent.getWorkOrder());
//        messageMap.put("PB_DESCRIPTION",messageContent.getPbDescription());
//        messageMap.put("NC_QTY",messageContent.getNcQty());
//        messageMap.put("PB_GRADE",messageContent.getPbGrade());
//        messageMap.put("PB_USER",messageContent.getPbUser());
//        messageMap.put("PB_QTY",messageContent.getPbQty());
//        messageMap.put("DISCOVER",AnomalyConstant.Discover.msg(messageContent.getDiscover()));
//        messageMap.put("ENTITY_LOCATION",messageContent.getEntityLocation());
//        messageMap.put("REPORT_FROM",AnomalyConstant.ReportFrom.msg(messageContent.getReportFrom()));
//        messageMap.put("OPERATION",messageContent.getOperationDescription());
////        messageMap.put("reportSendUserGroup",messageContent.getReportSendUserGroup());
//        if(StringUtil.isBlank(messageContent.getNcCode()) || "/,".equals(messageContent.getNcCode())){
//            messageMap.put("NC_CODE","");
//        }else{
//            String ncCode = messageContent.getNcCode().substring(0,messageContent.getNcCode().length() - 1);
//            messageMap.put("NC_CODE",ncCode);
//        }
//        if(StringUtil.isBlank(messageContent.getNcCodeDescription()) || "/,".equals(messageContent.getNcCodeDescription())){
//            messageMap.put("NC_CODE_DESCRIPTION","");
//        }else{
//            String ncCodeDescription = messageContent.getNcCodeDescription().substring(0,messageContent.getNcCodeDescription().length() - 1);
//            messageMap.put("NC_CODE_DESCRIPTION",ncCodeDescription);
//        }
//        messageMap.put("SHUT_DOWN",AnomalyConstant.ShutDown.msg(messageContent.getShutDown()));
//
//        //判断该异常单的状态是否是纠防确认
//        if(Constants.CORRECTION_CONFIRM.equals(messageContent.getStatus()) || Constants.SHUT_DOWN.equals(messageContent.getStatus())){
//
//            DataField dataField = new DataField();
//            dataField.setSite(site);
//            //原因分类
//            String dutyCauseType = messageContent.getDutyCauseType();
//            if(!StringUtil.isBlank(dutyCauseType)){
//                List<String> dutyCauseTypeList = Arrays.asList(dutyCauseType.split(","));
//                dataField.setDataField("REASON_CATEGORY");
//                dataField.setDataValue(dutyCauseTypeList);
//                String dutyCauseTypeDescription = dataFieldListMapper.findDataFieldListByDataField(dataField, locale);
//                messageMap.put("DUTY_CAUSE_TYPE",dutyCauseTypeDescription);
//            }else{
//                messageMap.put("DUTY_CAUSE_TYPE","");
//            }
//            //责任部门
//            String dutyDepart = messageContent.getDutyDepart();
//            if(!StringUtil.isBlank(dutyDepart)){
//                List<String> dutyDepartList = Arrays.asList(dutyDepart.split(","));
//                dataField.setDataField("RESPONSIBILITY_DEPARTMENT");
//                dataField.setDataValue(dutyDepartList);
//                String dutyDepartDescription = dataFieldListMapper.findDataFieldListByDataField(dataField, locale);
//                messageMap.put("DUTY_DEPART",dutyDepartDescription);
//            }else{
//                messageMap.put("DUTY_DEPART","");
//            }
//            //责任分类
//            String dutyType = messageContent.getDutyType();
//            if(!StringUtil.isBlank(dutyType)){
//                List<String> dutyTypeList = Arrays.asList(dutyType.split(","));
//                dataField.setDataField("RESPONSIBILITY_TYPE");
//                dataField.setDataValue(dutyTypeList);
//                String dutyDepartDescription = dataFieldListMapper.findDataFieldListByDataField(dataField, locale);
//                messageMap.put("DUTY_TYPE",dutyDepartDescription);
//            }else{
//                messageMap.put("DUTY_TYPE","");
//            }
//            messageMap.put("PRINCIPAI_USER",messageContent.getPrincipalUser());
//            messageMap.put("DUTY_CAUSE_DESCRIPTION",messageContent.getDutyCauseDescription());
//        }
//
//        if(Constants.PROGRAM_CONFIRM.equals(messageContent.getStatus())  || Constants.SHUT_DOWN.equals(messageContent.getStatus())){
//            messageMap.put("ABNORMAL_METHOD",AnomalyConstant.AnomalyMethod.msg(messageContent.getAbnormalMethod()));
//            messageMap.put("RESOLVE_REMAKR",messageContent.getResolveRemark());
//            messageMap.put("ROUTER",messageContent.getRouterDescription());
//            messageMap.put("RESOLVE_SHOP_ORDER",messageContent.getResolveShopOrder());
//        }
    }

    @Override
    public List<AbnormalBill> getQCAbnormal() {
        return abnormalBillMapper.getQCAbnormalList(CommonMethods.getSite());
    }

    @Override
    public IPage getAbnormalByConditionalPage(IPage page,Map paramMap,String keyword) {
        paramMap.put("site",CommonMethods.getSite());
        return abnormalBillMapper.getAbnormalByConditional(page,paramMap,keyword);
    }

    @Override
    public IPage getAbnormalSFCPage(IPage page, Map paramMap, String keyword) {
        paramMap.put("site",CommonMethods.getSite());
        return abnormalBillMapper.getAbnormalSFCPage(page,paramMap,keyword);
    }

    /**
     * @param sfcDto 以下是传递的参数
     * sfc
     * abnormalNo
     * qty
     * stepId
     * */
    @Override
    public void batchRepair(SfcDto sfcDto) {
        String site = CommonMethods.getSite();
        String sfc = sfcDto.getSfc();
        String abnormalNo = sfcDto.getAbnormalNo();

        String handle = HandleEnum.SFC.getHandle(site, sfc);
        BigDecimal splitQty = new BigDecimal(sfcDto.getQty());

        //根据sfc找工单等信息
        SfcDto sfcData = splitSfcMapper.getSfcData(handle);
        if (sfcData==null){
            Sfc sfcServiceById = sfcService.getById(handle);
            if (!sfcServiceById.getStatusBo().equals(HandleEnum.STATUS.getHandle(site,"405"))){
                throw new BaseException("未找到产品条码信息");
            }
            sfcData= splitSfcMapper.getCompleteSfcData(handle).get(0);
        }
        String operation = sfcData.getOperation();
        SfcDispatchDto sfcDispatchDto = new SfcDispatchDto();
        sfcDispatchDto.setSite(site);
        sfcDispatchDto.setSfc(sfc);
        sfcDispatchDto.setStepId(sfcData.getStepId());
        SfcDispatchDto sfcDispatchBySfc = sfcDispatchCommonService.findSfcDispatchBySfc(sfcDispatchDto);
        if (sfcDispatchBySfc.equals(DispatchStatusEnum.CANCEL.getCode())){
            throw new BaseException("产品已取消派工");
        }
        //查询质量异常记录数量 处置工艺路线及不良代码
        SplitSfcDto splitSfcDto=splitSfcMapper.getAbnormalQty(site,sfc, abnormalNo);
        if(splitSfcDto == null){
            throw new BaseException("没有找到报废的信息");
        }
        String routerBo = splitSfcDto.getRouterBo();
        String ncCode = splitSfcDto.getNcCode();

        String[] splitNcCode = ncCode.split(",");

        SplitSfcRequest splitSfcRequest=new SplitSfcRequest();
        try{
            SplitSerializeServiceInterface splitService =  MEServices.create("com.sap.me.production", "SplitSerializeService",site);
            NCProductionServiceInterface ncProductionService =  MEServices.create("com.sap.me.nonconformance", "NCProductionService",site);

            //记录不合格
            CreateNCRequest createNCRequest=new CreateNCRequest();
            createNCRequest.setQty(splitQty);
            createNCRequest.setSfcRef(HandleEnum.SFC.getHandle(site,sfc));
            ProductionContext productionContext=new ProductionContext();
            StepIdentifier stepIdentifier=new StepIdentifier();
            stepIdentifier.setStepId(sfcData.getStepId());
            stepIdentifier.setOperationId(sfcData.getOperation());
            productionContext.setStepIdentifier(stepIdentifier);
            productionContext.setResourceRef(commonService.getResrceByOperation(sfcData.getOperation()));
            createNCRequest.setProdCtx(productionContext);
            createNCRequest.setNcCodeRef(HandleEnum.NC_CODE.getHandle(site,splitNcCode[0]));
            ncProductionService.createNC(createNCRequest);
            //不合格处置特殊工艺路线
            DispositionMultipleSfcsRequest dispositionSfcsRequest=new DispositionMultipleSfcsRequest();
            List<String> sfcs=new ArrayList<>();
            sfcs.add(HandleEnum.SFC.getHandle(site,sfc));
            dispositionSfcsRequest.setSfcs(sfcs);
            dispositionSfcsRequest.setBypassStepValidation(true);
            DispositionSelection dispositionSelection=new DispositionSelection();
            Router maxRevisionRouter = routerService.getMaxRevisionRouter(site, StringUtil.trimHandle(routerBo));
            dispositionSelection.setRouterRef(maxRevisionRouter.getHandle());
            dispositionSfcsRequest.setDispositionSelection(dispositionSelection);
            dispositionSfcsRequest.setProdCtx(new ProductionContext());
            ncProductionService.dispositionMultipleSfcs(dispositionSfcsRequest);
            List<RouterStepDto> routerOperationByRouterBo = routerStepService.findRouterOperationByRouterBo(site, maxRevisionRouter.getHandle());
            if (routerOperationByRouterBo.isEmpty()){
                throw new BaseException("处置工艺路线没有步骤");
            }
            sfcDispatchCommonService.saveSplitSfcDispatch(site, CommonMethods.getUser(),"A", sfcData.getShopOrder(), sfc, operation, sfcDispatchBySfc.getStepId(),sfc, maxRevisionRouter.getHandle(), sfcData.getStepSequence());
        }catch (Exception e){
            ExceptionUtil.throwException(e);
        }
    }

    @Override
    public MessageType findMessageTypeByStatusAndUserGroup(Message message, AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose) {
        String status = abnormalBill.getStatus();
        String site = CommonMethods.getSite();
        String userGroup = null;
        //根据异常单的状态找到对应的用户组
        switch (status){
            case Constants.NEW:
            case Constants.RESPONSE:
                userGroup = abnormalBill.getReportSendUserGroup();
                break;
            case Constants.PROGRAM_CONFIRM:
                userGroup = abnormalBillDispose.getResolveSendUserGroup();
                break;
            case Constants.CORRECTION_CONFIRM:
                userGroup = abnormalBillDispose.getDutySendUserGroup();
                break;
            case Constants.CANCEL:
                userGroup = abnormalBill.getCancelSendUserGroup();
                break;
            default:
        }
        //如果异常单的状态为关闭，则直接返回true，因为这两个状态不需要发送消息
        if(Constants.SHUT_DOWN.equals(status)){
            return null;
        }
        if(StringUtils.isBlank(userGroup)){
            throw new BaseException("消息发送失败，找不到对应的用户组");
        }else{
            MessageType type = null;
            try{
              type = messageTypeMapper.findMessageTypeByUserGroup(site, userGroup);
            }catch (Exception e){
                throw new BaseException("根据发送的用户组找到有可能找到多个对应的消息类型，请检查。"+e.getMessage());
            }
            if(type == null){
                throw new BaseException("根据发送的用户组找不到对应的消息类型，请维护。");
            }else{
                return type;
            }

        }
    }

    @Override
    public void saveDutyMessageAndResolveMessageByNodeIsResponse(Message paramMessage,String userGroup) {
        Message message = new Message();
        String uuid = UUID.randomUUID().toString();
        message.setHandle(uuid);
        message.setSite(paramMessage.getSite());
        message.setObjectBo(paramMessage.getObjectBo());
        message.setType(paramMessage.getType());
        message.setMessageType(paramMessage.getMessageType());
        message.setSendUserGroup(paramMessage.getSendUserGroup());
        message.setSendUser(paramMessage.getSendUser());
        message.setContent(paramMessage.getContent());
        message.setUpUserGroup(paramMessage.getUpUserGroup());
        message.setUpUser(paramMessage.getUpUser());
        message.setUpMessageType(paramMessage.getUpMessageType());
        message.setResponseDateTime(paramMessage.getResponseDateTime());
        message.setGrade(paramMessage.getGrade());
        message.setCreatedUser(paramMessage.getCreatedUser());
        message.setCreatedDateTime(paramMessage.getCreatedDateTime());
        message.setModifiedUser(paramMessage.getModifiedUser());
        message.setModifiedDateTime(paramMessage.getModifiedDateTime());
        UserGroup customFieldByGroup = userGroupMapper.getCustomFieldByGroup(message.getSite(), userGroup);
        if(customFieldByGroup != null){
            if(StringUtils.isBlank(customFieldByGroup.getMessageDutyTime())){
                throw new BaseException("请维护用户组:"+userGroup+"的自定义字段（责任划分超时时间）");
            }
            if(StringUtils.isBlank(customFieldByGroup.getMessageResolveTime())){
                throw new BaseException("请维护用户组:"+userGroup+"的自定义字段（方案确认超时时间）");
            }
            message.setUpDateTime(message.getResponseDateTime().plusMinutes(Integer.parseInt(customFieldByGroup.getMessageDutyTime())));
            paramMessage.setUpDateTime(message.getResponseDateTime().plusMinutes(Integer.parseInt(customFieldByGroup.getMessageResolveTime())));
        }else{
            throw new BaseException("请维护用户组:"+userGroup+"的自定义字段（消息通知时间、消息通知等级、责任划分超时时间、责任划分超时等级）");
        }

        message.setNode(Constants.ABNORMAL_MESSAGE_RESPONSE_DUTY);
        paramMessage.setNode(Constants.ABNORMAL_MESSAGE_RESPONSE_RESOLVE);
        paramMessage.setStatus("N");
        message.setStatus("N");
        List<Message> messages = new ArrayList<>();
        messages.add(message);
        messages.add(paramMessage);
        //关闭新建状态的消息

        //找到新建状态的，并关闭
        UpdateWrapper<Message> resolveWrapper = new UpdateWrapper<>();
        Message resolveMessage = new Message();
        resolveMessage.setStatus("Y");
        resolveWrapper.eq("STATUS","N");
        resolveWrapper.eq("OBJECT_BO",paramMessage.getObjectBo());
        resolveWrapper.eq("NODE",Constants.ABNORMAL_MESSAGE_REPORT);
        messageService.update(resolveMessage,resolveWrapper);

        messageService.saveOrUpdateBatch(messages);
    }

    @Override
    public Map<String, String> jgProductionIsScrap(String abnormalNo, String site, String sfc) {
        //查询该sfc在质量异常异常方案是否是报废,如果是，则大于1
        String abnormalBo = null;
        if(!StringUtils.isBlank(abnormalNo)){
           abnormalBo = HandleEnum.ABNORMAL_BILL.getHandle(site,abnormalNo);
        }
        return abnormalBillMapper.findAbnormalMethodBySFC(site,abnormalBo, sfc);
    }

    @Override
    public List<ScrapDto> getScrapDtoBysfc(String abnormalNo, String site, String sfc) {
        if(StringUtil.isBlank(site)){
            site = CommonMethods.getSite();
        }
        //根据用户提报上来的sfc和异常单查找主SFC
        Map<String, String> map = this.jgProductionIsScrap(abnormalNo, site, sfc);
        String mainSfc = null;
        String abnormalBo = null;
        if(map != null){
             mainSfc = map.get("SFC");
             abnormalBo = map.get("HANDLE");
        }

        List<SplitSfc> splitSfcs = null;
        SplitSfc splitSfc = new SplitSfc();
        splitSfc.setSite(site);

        //判断能否找到该主sfc。
        if(StringUtil.isBlank(mainSfc)){
            //判断该用户提报上来的sfc是否为空
            if(StringUtil.isBlank(sfc)) {
                throw new BaseException("该异常单下没有报废的产品条码");
            }

            //如果不为空，则判断根据这个sfc能从Z_SPLIT_SFC表中查找到主SFC吗，然后在判断主SFC是否已经报废
            splitSfc.setSplitSfc(sfc);
            splitSfcs = splitSfcService.selectList(splitSfc);
            if(splitSfcs.size()>0){
                Map<String, String> map1 = this.jgProductionIsScrap(abnormalNo, site, splitSfcs.get(0).getSfc());
                mainSfc = map1.get("SFC");
                abnormalBo = map1.get("HANDLE");
            }else{
                if(!StringUtil.isBlank(sfc) && !StringUtil.isBlank(abnormalNo)){
                    throw new BaseException("该异常单下的产品条码不是报废");
                }
                throw new BaseException("该产品条码的异常方案不是报废");
            }
        }else if(StringUtil.isBlank(sfc)){
            //根据异常单找到了主sfc，并且sfc参数为空，找到异常单主sfc下拆分的次sfc
            splitSfc.setSfc(mainSfc);
            splitSfcs = splitSfcService.selectList(splitSfc);
        }
        List<ScrapDto> scrapDtoBySfc = abnormalBillMapper.findScrapDtoBySfc(site, mainSfc,splitSfcs);

        //如果用户提报上来的sfc不为空，并且不是主sfc，则把主sfc从scrapDtoBySfc去掉
        if(!StringUtil.isBlank(sfc) && !sfc.equals(mainSfc)){
            for (int i = 0; i < scrapDtoBySfc.size(); i++) {
                if(scrapDtoBySfc.get(i).getSfc().equals(mainSfc)){
                    scrapDtoBySfc.remove(scrapDtoBySfc.get(i));
                    continue;
                }
            }
        }
        if(scrapDtoBySfc.size() <= 0){
            throw new BaseException("该产品条码的异常方案不是报废");
        }

        //查找到责任人,放到表里
        AbnormalBillDispose abnormalBillDispose = new AbnormalBillDispose();
        abnormalBillDispose.setAbnormalBillBo(abnormalBo);
        List<AbnormalBillDispose> abnormalBillDisposes = abnormalBillDisposeService.selectList(abnormalBillDispose);
        if(abnormalBillDisposes.size() > 0){
            for (int i = 0; i < scrapDtoBySfc.size(); i++) {
                scrapDtoBySfc.get(i).setDutyUser(abnormalBillDisposes.get(0).getPrincipalUser());
            }
        }
        return scrapDtoBySfc;
    }
    void creatInspectionTask(String site,String inspectionTaskBo,String sfc,String stepId,String comments){
        InspectionTask byId = inspectionTaskService.getById(inspectionTaskBo);
        InspectionTask newInspectionTask = new InspectionTask();
        if (StringUtil.notBlank(inspectionTaskBo)){
            if (byId==null){
                throw new BaseException("不存在的专检任务");
            }
            BeanUtils.copyProperties(byId, newInspectionTask);
            String newTaskNo = "P_" + DateUtil.getTimeString();
            String handle = HandleEnum.INSPECTION_TASK.getHandle(site, newTaskNo);
            newInspectionTask.setHandle(handle);
            newInspectionTask.setTaskNo(newTaskNo);
            newInspectionTask.setStatus(Constants.INSPECTION_TASK_STATUS_NEW);
            newInspectionTask.setResult(null);
            newInspectionTask.setComments(comments);
            newInspectionTask.setCreatedDateTime(LocalDateTime.now());
            newInspectionTask.setModifiedDateTime(LocalDateTime.now());
        }else {
            String taskNo = "P_" + DateUtil.getTimeString();
            String handle = "InspectionBO:" + site + "," + taskNo;
            SfcDispatchDto sfcDispatchDto = new SfcDispatchDto();
            sfcDispatchDto.setSfc(sfc);
            sfcDispatchDto.setStepId(stepId);
            SfcDispatchDto sfcDispatchBySfc = sfcDispatchCommonService.findSfcDispatchBySfc(sfcDispatchDto);

            InspectionTask task = new InspectionTask();
            task.setHandle(handle);
            task.setSite(site);
            task.setCategory(Constants.INSPECTION_TYPE_P);
            task.setTaskNo(taskNo);
            task.setStatus(Constants.INSPECTION_TASK_STATUS_NEW);
            task.setResult(null);
            task.setDescription("专检检验任务");
            task.setInspectionItemBo( null);
            task.setShopOrder(sfcDispatchBySfc.getShopOrder());
            task.setWorkCenter(sfcDispatchBySfc.getWorkCenter());
            task.setSfc(sfc);
            task.setOperation(sfcDispatchBySfc.getOperation());
            task.setStepId(stepId);
            task.setResrce(sfcDispatchBySfc.getResrce());
            task.setCreateUser(CommonMethods.getUser());
            task.setCreatedDateTime(LocalDateTime.now());
            task.setModifyUser(CommonMethods.getUser());
            task.setModifiedDateTime(LocalDateTime.now());
            task.setSfcDispatchBo(sfcDispatchBySfc.getHandle());
            task.setComments(comments);
            task.setSfc(sfc);
        }
        inspectionTaskService.save(newInspectionTask);
    }
}