package com.sw.mes.sectionMes.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.dto.*;
import com.sw.mes.core.dto.sectionMes.FbInformationReceptionDto;
import com.sw.mes.core.response.Result;
import com.sw.mes.sectionMes.dto.FeedBackPassBackDto;
import com.sw.mes.sectionMes.entity.LogSectionMesInteractive;
import com.sw.mes.sectionMes.service.LogSectionMesInteractiveService;
import com.sw.mes.sectionMes.service.MESInputService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author lf
 * @description
 * @date 2024/2/2 9:02
 */
@Service
public class MESInputServiceImpl implements MESInputService {

    @Autowired
    private LogSectionMesInteractiveService logSectionMesInteractiveService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public FeedBackPassBackDto feedBackPassBack(JSONObject data) {
        Assert.notNull(data, "反馈信息不能为空");
        FeedBackPassBackDto dto = new FeedBackPassBackDto();
        FbInformationReceptionDto fbInformationReceptionDto = JSON.parseObject(String.valueOf(data), FbInformationReceptionDto.class);
        String trayId = fbInformationReceptionDto.getTrayId();
        String state = fbInformationReceptionDto.getState();
        String siliconRodNo = fbInformationReceptionDto.getSiliconRodNo();
        if (null == trayId) {
            throw new RuntimeException("托盘号不能为空");
        }
        if (null == state) {
            throw new RuntimeException("状态不能为空");
        }
        if (null==siliconRodNo){
            throw new RuntimeException("方棒晶编不能为空");
        }
        ArrayList<SectionMesToFbReceiveDto> sectionMesToFbReceiveDtoArrayList = new ArrayList<>();
        SectionMesToFbReceiveDto sectionMesToFbReceiveDto = new SectionMesToFbReceiveDto();
        sectionMesToFbReceiveDto.setTrayId(trayId);
        sectionMesToFbReceiveDto.setState(state);
        sectionMesToFbReceiveDto.setFeedBackPassBackInfo(JSON.toJSONString(fbInformationReceptionDto));
        sectionMesToFbReceiveDto.setSectionNo(siliconRodNo);
        sectionMesToFbReceiveDtoArrayList.add(sectionMesToFbReceiveDto);
        Result result = null;
        try {
            result = fbFeignClients.fbSectionMesReceive(sectionMesToFbReceiveDtoArrayList);
            if (result.getCode() != 200) {
                throw new RuntimeException("方棒切片mes接收接口失败" + objectMapper.writeValueAsString(result));
            }
            dto.setState("S");
            //保存交互记录
            saveInteractiveLog("切片MES->拉晶MES", "方棒反馈回传接口", "feedBackPassBack", data, JSON.toJSONString(dto));
        } catch (Exception e) {
            //保存交互记录
            saveInteractiveLog("切片MES->拉晶MES", "方棒反馈回传接口", "feedBackPassBack", data, result);
            throw new RuntimeException(e);
        }
        return dto;
    }

    @Override
    public void returnMaterial(JSONObject data) {
        Assert.notNull(data, "退料信息不能为空");
        JSONObject tInputItem = data.getJSONObject("T_INPUT");
        JSONArray item = tInputItem.getJSONArray("item");
//        退库复检主表
        RecheckInspectReceiveDto recheckInspectReceiveDto = new RecheckInspectReceiveDto();
        recheckInspectReceiveDto.setSource("切片mes");
        recheckInspectReceiveDto.setUser("切片mes");
        recheckInspectReceiveDto.setApplyTime(new Date());
        recheckInspectReceiveDto.setIsRecheck(1);
        recheckInspectReceiveDto.setCrystalNum(item.size());
        recheckInspectReceiveDto.setSectionMesReturnResult(JSON.toJSONString(data));

        //        退库复检明细表
        ArrayList<RecheckInspectReceiveDetailDto> receiveDetailDtoArrayList = new ArrayList<>();
        for (int i = 0; i < item.size(); i++) {
            JSONObject jsonObject = item.getJSONObject(i);
            recheckInspectReceiveDto.setTrayNo(jsonObject.getString("TRAYID"));
            RecheckInspectReceiveDetailDto recheckInspectReceiveDetailDto = new RecheckInspectReceiveDetailDto();
            recheckInspectReceiveDetailDto.setTrayNo(jsonObject.getString("TRAYID"));
            recheckInspectReceiveDetailDto.setCrystalNo(jsonObject.getString("SILICONRODNO"));
            recheckInspectReceiveDetailDto.setConfirmTime(new Date());
            recheckInspectReceiveDetailDto.setState(0);
            recheckInspectReceiveDetailDto.setWarehouseCode(jsonObject.getString("LGORT_FROM"));
            receiveDetailDtoArrayList.add(recheckInspectReceiveDetailDto);
        }

        RecheckInspectReceivePostDto dto = new RecheckInspectReceivePostDto();
        dto.setReceive(recheckInspectReceiveDto);
        dto.setDetailList(receiveDetailDtoArrayList);
        Result result = null;
        try {
            result = fbFeignClients.sectionMesReturnInspection(dto);
            if (result.getCode() != 200) {
                throw new RuntimeException("调用方棒新增退库复检接收接口失败" + result);
            }
            //保存交互记录
            saveInteractiveLog("切片MES->拉晶MES", "方棒退料", "returnMaterial", data, "退料成功");
        } catch (RuntimeException e) {
            //保存交互记录
            saveInteractiveLog("切片MES->拉晶MES", "方棒退料", "returnMaterial", data, result);
            throw new RuntimeException(e);
        }
    }

    // 保存原始记录到数据表
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveInteractiveLog(String direction, String controllerName, String oprMethod, Object data, Object result) {
        LogSectionMesInteractive log = new LogSectionMesInteractive();
        log.setDataDirection(direction);
        log.setControllerName(controllerName);
        log.setOprMethod(oprMethod);
        log.setContext(JSONObject.toJSONString(data));
        log.setReturnContext(JSONObject.toJSONString(result));
        log.setCreateTime(new Date());
        logSectionMesInteractiveService.saveOrUpdate(log);
    }
}
