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

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.wms.dto.SquareResultDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.*;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.annotation.ServiceLogs;
import com.sw.mes.fb.checkout.dto.PointDto;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fls.dto.ProductAssemblyConfigDto;
import com.sw.mes.mcs.dto.*;
import com.sw.mes.mcs.service.MesToMcsService;
import com.sw.mes.mcs.utils.RequestDto;
import com.sw.mes.mcs.utils.RequestUtils;
import com.sw.mes.mcs.utils.ResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: GaoXinJian
 * @Date: 2022-01-12 13:55
 */
@Service
@Transactional
public class MesToMcsServiceImpl implements MesToMcsService {
    @Autowired
    RequestUtils requestUtils;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    @Lazy
    private FbCheckOutDataService fbCheckOutDataService;

    @Value("${spring.mcsServiceUrl}")
    private String mcsServiceUrl;

    private final String squareBindingUrl = "/MCS_SERVER_MES/mcs/mes/state/squareBinding";
    private final String squareRankUrl = "/auto/mesToMcsController/squareRank";
    private final String squareRankUrl1 = "/wms/mesToWmsController/squareRank";
    private final String getFbSectionNo = "/auto/mesToMcsController/getSNInfoWithIP";
    private final String sendFbSectionAndIp = "/auto/mesToMcsController/pushSNInfoWithIP";
    private final String productAssemblyConfigOutUrl = "";
    private final String gainTrayNoUrl = "/mcs/mes/getRfidInfoByIp";
    // 不检测下发mcs
//    private final String noDetectionUrl = "/MK/WMS/horizontalStoreroom/matchingCutInf";

    @Override
    @ServiceLogs(description = "方棒托盘绑定推送mcs")
    public ResultDto squareBinding(SquareBindingDto squareBindingDto) {
        return requestUtils.postForMcs(new RequestDto(squareBindingUrl, squareBindingDto));
    }

    @Override
    @ServiceLogs(description = "方棒评级下发mcs")
    public ResultDto squareRank(SquareRankDto squareRankDto) {
        return postResultDto(squareRankDto, squareRankUrl);
//        return requestUtils.postForMcs(new RequestDto(squareRankUrl,squareRankDto));
    }

    @Override
    @ServiceLogs(description = "新方棒评级下发mcs")
    @Async
    public Result squareRankResultMcs(SquareResultDto squareResultDto) {
        String url = mcsServiceUrl+squareRankUrl;
        String result = sendData(squareResultDto, url);
        return ResultGenerator.success(result);
    }

    @Override
    @ServiceLogs(description = "新方棒评级下发wms")
    @Async
    public Result squareRankResultWms(SquareResultDto squareResultDto) {
        String url = mcsServiceUrl+squareRankUrl1;
        String result = sendData(squareResultDto, url);
        return ResultGenerator.success(result);
    }

    private String sendData(SquareResultDto squareResultDto,String url) {
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Authorization", "token_admin");
        HttpEntity httpEntity = new HttpEntity<>(squareResultDto, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        String body = responseEntity.getBody();
        return body;
    }


    @Override
    @ServiceLogs(description = "方棒评级下发wms")
    public ResultDto squareRank1(SquareRankDto squareRankDto) {
        return postResultDto(squareRankDto, squareRankUrl1);
//        return requestUtils.postForMcs(new RequestDto(squareRankUrl1,squareRankDto));
    }

    public ResultDto postResultDto(SquareRankDto squareRankDto, String squareRankUrl) {
        String resultJson = null;
        ResultDto resultDto = new ResultDto();
        try {
            Integer i = 3;
            for (Integer integer = 0; integer < i; integer++) {
                //查方棒检验数据
                FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(squareRankDto.getSectionNo());

                HttpHeaders headers = new HttpHeaders();
                MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(mediaType);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                headers.add("Authorization", "token_admin");
                HttpEntity<FbCheckOutData> httpEntity = new HttpEntity<>(fbCheckOutData, headers);
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(mcsServiceUrl+squareRankUrl, httpEntity, String.class);
                resultJson = responseEntity.getBody();
                JSONObject jsonObject = JSONObject.parseObject(resultJson);
                String s = jsonObject.get("status").toString();
                String s1 = null;
                if(jsonObject.containsKey("code")){
                    s1 = jsonObject.get("code").toString();
                }
                if(s.equals("100") && squareRankUrl.contains(squareRankUrl)){
//                String s1 = jsonObject.get("result").toString();
//                JSONObject jsonObject1 = JSONObject.parseObject(s1);
//                String s2 = jsonObject1.get("sn").toString();
                    resultDto.setData(jsonObject);
                    resultDto.setStatus(200);
                    break;
//                    return resultDto;
                } else if(s1.equals("200") && squareRankUrl.contains(squareRankUrl1)){
                    resultDto.setData(jsonObject);
                    resultDto.setStatus(200);
                    break;
//                    return resultDto;
                } else {
//                    break;
                    throw new RuntimeException(resultJson);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultDto.setMessage(JSONObject.toJSONString(resultJson));
//            throw new RuntimeException(e.getMessage());
        }
        return resultDto;
    }

    @Override
    @ServiceLogs(description = "通过点位获取方棒编号")
    public ResultDto getFbSectionNo(PointDto pointDto) {
//        return requestUtils.postForMcs(new RequestDto(getFbSectionNo,pointDto));

        String resultJson;
        ResultDto resultDto = new ResultDto();
        try {
            HttpHeaders headers = new HttpHeaders();
            org.springframework.http.MediaType mediaType = org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(mediaType);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            headers.add("Authorization", "token_admin");
            HttpEntity<PointDto> httpEntity = new HttpEntity<>(pointDto, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(mcsServiceUrl+getFbSectionNo, httpEntity, String.class);
            resultJson = responseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            String s = jsonObject.get("code").toString();
            if(s.equals("200")){
                String s1 = jsonObject.get("result").toString();
                JSONObject jsonObject1 = JSONObject.parseObject(s1);
                String s2 = jsonObject1.get("sn").toString();
                resultDto.setData(s2);
                resultDto.setStatus(200);
                return resultDto;
            } else {
                throw new RuntimeException("当前点位未查询到方棒编号");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("当前点位未查询到方棒编号");
        }
    }

    @Override
    @ServiceLogs(description = "提交检验数据是发送编号及点位")
    public ResultDto sendFbSectionAndIp(PointDto pointDto) {
//        return requestUtils.postForMcs(new RequestDto(sendFbSectionAndIp,pointDto));

        String resultJson;
        ResultDto resultDto = new ResultDto();
        try {
            HttpHeaders headers = new HttpHeaders();
            org.springframework.http.MediaType mediaType = org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(mediaType);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            headers.add("Authorization", "token_admin");
            HttpEntity<PointDto> httpEntity = new HttpEntity<>(pointDto, headers);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(mcsServiceUrl + sendFbSectionAndIp, httpEntity, String.class);
            resultJson = stringResponseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            String s = jsonObject.get("code").toString();
            if(s.equals("200")){
                resultDto.setData(resultJson);
                resultDto.setStatus(200);
            } else {
                resultDto.setMessage(resultJson);
                resultDto.setStatus(400);
            }
            return resultDto;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("当前点位未查询到方棒编号");
        }
    }

    @Override
    public ResultDto productAssemblyConfigOut(ProductAssemblyConfigDto productAssemblyConfigDto) {
        return requestUtils.postForMcs(new RequestDto(productAssemblyConfigOutUrl, productAssemblyConfigDto));
    }

    @Override
    public GainTrayNoResultDto gainTrayNo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new BusinessException("获取请求失败！");
        }
        String remoteAddr = IpUtils.getRemoteAddr(attributes.getRequest());
        if (remoteAddr == null || "unknown".equals(remoteAddr)) {
            throw new BusinessException("获取ip失败！");
        }

        GainTrayNoDto gainTrayNoDto = new GainTrayNoDto();
        gainTrayNoDto.setTime(new Date());
        gainTrayNoDto.setIp(remoteAddr);
        ResultDto resultDto = requestUtils.postForMcs(new RequestDto(gainTrayNoUrl, gainTrayNoDto));
        if (resultDto == null || resultDto.getStatus() == null || resultDto.getStatus() != 100) {
            throw new BusinessException("[" + remoteAddr + "]获取托盘信息异常！" + resultDto == null ? null : resultDto.getMessage());
        }

        GainTrayNoResultDto resultDto1 = JSONObject.parseObject(resultDto.getData().toString(), GainTrayNoResultDto.class);
        return resultDto1;
    }

    @Override
    public ResultDto noDetection(NoDetectionDto noDetectionDto) {
//        String fbSectionNo = noDetectionDto.getFbSectionNo();
//        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(fbSectionNo);
//        Map<String,Object> map = new HashMap<>();
//        /**
//         * crystalNo,length,conductiveType,specs,productGrade,productType
//         * gradeType,边长
//         * 08:53productType
//         * gradeType 评级等级
//         */
//
//        BigDecimal length = fbCheckOutData.getLength();
//        String conductionType = fbCheckOutData.getConductionType();
//        String specification = fbCheckOutData.getSpecification();
//        String planGrade = fbCheckOutData.getPlanGrade();
//        String productType = fbCheckOutData.getProductType();
//        String gradeType = fbCheckOutData.getGradeType();
//        String sideLengthRange = fbCheckOutData.getSideLengthRange();
//
//        map.put("crystalNo",fbSectionNo);
//        map.put("length",length);
//        map.put("conductiveType",conductionType);
//        map.put("specs",specification);
//        map.put("productGrade",planGrade);
//        map.put("productType",productType);
//        map.put("gradeType",gradeType);
//        map.put("sideLengthRange ",sideLengthRange);
//        return requestUtils.postForMcs(new RequestDto(noDetectionUrl,noDetectionDto));
        return null;
    }
}
