package com.sw.mes.yb.mcs.controller;

import com.sw.mes.base.factory.init.dto.SortingConfigDto;
import com.sw.mes.base.factory.init.dto.WarehouseDto;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.store.WarehouseInventoryBo;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.production.dto.FormulaSchemeDto;
import com.sw.mes.yb.mcs.dto.*;
import com.sw.mes.yb.mcs.dto.fillingMaterial.*;
import com.sw.mes.yb.mcs.dto.fillingMaterial.MoTrayBindingToMcs.MaterialPropertyDto;
import com.sw.mes.yb.mcs.entity.SegmentInspectionPassPointInfo;
import com.sw.mes.yb.mcs.service.YbMesToMcsService;
import com.sw.mes.yb.mcs.utils.ResultDto;
import com.sw.mes.yb.production.entity.AgainTask;
import com.sw.mes.yb.production.entity.AgainTaskDetail;
import com.sw.mes.yb.production.entity.AgainTaskPrepare.AgainTaskPrepare;
import com.sw.mes.yb.production.entity.LoadingTask;
import com.sw.mes.yb.production.service.AgainTaskDetailService;
import com.sw.mes.yb.production.service.AgainTaskPrepareService;
import com.sw.mes.yb.production.service.AgainTaskService;
import com.sw.mes.yb.production.service.LoadingTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: GaoXinJian
 * @Date: 2022-01-12 10:03
 */
@RestController
@RequestMapping("/mesToMcsController")
@Slf4j
@Api(description = "mes与mcs通信接口")
public class MesToMcsController {
    @Autowired
    YbMesToMcsService mesToMcsService;

    @Autowired
    private AgainTaskService againTaskService;
    @Autowired
    private LoadingTaskService loadingTaskService;

    @Autowired
    private AgainTaskDetailService againTaskDetailService;

    @Autowired
    private AgainTaskPrepareService againTaskPrepareService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    ModelMapper modelMapper;

    @ApiOperation(value = "圆棒托盘绑定接口")
    @PostMapping("/crystalTrayBindInfo")
    public Result crystalTrayBindInfo(@RequestBody CrystalTrayBindInfoDto crystalTrayBindInfoDto) {
        ResultDto resultDto = mesToMcsService.crystalTrayBindInfo(crystalTrayBindInfoDto);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }

     @ApiOperation(value = "圆棒托盘解绑接口")
    @PostMapping("/crystalTrayUnBindInfo")
    public Result crystalTrayUnBindInfo(@RequestBody CrystalTrayUnBindInfoDto crystalTrayUnBindInfoDto) {
        ResultDto resultDto = mesToMcsService.crystalTrayUnBindInfo(crystalTrayUnBindInfoDto);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }

    @ApiOperation(value = "圆棒评级结果下发")
    @PostMapping("/rankResult")
    public Result rankResult(@RequestBody RankResultDto rankResultDto) {
        ResultDto resultDto=mesToMcsService.rankResult(rankResultDto);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }

    @ApiOperation(value = "订单水位信息下发接口")
    @PostMapping("/orderConfig")
    public Result orderConfig(@RequestBody List<OrderConfigDto> orderConfigDtoList) {
        ResultDto resultDto=mesToMcsService.orderConfig(orderConfigDtoList);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }

    @ApiOperation(value = "拼棒绑定信息上传接口")
    @PostMapping("/spellBinding")
    public Result spellBinding(@RequestBody SpellBindingDto spellBindingDto) {
        ResultDto resultDto=mesToMcsService.spellBinding(spellBindingDto);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }

    @ApiOperation(value = "分选口规格配置信息下发接口")
    @PostMapping("/blankConfig")
    public Result blankConfig(@RequestBody List<BlankConfigDto> blankConfigDtoList) {
        for (BlankConfigDto blankConfigDto : blankConfigDtoList) {
            if (StringUtils.isNotBlank(blankConfigDto.getProductType())){
                String productType = mesToMcsService.productTypeConversion(blankConfigDto.getProductType());
                blankConfigDto.setProductType(productType);
            }else{
                blankConfigDto.setProductType("0");
            }
        }
        ResultDto resultDto=mesToMcsService.blankConfig(blankConfigDtoList);
        if (resultDto.getStatus() == 100) {
            return ResultGenerator.success(resultDto.getMessage(), resultDto.getData());
        } else {
            return ResultGenerator.message(Integer.valueOf(resultDto.getStatus()),resultDto.getMessage(),resultDto.getData());
        }
    }


    @ApiOperation(value = "分选口更新前校验是否允许修改")
    @PostMapping("/blankConfigUpdateCheck")
    public ResultDto blankConfigUpdateCheck(@RequestBody SortingConfigDto sortingConfigDto) {
        ResultDto resultDto = mesToMcsService.blankConfigForUpdateCheck(sortingConfigDto);
        return resultDto;
    }



    @ApiOperation(value = "晶棒绑定-人工单晶上线体,调用MCS")
    @PostMapping("/pdaBing")
    public Result pdaBing(@RequestBody PdaBingDto pdaBingDto) {
        return mesToMcsService.pdaBing(pdaBingDto);
    }

    @ApiOperation(value = "晶棒绑定-人工单晶上线体,调用MCS-方棒")
    @PostMapping("/pdaBingFb")
    public Result pdaBingFb(@RequestBody PdaBingDto pdaBingDto) {
        return mesToMcsService.pdaBingFb(pdaBingDto);
    }

    @ApiOperation(value = "晶棒绑定-人工单晶上线体,调用MCS")
    @PostMapping("/unPdaBing")
    public Result unPdaBing(@RequestBody PdaBingDto pdaBingDto) {
        return mesToMcsService.unPdaBing(pdaBingDto);
    }

    @ApiOperation(value = "晶棒绑定-人工单晶上线体,调用MCS-方棒")
    @PostMapping("/unPdaBingFb")
    public Result unPdaBingFb(@RequestBody PdaBingDto pdaBingDto) {
        return mesToMcsService.unPdaBingFb(pdaBingDto);
    }


    @ApiOperation(value = "更新库位载具")
    @PostMapping("/updateWarehouse")
    public Result updateWarehouse(@RequestBody WarehouseDto warehouseDto) {
        return mesToMcsService.updateWarehouse(warehouseDto);
    }

    @ApiOperation(value = "配方下发mcs")
    @PostMapping(value = "/formulaSchemeToMcs")
    public Result<FormulaSchemeToMesDto> formulaSchemeToMcs(@RequestParam Long formulaSchemeId) {
        try {
            return mesToMcsService.formulaSchemeToMcs(formulaSchemeId);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "生产任务下发mcs")
    @PostMapping(value = "/issueMoInterface")
    public Result<IssueMoToMcsDto> issueMoInterface(@RequestParam String type, @RequestParam Long id) {
        try {
            if(type.contains("复投")) {
                AgainTaskDetail task = againTaskDetailService.get(id);
                if(task!=null) {
                    return mesToMcsService.issueMoInterface(task);
                }
            }if(type.contains("预装料")) {
                AgainTaskPrepare task = againTaskPrepareService.get(id);
                if(task!=null) {
                    return mesToMcsService.issueMoInterface(task);
                }
            }else {
                LoadingTask task = loadingTaskService.get(id);
                if(task!=null) {
                    return mesToMcsService.issueMoInterface(task);
                }
            }
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
        return ResultGenerator.success();
    }


    @ApiOperation(value = "取消生产任务下发mcs")
    @PostMapping("/cancelMoDistributionInterface")
    public Result<List<CancelMoDistributionToMcsDto>> cancelMoDistributionInterface(String type, Long id) {
        try {
            if(type.contains("复投")) {
                AgainTask task = againTaskService.get(id);
                if(task!=null) {
                    return mesToMcsService.cancelMoDistributionInterface(task);
                }
            } else if(type.contains("罐料")){
                AgainTaskDetail task = againTaskDetailService.get(id);
                if(task!=null) {
                    return mesToMcsService.cancelMoDistributionInterface(task);
                }
            } else if(type.contains("预装料")){
                AgainTaskPrepare task = againTaskPrepareService.get(id);
                if(task!=null) {
                    return mesToMcsService.cancelMoDistributionInterface(task);
                }
            } else {
                LoadingTask task = loadingTaskService.get(id);
                if(task!=null) {
                    return mesToMcsService.cancelMoDistributionInterface(task);
                }
            }
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "装罐料原料托盘绑定接口")
    @PostMapping("/moTrayBinding")
    public Result moTrayBinding(@RequestBody MoTrayBindingDto dto) {
        try {
            return mesToMcsService.moTrayBinding(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "装罐料原料库位绑定接口")
    @PostMapping("/moWarehousingBinding")
    public Result moWarehousingBinding(@RequestBody MoWarehousingBindingDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }

        try {
            return mesToMcsService.moWarehousingBinding(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "扫描托号/物料箱号/批次号获取物料信息接口")
    @GetMapping("/getMaterialInfo")
    public Result getMaterialInfo(@ApiParam(value = "批次号", type = "query") @RequestParam(required = false, value = "batchNo") String batchNo,
                                  @ApiParam(value = "箱号", type = "query") @RequestParam(required = false, value = "serialNo") String serialNo,
                                  @ApiParam(value = "托号", type = "query") @RequestParam(required = false, value = "traceId") String traceId) {
        try {
            Result<List<WarehouseInventoryBo>> material = materialModelService.findMaterial(batchNo, serialNo, traceId);
            if(material == null || 200 != material.getCode()){
                return ResultGenerator.fail(material.getMessage());
            }
            if(material.getData() == null || material.getData().size() < 1) return ResultGenerator.fail("未查询到物料数据!");
            List<MaterialPropertyDto> dtos = material.getData().stream()
                    .map(entity -> toLazyDto(entity))
                    .collect(Collectors.toList());
            return ResultGenerator.success(dtos);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "晶裂免检")
    @PostMapping("/exemption")
    public Result exemption(@RequestBody PdaBingDto pdaBingDto) {
        return mesToMcsService.exemption(pdaBingDto);
    }

    public MaterialPropertyDto toLazyDto(WarehouseInventoryBo entity) {
        MaterialPropertyDto map = modelMapper.map(entity, MaterialPropertyDto.class);
        map.setMaterialBatch(entity.getBatchNo());
        map.setMaterialNo(entity.getMaterialModelCode());
        map.setCount(entity.getQuantity());
        map.setMaterialName(entity.getMaterialModelName());
        map.setMaterialType(entity.getMaterialTypeName());
        map.setUnit(entity.getUnitName());
        map.setWarehouseName(entity.getWarehouseName());
        map.setWarehouseCode(entity.getWarehouseCode());
        // 物料主数据
        MaterialModel materialModel = materialModelService.findByCode(entity.getMaterialModelCode());
        if(materialModel != null){
            map.setDirectional(materialModel.getDirectionalSign());
        }
        return map;
    }
}