package com.sw.mes.fb.aio.service.impl;


import com.sw.mes.base.factory.init.entity.FactoryModel;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.fb.aio.dao.EapGrindingRackDao;
import com.sw.mes.fb.aio.entity.EapGrindingRack;
import com.sw.mes.fb.aio.service.EapGrindingRackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class EapGrindingRackServiceImpl extends BaseServiceImpl<EapGrindingRack> implements EapGrindingRackService {
    EapGrindingRackDao dao;
	@Autowired
    public void setDao(EapGrindingRackDao dao) {
        super.setBaseDao(dao);
        this.dao=dao;
    }

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Override
    public EapGrindingRack findTopBySnOrderByIdDesc(String sn) {
        return dao.findTopBySnOrderByIdDesc(sn);
    }

    @Override
    public void save(EapGrindingRack eapGrindingRack) {
        List<PlanProcessingOrder> planProcessingOrders = planProcessingOrderService.findByCodeOrderByIdDesc(eapGrindingRack.getSn());
        if (planProcessingOrders.size() == 0) {
            throw new BusinessException("工单号【" + eapGrindingRack.getSn() + "】不存在");
        }
        PlanProcessingOrder planProcessingOrder = planProcessingOrders.get(0);
        if (planProcessingOrder.getStatus() == EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()) {
            // 查询加工工单信息，判断是否是本站点的加工品
            FactoryModel factoryModel = wipStorageService.getFactoryModel(planProcessingOrder.getWipStorage().getProcessId(), planProcessingOrder.getWipStorage().getProcessName());
            if (null !=factoryModel
                    && factoryModel.getCode().equals(EnumValuesFactory.WipStorageCode.磨倒.getKey())
                    && planProcessingOrder.getWipStorage().getStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey()
            ) {
                //站点变更，手动进出站
                ybFeignClients.inAndOutStation(eapGrindingRack.getSn(), eapGrindingRack.getEquipNo(), EnumValuesFactory.WipStorageCode.磨倒.getKey(), 0);
            }
            saveOrUpdate(eapGrindingRack);
        }
    }
}
