package com.ximai.mes.report.service.impl;

import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.constant.TaskStatusEnum;
import com.ximai.mes.constant.WorkorderStatusEnum;
import com.ximai.mes.pro.domain.ProFeedback;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.task.ProTask;
import com.ximai.mes.pro.domain.task.ProTaskWorkunit;
import com.ximai.mes.pro.domain.vo.WorkorderFirstUnfinishedProcessVo;
import com.ximai.mes.pro.mapper.ProFeedbackMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.mapper.task.ProTaskMapper;
import com.ximai.mes.pro.mapper.task.ProTaskWorkunitMapper;
import com.ximai.mes.report.request.WorkOrderProgressRequest;
import com.ximai.mes.report.response.WorkOrderProgressFeedbackListResponse;
import com.ximai.mes.report.response.WorkOrderProgressListResponse;
import com.ximai.mes.report.response.WorkOrderProgressProcessListResponse;
import com.ximai.mes.report.service.WorkOrderProgressService;
import com.ximai.system.service.ISysDictDataService;
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.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WorkOrderProgressServiceImp implements WorkOrderProgressService {
    @Autowired
    ProWorkorderMapper proWorkorderMapper;

    @Autowired
    private ProTaskMapper proTaskMapper;
    @Autowired
    private ProFeedbackMapper proFeedbackMapper;
    @Autowired
    ProTaskWorkunitMapper proTaskWorkunitMapper;
    @Override
    @Transactional
    public List<WorkOrderProgressListResponse> getList(WorkOrderProgressRequest workOrderProgressRequest) {
        List<WorkOrderProgressListResponse>  workOrderProgressListResponses = proWorkorderMapper.getWorkOrderProgressServiceList(workOrderProgressRequest);
        for (WorkOrderProgressListResponse workOrderProgressListResponse : workOrderProgressListResponses){
            if(workOrderProgressListResponse.getQuantity() != null && workOrderProgressListResponse.getQuantity().compareTo(BigDecimal.ZERO) >0){
                workOrderProgressListResponse.setQuantityProduced(workOrderProgressListResponse.getQuantityProduced() != null ? workOrderProgressListResponse.getQuantityProduced() : BigDecimal.ZERO);
                if(workOrderProgressListResponse.getQuantity().compareTo(workOrderProgressListResponse.getQuantityProduced()) > 0){
                    workOrderProgressListResponse.setQuantityMu(workOrderProgressListResponse.getQuantityProduced().multiply(new BigDecimal(100)).divide(workOrderProgressListResponse.getQuantity(),2, RoundingMode.HALF_UP));
                }else{
                    workOrderProgressListResponse.setQuantityMu(new BigDecimal(100));

                }
            }else{
                workOrderProgressListResponse.setQuantityMu(new BigDecimal(100));

            }
        }
        fillFirstUnfinishedProcessName(workOrderProgressListResponses);
        return workOrderProgressListResponses;
    }

    /**
     * 生产中工单填充首道未完成工序名（与工序明细状态判定一致）
     */
    private void fillFirstUnfinishedProcessName(List<WorkOrderProgressListResponse> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<String> producingCodes = list.stream()
                .filter(r -> WorkorderStatusEnum.PRODUCING.getValue().equals(r.getStatus()))
                .map(WorkOrderProgressListResponse::getWorkorderCode)
                .filter(StringUtils::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        if (producingCodes.isEmpty()) {
            return;
        }
        List<WorkorderFirstUnfinishedProcessVo> rows = proTaskMapper.selectFirstUnfinishedProcessNameByWorkorderCodes(producingCodes);
        Map<String, String> nameMap = rows.stream().collect(Collectors.toMap(
                vo -> progressRowKey(vo.getWorkorderCode(), vo.getTaskBatch()),
                WorkorderFirstUnfinishedProcessVo::getFirstUnfinishedProcessName,
                (a, b) -> a));
        for (WorkOrderProgressListResponse item : list) {
            if (WorkorderStatusEnum.PRODUCING.getValue().equals(item.getStatus())) {
                item.setFirstUnfinishedProcessName(nameMap.get(progressRowKey(item.getWorkorderCode(), item.getTaskBatch())));
            }
        }
    }

    private static String progressRowKey(String workorderCode, String taskBatch) {
        return workorderCode + "|" + (taskBatch != null ? taskBatch : "");
    }

    @Override
    public List<WorkOrderProgressProcessListResponse> getProcessList(String workorderCode, String taskBatch) {
        List<WorkOrderProgressProcessListResponse> workOrderProgressProcessListResponses =
                proTaskMapper.getProcessList(workorderCode, taskBatch);
        for (WorkOrderProgressProcessListResponse workOrderProgressProcessListResponse : workOrderProgressProcessListResponses){
//            if(workOrderProgressProcessListResponse.getStatus().equals(TaskStatusEnum.BEGINNING.getStatus())){
//                workOrderProgressProcessListResponse.setStatus("加工中");
//            }else if(workOrderProgressProcessListResponse.getStatus().equals(TaskStatusEnum.FINISHED.getStatus())){
//                workOrderProgressProcessListResponse.setStatus("已完工");
//            }else if(workOrderProgressProcessListResponse.getStatus().equals(TaskStatusEnum.PAUSE.getStatus())){
//                workOrderProgressProcessListResponse.setStatus("暂停");
//            }else if(workOrderProgressProcessListResponse.getStatus().equals(TaskStatusEnum.PREPARE.getStatus())){
//                workOrderProgressProcessListResponse.setStatus("未开工");
//            }else if(workOrderProgressProcessListResponse.getStatus().equals(TaskStatusEnum.ERROR_STOP.getStatus())){
//                workOrderProgressProcessListResponse.setStatus("故障停工");
//            }
            ProTaskWorkunit proTaskWorkunitQuery = new ProTaskWorkunit();
            proTaskWorkunitQuery.setTaskId(workOrderProgressProcessListResponse.getTaskId());
            List<ProTaskWorkunit> proTaskWorkunitList = proTaskWorkunitMapper.selectProTaskWorkunitList(proTaskWorkunitQuery);
            if(proTaskWorkunitList.size() > 0){
                if(proTaskWorkunitList.stream()
                        .filter(proTaskWorkunit -> proTaskWorkunit.getStatus().equals(TaskStatusEnum.FINISHED.getStatus())).count() == proTaskWorkunitList.size() ){
                    //下面的所有派工表任务都完工时,标记为完工
                    workOrderProgressProcessListResponse.setStatus("已完工");
                }else if(proTaskWorkunitList.stream()
                        .filter(proTaskWorkunit -> proTaskWorkunit.getStatus().equals(TaskStatusEnum.ERROR_STOP.getStatus())).count() > 0 ){
                    //下面的所有派工表任务存在有任何一条故障时,标记为故障停工
                    workOrderProgressProcessListResponse.setStatus("故障停工");
                }else if(proTaskWorkunitList.stream()
                        .filter(proTaskWorkunit -> proTaskWorkunit.getStatus().equals(TaskStatusEnum.PREPARE.getStatus())).count() == proTaskWorkunitList.size() ){
                    //下面的所有派工表任务都未开工时,标记为未开工
                    workOrderProgressProcessListResponse.setStatus("未开工");
                }else{
                    //其他加工中
                    workOrderProgressProcessListResponse.setStatus("加工中");
                }
            }else{
                workOrderProgressProcessListResponse.setStatus("未开工");
            }

            if(workOrderProgressProcessListResponse.getQuantityProduced() != null && workOrderProgressProcessListResponse.getQuantityProduced().compareTo(BigDecimal.ZERO) > 0){
                if(workOrderProgressProcessListResponse.getQuantityProduced().compareTo(workOrderProgressProcessListResponse.getQuantityQualify()) > 0){
                    workOrderProgressProcessListResponse.setPassRate(workOrderProgressProcessListResponse.getQuantityQualify().multiply(new BigDecimal(100)).
                            divide(workOrderProgressProcessListResponse.getQuantityProduced(),2, RoundingMode.HALF_UP));
                }else{
                    workOrderProgressProcessListResponse.setPassRate(new BigDecimal(100));
                }
            }else{
                workOrderProgressProcessListResponse.setPassRate(BigDecimal.ZERO);
            }
        }
        return workOrderProgressProcessListResponses;
    }

    @Override
    public List<WorkOrderProgressFeedbackListResponse> getFeedbackList(String workorderCode,Long taskId,Long taskWorkunitId) {
        List<WorkOrderProgressFeedbackListResponse>  workOrderProgressFeedbackListResponses = proFeedbackMapper.getFeedbackList( workorderCode,taskId,taskWorkunitId);
        return workOrderProgressFeedbackListResponses;
    }
}
