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.FbTurnstoreTrayItemDto;
import com.sw.mes.core.dto.sectionMes.FbInformationReceptionDto;
import com.sw.mes.core.dto.sectionMes.ReturnMaterialFeedBackDto;
import com.sw.mes.core.response.Result;
import com.sw.mes.jip.entity.JipHeaderConfig;
import com.sw.mes.jip.enums.IFKeyWordEnums;
import com.sw.mes.jip.service.JipHeaderConfigService;
import com.sw.mes.sectionMes.entity.LogSectionMesInteractive;
import com.sw.mes.sectionMes.service.LogSectionMesInteractiveService;
import com.sw.mes.sectionMes.service.MESOutputService;
import com.sw.mes.sto.dto.StoDto;
import com.sw.mes.sto.dto.StoItemDto;
import com.sw.mes.sto.service.StoOutputService;
import com.sw.mes.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

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

/**
 * @author lf
 * @description
 * @date 2024/2/1 9:41
 */
@Service
@Slf4j
public class MESOutputServiceImpl implements MESOutputService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JipHeaderConfigService jipHeaderConfigService;

    @Autowired
    private LogSectionMesInteractiveService logSectionMesInteractiveService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StoOutputService stoOutputService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Override
    public void fbInformationReception(List<FbInformationReceptionDto> data) {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.FBINFORMATIONRECEPTION.getKeyword());

        if (null == jipHeaderConfig) {
            throw new RuntimeException("MES中未配置方棒信息接收接口信息");
        }
        if (StringUtils.isBlank(jipHeaderConfig.getUrl())) {
            throw new RuntimeException("MES中未配置方棒信息接收接口URL请求地址");
        }
        String dataJson = JSON.toJSONString(data);

        //2.发送方棒信息接收到切片MES
        JSONObject result;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(dataJson, headers);
            ResponseEntity<JSONObject> response = restTemplate.exchange(jipHeaderConfig.getUrl(), HttpMethod.POST, request, JSONObject.class);
            result = response.getBody();
            //保存交互记录
            saveInteractiveLog("拉晶MES->切片MES", "方棒信息接收接口", "fbInformationReception", dataJson, result);
            System.out.println(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            log.error("error_in_fbInformationReception", e);
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void returnMaterialFeedBack(List<ReturnMaterialFeedBackDto> data) {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.FBRETURNMATERIALFEEDBACK.getKeyword());
        JipHeaderConfig sto = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.STO.getKeyword());

        if (null == jipHeaderConfig) {
            throw new RuntimeException("MES中未配置方棒退料反馈接口信息");
        }
        if (StringUtils.isBlank(jipHeaderConfig.getUrl())) {
            throw new RuntimeException("MES中未配置方棒退料反馈接口URL请求地址");
        }

        if (null == sto) {
            throw new RuntimeException("MES中未配置Sto接口信息");
        }
        if (StringUtils.isBlank(sto.getUrl())) {
            throw new RuntimeException("MES中未配置Sto接口URL请求地址");
        }
        String dataJson = JSON.toJSONString(data);
        JSONObject result = null;
        //2.发送方棒退料反馈信息到sto
        ArrayList<StoDto> stoDtoArrayList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(data) && "S".equals(data.get(0).getState())) {
            try {
                StoDto stoDto = new StoDto();
                String sectionMesReturnResult = data.get(0).getSectionMesReturnResult();
                JSONObject jsonObject = objectMapper.readValue(sectionMesReturnResult, JSONObject.class);
                JSONObject tInput = jsonObject.getJSONObject("T_INPUT");
                String zbonded = tInput.getString("ZBONDED");
                String zsfdx = tInput.getString("ZSFDX");
                stoDto.setZbonded(zbonded);
                stoDto.setZsfdx(zsfdx);

                ArrayList<StoItemDto> stoItemDtoArrayList = new ArrayList<>();
                JSONArray item = tInput.getJSONArray("item");
                for (ReturnMaterialFeedBackDto dto : data) {
                    Result<FbTurnstoreTrayItemDto> fbTurnstoreTrayItemDtoResult = fbFeignClients.findBySectionNo(dto.getSiliconRodNo());
                    if (fbTurnstoreTrayItemDtoResult.getCode()==200){
                        FbTurnstoreTrayItemDto turnstoreTrayItemDto = fbTurnstoreTrayItemDtoResult.getData();
                        JSONObject jsonObject1 = item.getJSONObject(0);
                        StoItemDto stoItemDto = new StoItemDto();
                        stoItemDto.setWerksFrom(jsonObject1.getString("WERKS_FROM"));
                        stoItemDto.setLgortFrom(jsonObject1.getString("LGORT_FROM"));
                        stoItemDto.setWerksTo(jsonObject1.getString("WERKS_TO"));
                        stoItemDto.setLgortTo(jsonObject1.getString("LGORT_TO"));
                        stoItemDto.setRowId(jsonObject1.getString("ROW_ID"));
                        stoItemDto.setMeins(jsonObject1.getString("MEINS"));
                        stoItemDto.setCharg(turnstoreTrayItemDto.getBatchNo());
                        stoItemDto.setMenge(String.valueOf(turnstoreTrayItemDto.getTheoryWeightFb()));
                        stoItemDto.setMatnr(turnstoreTrayItemDto.getMaterialNumber());
                        stoItemDtoArrayList.add(stoItemDto);
                    }
                }
                stoDto.setItems(stoItemDtoArrayList);
                stoDtoArrayList.add(stoDto);
                stoOutputService.sendData(stoDtoArrayList);
                saveInteractiveLog("拉晶MES->sto", "切片退货确认接收做sto", "sendData", JSON.toJSONString(stoDtoArrayList), "成功");
            } catch (Exception e) {
                saveInteractiveLog("拉晶MES->sto", "切片退货确认接收做sto", "sendData", JSON.toJSONString(stoDtoArrayList), e);
                throw new RuntimeException(e);
            }
        }
        //2.发送方棒退料反馈信息到切片MES
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(dataJson, headers);
            ResponseEntity<JSONObject> response = restTemplate.exchange(jipHeaderConfig.getUrl(), HttpMethod.POST, request, JSONObject.class);
            result = response.getBody();
            //保存交互记录
            saveInteractiveLog("拉晶MES->切片MES", "方棒退料反馈接口", "returnMaterialFeedBack", dataJson, result);
        } catch (Exception e) {
            e.printStackTrace();
            saveInteractiveLog("拉晶MES->切片MES", "方棒退料反馈接口", "returnMaterialFeedBack", dataJson, result);
            throw new RuntimeException(e.getMessage());
        }
    }

    // 保存原始记录到数据表
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveInteractiveLog(String direction, String controllerName, String oprMethod, Object data, Object result) {
        try {
            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);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
