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.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.model.InspectionTask;
import com.foreverwin.mesnac.common.service.InspectionTaskService;
import com.foreverwin.mesnac.common.service.SfcDispatchCommonService;
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.meapi.model.Operation;
import com.foreverwin.mesnac.meapi.model.Router;
import com.foreverwin.mesnac.meapi.service.CustomFieldsService;
import com.foreverwin.mesnac.meapi.service.OperationService;
import com.foreverwin.mesnac.meapi.service.RouterService;
import com.foreverwin.mesnac.production.dto.WorkShopTransferDto;
import com.foreverwin.mesnac.production.mapper.SfcCrossMapper;
import com.foreverwin.mesnac.production.mapper.WorkShopTransferMapper;
import com.foreverwin.mesnac.production.model.StepOperation;
import com.foreverwin.mesnac.production.model.WorkShopTransfer;
import com.foreverwin.mesnac.production.service.WorkShopTransferService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 车间转移记录 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-07-30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkShopTransferServiceImpl extends ServiceImpl<WorkShopTransferMapper, WorkShopTransfer> implements WorkShopTransferService {

    @Autowired
    private SfcDispatchCommonService sfcDispatchCommonService;
    @Autowired
    private WorkShopTransferMapper workShopTransferMapper;
    @Autowired
    private InspectionTaskService inspectionTaskService;
    @Autowired
    private CustomFieldsService customFieldsService;
    @Autowired
    private OperationService operationService;
    @Autowired
    private SfcCrossMapper sfcCrossMapper;
    @Autowired
    private RouterService routerService;

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

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

    @Override
    public WorkShopTransferDto sfcEnter(String sfc,String type) {
        //条码是否在工作中心下
        String site = CommonMethods.getSite();
        if (StringUtil.isBlank(sfc)) {
            throw new BaseException("产品条码不能为空");
        }
        WorkShopTransferDto dto =  workShopTransferMapper.getSfcData(site, sfc);
        if (dto == null) {
            //throw new BaseException("未找到该产品条码"); 产品编号:202110110001(具体SFC号)工序数量与工艺路线不符，请联系总计划刷新派工单！
            throw new BaseException("产品条码[" + sfc + "]，工序数量与工艺路线不符，请联系总计划刷新派工单！！");
        }
        String currentOperation = dto.getOperation();
        String operationDesc = dto.getOperationDesc();

        //查询上一工序
        Router router = routerService.getRouterBySfcBo(HandleEnum.SFC.getHandle(site, sfc));
        int seq = 0;
        List<StepOperation> stepOperationList = sfcCrossMapper.findRouterOperationByRouterBo(site, router.getHandle(), LocaleContextHolder.getLocale().getLanguage());
        for (int i = 0; i < stepOperationList.size(); i++) {
            StepOperation stepOperation = stepOperationList.get(i);
            if (stepOperation.getStepId().equals(dto.getStepId())) {
                seq = i;
            }
        }
        String operation = "";
        if (type.equals("IN")){
            if (stepOperationList.size()!=seq+1){
                StepOperation stepOperation = stepOperationList.get(seq + 1);
                operation=stepOperation.getOperation();
                dto.setOperation(operation);
                dto.setOperationDesc(stepOperation.getDescription());
            }
            dto.setLastOperation(currentOperation);
            dto.setLastOperationDesc(operationDesc);
        }else {
            //转出本工序
            operation=dto.getOperation();
            if (seq != 0) {
                StepOperation stepOperation = stepOperationList.get(seq - 1);
                dto.setLastOperation(stepOperation.getOperation());
                dto.setLastOperationDesc(stepOperation.getDescription());
            }
        }
        /*String workCenter;
        if (StringUtil.notBlank(operation)&&operation.contains("_")) {
            workCenter = operation.split("_")[0];
        } else {
            workCenter = operation;
        }
        WorkCenter workCenterModel = workCenterMapper.findWorkCenterDescriptionByWorkCenter(site, workCenter, LocaleContextHolder.getLocale().getLanguage());
        if (workCenterModel == null) {
            throw BusinessException.build("生产车间【" +workCenter+ "】不存在");
        }
        dto.setWorkCenterDesc(workCenterModel.getDescription());
        dto.setWorkCenter(workCenter);*/
        return dto;
    }
    @Override
    public List<WorkShopTransferDto> transferOut(String handleList) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String taskNo =  DateUtil.getTimeString();
        List<WorkShopTransferDto> returnList=new ArrayList<>();
        String[] split = handleList.split(",");
        for (String sfc:split){
            WorkShopTransferDto dto = sfcEnter(sfc,"OUT");
            String stepId = dto.getStepId();
            String isOutSource = dto.getIsOutSource();
            String sfcBO = HandleEnum.SFC.getHandle(site, sfc);
            if (StringUtil.notBlank(isOutSource) && isOutSource.equals("Y")) {
                try {
                    /*Operation currentRevisionRef = operationService.getCurrentRevisionRef(site, dto.getOperation());
                    sfcCrossService.startAction(site, currentRevisionRef.getHandle(), dto.getResrce(), sfcBO, dto.getQty());
                    //更改派工单状态
                    sfcDispatchCommonService.updateSfcDispatchStatus(site, CommonMethods.getUser(), dto.getDispatchNo(), DispatchStatusEnum.START.getCode(),null);
                    */
                } catch (Exception e) {
                    ExceptionUtil.throwException(e);
                }
            }
            List<WorkShopTransferDto> list = workShopTransferMapper.getOutList(site, null, null, null, null,null, sfc,stepId);
            WorkShopTransferDto transferDto = list.get(0);
            WorkShopTransfer transferLog = new WorkShopTransfer();
            transferLog.setHandle(UUID.randomUUID().toString());
            QueryWrapper<WorkShopTransfer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(WorkShopTransfer.SFC_DISPATCH_BO, dto.getSfcDispatchBo());
            List<WorkShopTransfer> workShopTransfers = list(queryWrapper);
            if (!workShopTransfers.isEmpty()) {
                throw BusinessException.build("产品"+sfc+"已转出");
            }
            //检查是否检验合格
            Operation currentRevisionRef = operationService.getCurrentRevisionRef(site, transferDto.getLastOperation());
            String special = customFieldsService.getCustomFieldsValue(currentRevisionRef.getHandle(), "SPECIAL");

            if(StringUtil.isBlank(special) || !special.equals("N")){
                String lastStepId = transferDto.getLastStepId();
                QueryWrapper<InspectionTask> taskQueryWrapper=new QueryWrapper<>();
                taskQueryWrapper.eq(InspectionTask.SFC,sfc);
                taskQueryWrapper.eq(InspectionTask.STEP_ID,lastStepId);
                taskQueryWrapper.orderByDesc(InspectionTask.CREATED_DATE_TIME);
                List<InspectionTask> inspectionTaskList = inspectionTaskService.list(taskQueryWrapper);
                if(!inspectionTaskList.isEmpty()){
                    String status = inspectionTaskList.get(0).getStatus();
                    String result = inspectionTaskList.get(0).getResult();
                    if(!status.equals(Constants.INSPECTION_TASK_STATUS_COMPLETE) ||StringUtil.isBlank(result)||!result.equals(Constants.RSESULT_OK)){
                        throw BusinessException.build("产品"+sfc+"专检任务未完成或不合格");
                    }
                }
            }

            transferLog.setSfcDispatchBo(dto.getSfcDispatchBo());
            transferLog.setSite(site);
            transferLog.setTransferNo(taskNo);
            transferLog.setWorkCenter(transferDto.getWorkCenter());
            transferLog.setTransferWorkCenter(null);
            transferLog.setSfc(sfc);
            transferLog.setShopOrder(transferDto.getShopOrder());
            transferLog.setStepId(dto.getStepId());
            transferLog.setOperation(dto.getOperation());
            transferLog.setLastOperation(transferDto.getLastOperation());
            transferLog.setQty(dto.getQty());
            transferLog.setIsOut("Y");
            transferLog.setIsOutSource(dto.getIsOutSource());
            transferLog.setCreateUser(user);
            transferLog.setCreatedDateTime(LocalDateTime.now());
            transferLog.setModifyUser(user);
            transferLog.setModifiedDateTime(LocalDateTime.now());
            transferLog.setTransferOutUser(user);
            transferLog.setTransferOutTime(LocalDateTime.now());
            save(transferLog);
            dto.setWorkCenter(transferDto.getWorkCenterDesc());
            dto.setBlankingSize(transferDto.getBlankingSize());
            dto.setTransferNo(taskNo);
            dto.setEmployeeDescription(transferDto.getEmployeeDescription());
            dto.setLocalDate(LocalDate.now());
            returnList.add(dto);
        }
        return returnList;
    }

    @Override
    public void transferIn(List<String> handleList) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        for (String sfc:handleList) {
            WorkShopTransferDto dto = sfcEnter(sfc, "IN");
            String isOutSource = dto.getIsOutSource();
            String sfcBO = HandleEnum.SFC.getHandle(site, sfc);
            Operation currentRevisionRef = operationService.getCurrentRevisionRef(site, dto.getOperation());
            //查询是否有转出记录
            QueryWrapper<WorkShopTransfer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(WorkShopTransfer.SFC, sfc);
            queryWrapper.eq(WorkShopTransfer.STEP_ID, dto.getStepId());
            queryWrapper.eq(WorkShopTransfer.IS_OUT, "Y");
            List<WorkShopTransfer> list = list(queryWrapper);
            if (list.isEmpty()) {
                throw BusinessException.build("没有转出记录");
            }
            if (StringUtil.notBlank(isOutSource) && isOutSource.equals("Y")) {
                //转出开始
                try {
                  /*  //转入完成
                    sfcCrossService.completeAction(site, currentRevisionRef.getHandle(), dto.getResrce(), sfcBO, dto.getQty());
                    //更改派工单状态
                    sfcDispatchCommonService.updateSfcDispatchStatus(site, CommonMethods.getUser(), dto.getDispatchNo(), DispatchStatusEnum.COMPLETE.getCode(), BigDecimal.ZERO);
                    */
                } catch (Exception e) {
                    ExceptionUtil.throwException(e);
                }
            }
            WorkShopTransfer transfer = list.get(0);
            if (StringUtil.notBlank(transfer.getIsIn())){
                throw BusinessException.build(sfc+"已转入");
            }
            LocalDateTime now = LocalDateTime.now();
            transfer.setTransferInTime(now);
            transfer.setTransferInUser(user);
            transfer.setModifiedDateTime(now);
            transfer.setModifyUser(user);
            transfer.setIsIn("Y");
            updateById(transfer);
        }
    }

    @Override
    public List<WorkShopTransferDto> getOutList(WorkShopTransferDto workShopTransferDto) {
        String site = CommonMethods.getSite();
        String workCenter = workShopTransferDto.getWorkCenter();
        String transferWorkCenter = workShopTransferDto.getTransferWorkCenter();
        String operation = workShopTransferDto.getOperation();
        String status = workShopTransferDto.getStatus();
        return workShopTransferMapper.getOutList(site,workCenter,transferWorkCenter,null,operation,status,null, null);
    }
    @Override
    public List<WorkShopTransferDto> getInList(WorkShopTransferDto workShopTransferDto) {
        String site = CommonMethods.getSite();
        String workCenter = workShopTransferDto.getWorkCenter();
        String transferWorkCenter = workShopTransferDto.getTransferWorkCenter();
        String transferNo = workShopTransferDto.getTransferNo();
        String status = workShopTransferDto.getStatus();
        return workShopTransferMapper.getInList(site,workCenter,transferWorkCenter,transferNo,status,null);
    }



}