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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.dto.SfcDispatchDto;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.service.SfcDispatchCommonService;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.meapi.dto.SfcDto;
import com.foreverwin.mesnac.production.mapper.SfcHoldLogMapper;
import com.foreverwin.mesnac.production.mapper.SplitSfcMapper;
import com.foreverwin.mesnac.production.model.SfcHoldLog;
import com.foreverwin.mesnac.production.service.SfcHoldLogService;
import com.foreverwin.modular.core.exception.BaseException;
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.production.SfcStateServiceInterface;
import com.sap.me.production.UpdateSfcStatusRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 产品条码保留记录 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-08-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SfcHoldLogServiceImpl extends ServiceImpl<SfcHoldLogMapper, SfcHoldLog> implements SfcHoldLogService {

    @Autowired
    private SfcDispatchCommonService sfcDispatchCommonService;
    @Autowired
    private SfcHoldLogMapper sfcHoldLogMapper;
    @Autowired
    private SplitSfcMapper splitSfcMapper;
    @Override
    public IPage<SfcHoldLog> selectPage(FrontPage<SfcHoldLog> frontPage, SfcHoldLog sfcHoldLog) {
        QueryWrapper<SfcHoldLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(sfcHoldLog);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

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

    @Override
    public void sfcHold(List<SfcHoldLog> sfcHoldLogList) {
        for (SfcHoldLog sfcHoldLog:sfcHoldLogList){
            String site = CommonMethods.getSite();
            LocalDateTime now = LocalDateTime.now();
            String sfc = sfcHoldLog.getSfc();
            String type = sfcHoldLog.getType();
            String sfcBo = HandleEnum.SFC.getHandle(site, sfc);
            SfcDto sfcData = splitSfcMapper.getSfcData(sfcBo);
            if (sfcData==null){
                throw new BaseException("未找到产品条码信息");
            }
            if (sfcHoldLog.getType().equals("HOLD")&&!sfcData.getStatus().equals("403")){
                throw new BaseException("产品状态不可暂停");
            }
            if (sfcHoldLog.getType().equals("CANCEL")&&!sfcData.getStatus().equals("404")){
                throw new BaseException("产品状态不可取消暂停");
            }
            String stepId = sfcData.getStepId();
            String operation = sfcData.getOperation();
            SfcDispatchDto sfcDispatchDto = new SfcDispatchDto();
            sfcDispatchDto.setSfc(sfc);
            sfcDispatchDto.setStepId(stepId);
            sfcDispatchDto.setOperation(operation);
            SfcDispatchDto sfcDispatchBySfc = sfcDispatchCommonService.findSfcDispatchBySfc(sfcDispatchDto);
            SfcStateServiceInterface sfcStateServiceInterface = null;
            BigDecimal holdDuration=null;
            try {
                sfcStateServiceInterface = MEServices.create("com.sap.me.production", "SfcStateService", CommonMethods.getSite());
                UpdateSfcStatusRequest updateSfcStatusRequest = new UpdateSfcStatusRequest();
                updateSfcStatusRequest.setSfcRef(sfcBo);
                if (type.equals("HOLD")){
                    updateSfcStatusRequest.setStatusRef(HandleEnum.STATUS.getHandle(site,"404"));
                }else {
                    updateSfcStatusRequest.setStatusRef(HandleEnum.STATUS.getHandle(site,"403"));
                    //计算保留时长
                    QueryWrapper<SfcHoldLog> ueryWrapper=new QueryWrapper<>();
                    ueryWrapper.eq(SfcHoldLog.STEP_ID,stepId);
                    ueryWrapper.eq(SfcHoldLog.SFC,sfc);
                    ueryWrapper.orderByDesc(SfcHoldLog.CREATED_DATE_TIME);
                    List<SfcHoldLog> list = list(ueryWrapper);
                    LocalDateTime holdTime = list.get(0).getCreatedDateTime();
                    long workHourSeconds = Duration.between(holdTime, now).getSeconds();
                    holdDuration = new BigDecimal(workHourSeconds).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP);
                }
                sfcStateServiceInterface.updateSfcStatus(updateSfcStatusRequest);
            } catch (Exception e) {
                ExceptionUtil.throwException(e);
            }
            sfcHoldLog.setHandle(UUID.randomUUID().toString());
            sfcHoldLog.setSite(site);
            sfcHoldLog.setSfcDispatchBo(sfcDispatchBySfc.getHandle());
            sfcHoldLog.setStepId(stepId);
            sfcHoldLog.setOperation(operation);
            sfcHoldLog.setHoldDuration(holdDuration);
            sfcHoldLog.setCreateUser(CommonMethods.getUser());
            sfcHoldLog.setCreatedDateTime(now);
            save(sfcHoldLog);

        }

    }


}