package com.xisc.pm.infra.client;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.xisc.pm.api.dto.InspectionCertificateDTO;
import com.xisc.pm.api.dto.ProdPonoSlabRequestDTO;
import com.xisc.pm.api.dto.ProductionResponseDTO;
import com.xisc.pm.api.dto.ProductionTypeBResponseDTO;
import com.xisc.pm.api.dto.ProductionTypeGiveResponseDTO;
import com.xisc.pm.api.dto.ProductionTypePResponseDTO;
import com.xisc.pm.api.dto.QeSampleAddtionResponseDTO;
import com.xisc.pm.api.dto.ThickPlatePerformanceDeterminationDTO;
import com.xisc.pm.domain.vo.QeResvReplaceTriggerVO;
import com.xisc.pm.domain.vo.QeSampleAddtionRequestVO;
import com.xisc.pm.domain.vo.SlabNoCorrespondingBigLotReturnVo;
import com.xisc.pm.domain.vo.SlabNoCorrespondingBigLotVo;
import com.xisc.pm.infra.feign.QeApiFeign;
import com.xisc.pm.infra.util.Utils;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.exception.ExceptionResponse;
import lombok.extern.slf4j.Slf4j;
import org.hzero.core.util.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @date 2024/10/22 17:24
 * @description
 */
@Slf4j
@Component
public class QeApiClient {
    @Autowired
    private QeApiFeign qeApiFeign;

    @Autowired
    private ObjectMapper objectMapper;

    public Map<String, QeSampleAddtionResponseDTO> sampleAddtion(Long tenantId,
            List<QeSampleAddtionRequestVO> qeSampleAddtionRequestList,  List<String> responseJsonList) {
             List<QeSampleAddtionRequestVO> sortRequestList = qeSampleAddtionRequestList.stream()
                .sorted(Comparator.comparing(QeSampleAddtionRequestVO::getTmpSlabNo)).collect(Collectors.toList());
        try {
            log.info("调用QE-API【sampleAddtion】，入参：tenantId = {}, matNoList = {}", tenantId,
                    objectMapper.writeValueAsString(sortRequestList));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        ResponseEntity<String> res = qeApiFeign.sampleAddtion(tenantId, sortRequestList);
        responseJsonList.add(res.getBody());
        log.info("调用QE-API【sampleAddtion】，返回：" + res.getBody());
        if (ResponseUtils.isFailed(res)) {
            ExceptionResponse response = Utils.getExceptionResponse(res);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
        Map<String, QeSampleAddtionResponseDTO> result = new HashMap<>();
        List<ProductionResponseDTO> sampleAddtionResponse = dealResponse(res, ProductionResponseDTO.class);
        if (sampleAddtionResponse != null && !sampleAddtionResponse.isEmpty()) {
            for (ProductionResponseDTO productionResponseDTO : sampleAddtionResponse) {

                // 大板
                if (productionResponseDTO.getProductionTypeP() != null
                        && !productionResponseDTO.getProductionTypeP().isEmpty()) {
                    for (ProductionTypePResponseDTO typePResponseDTO : productionResponseDTO.getProductionTypeP()) {

                        QeSampleAddtionResponseDTO qeSampleAddtionResponseDTO = null;
                        if (result.containsKey(typePResponseDTO.getTmpSlabNo())) {
                            qeSampleAddtionResponseDTO = result.get(typePResponseDTO.getTmpSlabNo());
                        } else {
                            qeSampleAddtionResponseDTO = new QeSampleAddtionResponseDTO();
                            result.put(typePResponseDTO.getTmpSlabNo(), qeSampleAddtionResponseDTO);
                        }

                        qeSampleAddtionResponseDTO.getProductionTypePResponse().put(typePResponseDTO.getTmpSlabNo(),
                                typePResponseDTO);
                        if (typePResponseDTO.getSampleHeadLenPlate() != null) {
                            qeSampleAddtionResponseDTO.setSampleHeadLenPlate(qeSampleAddtionResponseDTO
                                    .getSampleHeadLenPlate().add(typePResponseDTO.getSampleHeadLenPlate()));
                        }
                        if (typePResponseDTO.getSampleTailLenPlate() != null) {
                            qeSampleAddtionResponseDTO.setSampleTailLenPlate(qeSampleAddtionResponseDTO
                                    .getSampleTailLenPlate().add(typePResponseDTO.getSampleTailLenPlate()));
                        }
                    }
                }

                // 张张板
                if (productionResponseDTO.getProductionTypeB() != null
                        && !productionResponseDTO.getProductionTypeB().isEmpty()) {
                    for (ProductionTypeBResponseDTO typeBResponseDTO : productionResponseDTO.getProductionTypeB()) {
                        QeSampleAddtionResponseDTO qeSampleAddtionResponseDTO = null;
                        if (result.containsKey(typeBResponseDTO.getTmpSlabNo())) {
                            qeSampleAddtionResponseDTO = result.get(typeBResponseDTO.getTmpSlabNo());
                        } else {
                            qeSampleAddtionResponseDTO = new QeSampleAddtionResponseDTO();
                            result.put(typeBResponseDTO.getTmpSlabNo(), qeSampleAddtionResponseDTO);
                        }

                        qeSampleAddtionResponseDTO.getProductionTypeBResponse().put(typeBResponseDTO.getOrderNo(),
                                typeBResponseDTO);
                        if (typeBResponseDTO.getSampleHeadLenFree() != null) {
                            qeSampleAddtionResponseDTO.setSampleHeadLenFree(qeSampleAddtionResponseDTO
                                    .getSampleHeadLenFree().add(typeBResponseDTO.getSampleHeadLenFree()));
                        }
                        if (typeBResponseDTO.getSampleTailLenFree() != null) {
                            qeSampleAddtionResponseDTO.setSampleTailLenFree(qeSampleAddtionResponseDTO
                                    .getSampleTailLenFree().add(typeBResponseDTO.getSampleTailLenFree()));
                        }
                    }
                }
                // 奉送样
                if (productionResponseDTO.getProductionTypeGive() != null
                        && !productionResponseDTO.getProductionTypeGive().isEmpty()) {

                    for (ProductionTypeGiveResponseDTO productionTypeGiveResponseDTO : productionResponseDTO
                            .getProductionTypeGive()) {
                        
                        QeSampleAddtionResponseDTO qeSampleAddtionResponseDTO = null;
                        if (result.containsKey(productionTypeGiveResponseDTO.getTmpSlabNo())) {
                            qeSampleAddtionResponseDTO = result.get(productionTypeGiveResponseDTO.getTmpSlabNo());
                        } else {
                            qeSampleAddtionResponseDTO = new QeSampleAddtionResponseDTO();
                            result.put(productionTypeGiveResponseDTO.getTmpSlabNo(), qeSampleAddtionResponseDTO);
                        }

                        qeSampleAddtionResponseDTO.getProductionTypeGiveResponse()
                                .put(productionTypeGiveResponseDTO.getOrderNo(), productionTypeGiveResponseDTO);

                        // 奉送样长度乘以奉送样个数
                        if (productionTypeGiveResponseDTO.getGiveSampleLen() != null && productionTypeGiveResponseDTO.getSampleGiveNum() != null) {
                            BigDecimal sampleLenGive = new BigDecimal(productionTypeGiveResponseDTO.getGiveSampleLen()).multiply(new BigDecimal(productionTypeGiveResponseDTO.getSampleGiveNum()));
                            qeSampleAddtionResponseDTO.setSampleLenGive(sampleLenGive.add(qeSampleAddtionResponseDTO.getSampleLenGive()));
                        }
//                        if (productionTypeGiveResponseDTO.getSampleLenGive() != null) {
//                            qeSampleAddtionResponseDTO.setSampleLenGive(productionTypeGiveResponseDTO.getSampleLenGive()
//                                    .add(qeSampleAddtionResponseDTO.getSampleLenGive()));
//                        }
                    }

                }

            }
            for (Entry<String, QeSampleAddtionResponseDTO> entry : result.entrySet()) {
                QeSampleAddtionResponseDTO qeSampleAddtionResponseDTO = entry.getValue();
                qeSampleAddtionResponseDTO.setSampleLenHead(qeSampleAddtionResponseDTO.getSampleHeadLenFree()
                        .add(qeSampleAddtionResponseDTO.getSampleHeadLenPlate()));
                qeSampleAddtionResponseDTO.setSampleLenTail(qeSampleAddtionResponseDTO.getSampleTailLenFree()
                        .add(qeSampleAddtionResponseDTO.getSampleTailLenPlate()));
                qeSampleAddtionResponseDTO.setSampleLen(
                        qeSampleAddtionResponseDTO.getSampleLenHead().add(qeSampleAddtionResponseDTO.getSampleLenTail())
                                );
            }

        }
        return result;
    }


    public void sampleGensRemove(Long tenantId, List<ProdPonoSlabRequestDTO> dtoList) {
        log.info("调用QE-API【sampleGensRemove】，入参：tenantId = {}, dtoList = {}", tenantId, dtoList);
        ResponseEntity<String> res = qeApiFeign.sampleGensRemove(tenantId, dtoList);
        log.info("调用QE-API【sampleGensRemove】，返回：" + res.getBody());
        if (ResponseUtils.isFailed(res)) {
            ExceptionResponse response = Utils.getExceptionResponse(res);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
    }

    /**
     * 会检证书删除
     *
     * @param tenantId    租户
     * @param plateIdList 钢板主键id集合
     * @return
     */
    public List<InspectionCertificateDTO> inspectionCertificateApi(Long tenantId, List<Long> plateIdList) {
        log.info("调用QE-API【inspectionCertificateApi】，入参：tenantId = {}, plateIdList = {}", tenantId, plateIdList);
        ResponseEntity<String> res = qeApiFeign.inspectionCertificateApi(tenantId, plateIdList);
        log.info("调用QE-API【inspectionCertificateApi】，返回：" + res.getBody());
        if (ResponseUtils.isFailed(res)) {
            ExceptionResponse response = Utils.getExceptionResponse(res);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
        return dealResponse(res, InspectionCertificateDTO.class);
    }
    
    /**
     * 命令板坯号对应大LOT键查询
     *
     * @param tenantId    租户
     * @param plateIdList 命令板坯号集合
     * @return
     */
    public List<SlabNoCorrespondingBigLotReturnVo> slabNoCorrespondingBigLot(Long tenantId, List<SlabNoCorrespondingBigLotVo> dtoList) {
        log.info("调用QE-API【slabNoCorrespondingBigLotApi】，入参：tenantId = {}, plateIdList = {}", tenantId, dtoList);
        ResponseEntity<String> res = qeApiFeign.slabNoCorrespondingBigLot(tenantId, dtoList);
        log.info("调用QE-API【slabNoCorrespondingBigLotApi】，返回：" + res.getBody());
        if (ResponseUtils.isFailed(res)) {
            ExceptionResponse response = Utils.getExceptionResponse(res);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
        return dealResponse(res, SlabNoCorrespondingBigLotReturnVo.class);
    }

    /**
     * 处理响应结果
     *
     * @param res
     * @param clazz
     * @return
     */
    public <T> List<T> dealResponse(ResponseEntity<String> res, Class<T> clazz) {
        if (ResponseUtils.isFailed(res)) {
            ExceptionResponse response = Utils.getExceptionResponse(res);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
        List<T> resultList = null;
        try {
            // 尝试将JSON字符串转换为实体列表
            CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
            resultList = objectMapper.readValue(res.getBody(), collectionType);
        } catch (CommonException e) {
            throw e;
        } catch (Exception e) {
            log.error(String.format("解析返回参数失败：%s ", e.getMessage()));
            throw new CommonException("pm.pm_call_qd_order_info_002", e.getMessage());
        }
        return resultList;
    }

    public ThickPlatePerformanceDeterminationDTO thickPlatePerformanceDeterminationApi(Long organizationId,
            ThickPlatePerformanceDeterminationDTO dto) {
        log.debug("调用质量接口【thickPlatePerformanceDeterminationApi】入参 tenantId：{}, dto = {}", organizationId,
                JSONObject.toJSON(dto));
        ResponseEntity<String> result = qeApiFeign.thickPlatePerformanceDeterminationApi(organizationId, dto);
        log.debug("调用质量接口【thickPlatePerformanceDeterminationApi】返回：" + result.getBody());
        if (ResponseUtils.isFailed(result)) {
            ExceptionResponse response = Utils.getExceptionResponse(result);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
        return JSONObject.parseObject(result.getBody(), ThickPlatePerformanceDeterminationDTO.class);
    }

    public void resvReplaceTriggerBatchApi(Long organizationId, List<QeResvReplaceTriggerVO> dtoList) {
        log.debug("调用质量接口【resvReplaceTriggerBatchApi】入参 tenantId：{}, dto = {}", organizationId,
                JSONObject.toJSON(dtoList));
        ResponseEntity<String> result = qeApiFeign.resvReplaceTriggerBatchApi(organizationId, dtoList);
        log.debug("调用质量接口【resvReplaceTriggerBatchApi】返回：" + result.getBody());
        if (ResponseUtils.isFailed(result)) {
            ExceptionResponse response = Utils.getExceptionResponse(result);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
    }

    public void tmpSlabNoUpdate(Long organizationId, List<ProdPonoSlabRequestDTO> dtoList) {
        log.debug("调用质量接口【tmpSlabNoUpdate】入参 tenantId：{}, dto = {}", organizationId,
                JSONObject.toJSON(dtoList));
        ResponseEntity<String> result = qeApiFeign.tmpSlabNoUpdate(organizationId, dtoList);
        log.debug("调用质量接口【tmpSlabNoUpdate】返回：" + result.getBody());
        if (ResponseUtils.isFailed(result)) {
            ExceptionResponse response = Utils.getExceptionResponse(result);
            throw new CommonException("pm.pm_call_qd_order_info_001", response.getMessage());
        }
    }

}
