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

import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.enumvalue.EnumValuesAgv;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.yb.agv.dto.AgvCallDto;
import com.sw.mes.yb.fls.dto.*;
import com.sw.mes.yb.fls.entity.RecycledWaitRecord;
import com.sw.mes.yb.fls.service.MesToFlsService;
import com.sw.mes.yb.fls.utils.FlsResultDto;
import com.sw.mes.yb.fls.utils.ResultDto;
import com.sw.mes.yb.mcs.service.YbMesToMcsService;
import com.sw.mes.yb.pad.service.RecycledWaitRecordService;
import com.sw.mes.yb.production.dto.RecycledMaterialManageDetailDto;
import com.sw.mes.yb.turnstore.dao.ProductionBindingTrayLogDao;
import com.sw.mes.yb.turnstore.entity.ProductionBindingTrayLog;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayLogService;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: GaoXinJian
 * @Date: 2022-02-16 12:26
 */
@RestController
@Api(description = "Mes调用Fls接口")
@RequestMapping("/mesToFlsController")
public class MesToFlsController {
    @Autowired
    MesToFlsService mesToFlsService;

    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;
    @Autowired
    private ProductionBindingTrayLogDao productionBindingTrayLogDao;
    @Autowired
    private RecycledWaitRecordService recycledWaitRecordService;

    @Autowired
    private YbMesToMcsService ybMesToMcsService;

    @ApiOperation(value = "更新KfReturnMaterial")
    @PostMapping("/update")
    public Result callAgv() {
//        try {
//            Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
//            String targetPoint = EnumValuesAgv.EquipmentAreaBLHCK.getText(equipment.getArea());
//
//            AgvCallDto agvCall = new AgvCallDto();
//            agvCall.setKeyword(EnumValuesAgv.AGVKeyword.开方自动退料.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
//            agvCall.setStartPoint(dto.getEquipmentCode()); //起始位置编号  - 当前传入机台号
//            agvCall.setTargetPoint(targetPoint);//结束工作位
//            //其他信息可根据配置信息自动填充
//            String taskCode = agvDispatchService.callAgv(agvCall);
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
        return null;
    }

    //AGV到点后托盘位置解绑
    @ApiOperation(value = "AGV到点后托位解绑")
    @PostMapping("/unbindLandmarkCode")
    public Result unbindBracketNo(@RequestBody BracketNoRequestDto bracketNoRequestDto) {
        //AGV拉至到点后，MES操作PDA托盘解绑
        try {
            bracketNoRequestDto.setMode("posUnbinding");
            FlsResultDto resultDto = mesToFlsService.unbindBracketNo(bracketNoRequestDto);
            if (resultDto == null || resultDto.getCode() == null || resultDto.getCode() != 0) {
                throw new RuntimeException("通知fls解绑地标码:" + bracketNoRequestDto.getLandmarkCode() + "失败" + resultDto.getMessage());
            }
            return ResultGenerator.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "pda头尾料/样片装车呼叫AGV信息上传FLS")
    @PostMapping(value = "/recycledMaterialToAGV")
    public Result recycledMaterialToAGV(@RequestBody @Valid List<RecycledMaterialToAGVDto> recycledMaterialToAGVDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            String pailNum = recycledMaterialToAGVDto.get(0).getPailNum();
            //1 查询最新数据,校验载具车是否是未解绑
            ProductionBindingTrayLog firstData = productionBindingTrayLogDao.getFirstData(pailNum);
            if (null != firstData && null != firstData.getIsBinding() && 2 != firstData.getIsBinding()) {
                return ResultGenerator.fail("载具车未解绑,请先解绑:" + firstData.getTrayNo() + "与:[" + firstData.getCrystalNo() + "]的关系");
            }
            // 2 校验产品类型是否相同
            List<String> collect = recycledMaterialToAGVDto.stream().map(RecycledMaterialToAGVDto::getMaterialType).distinct().collect(Collectors.toList());
            if (collect.size() != 1) {
                return ResultGenerator.fail("物料的产品类别不同,请校验数据");
            }
            RecycledMaterialToAGVDtos recycledMaterialToAGVDtos = new RecycledMaterialToAGVDtos();
            recycledMaterialToAGVDtos.setRecycledMaterialToAGVDtoList(recycledMaterialToAGVDto);
            recycledMaterialToAGVDtos.setMode("getRecycledInfo");
            FlsResultDto resultDto = mesToFlsService.recycledMaterialToAGV(recycledMaterialToAGVDtos);
            if (resultDto == null || resultDto.getCode() == null || resultDto.getCode() != 0) {
                throw new RuntimeException("发送回收料并通知fls呼叫AGV失败:" + resultDto.getMessage());
            } else {
                //3 fls接收数据成功后, 与产品讨论使用车号作为托盘号,车号也替代单晶号做为伪单晶 ,进行绑定,做日志记录
                productionBindingTrayService.bindingRecycledPailNum(pailNum);
                //4 记录已发送的数据
                List<RecycledWaitRecord> recycledWaitRecords = new ArrayList<>();
                for (RecycledMaterialToAGVDto materialToAGVDto : recycledMaterialToAGVDto) {
                    RecycledWaitRecord recycledWaitRecord = new RecycledWaitRecord();
                    recycledWaitRecord.setCreateUser("PDA")
                            .setCreateTime(new Date())
                            .setMaterialType(materialToAGVDto.getMaterialType())
                            .setSectionNo(materialToAGVDto.getSectionNo())
                            .setPailNum(materialToAGVDto.getPailNum())
                            .setLocationNo(materialToAGVDto.getLocationNo())
                            .setLandmarkCode(materialToAGVDto.getLandmarkCode())
                            .setStatus(1);
                    recycledWaitRecords.add(recycledWaitRecord);
                }
                recycledWaitRecordService.saveAll(recycledWaitRecords);
            }
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
        return ResultGenerator.success();
    }




    /**
     * 新接口，改造自上面接口，业务逻辑不同，当前需要与mcs通信两次
     * @param recycledMaterialToAGVDto
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "pda头尾料/样片装车,信息上传MCS,呼叫AGV")
    @PostMapping(value = "/recycledMaterialToMcsAndAGV")
    public Result recycledMaterialToMcsAndAGV(@RequestBody @Valid List<RecycledMaterialToAGVDto> recycledMaterialToAGVDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return ybMesToMcsService.recycledMaterialToMcsAndAGV(recycledMaterialToAGVDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }




    @ApiOperation(value = "MES手动下发单晶编号、托位号、回收料分类名称到fls")
    @PostMapping("/sendBracketNoInfo")
    public Result sendSectionForInfo(@RequestBody BracketNoToFlsDto bracketNoToFlsDto) {
        try {
            bracketNoToFlsDto.setMode("HeadTailInfoDownLoad");
            FlsResultDto resultDto = mesToFlsService.sendSectionForInfo(bracketNoToFlsDto);
            if (resultDto == null || resultDto.getCode() == null || resultDto.getCode() != 0) {
                throw new RuntimeException("发送回收料点位到fls失败:" + resultDto.getMessage());
            } else {
                return ResultGenerator.success();
            }
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }
}
