package com.sw.mes.yb.scheduled;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.api.materialclean.MaterialCleanFeignClients;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.dto.erp.ErpOrderDto;
import com.sw.mes.core.dto.erp.ErpResultDto;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

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


/**
 * mes对接erp接口
 * @author xushu
 */
@Slf4j
@Component
public class MesToErpScheduling {

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

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductionOrderService productionOrderService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    private MaterialCleanFeignClients materialCleanFeignClients;

    /**
     * 拉取erp订单job
     */
    @XxlJob("pullErpOrderJobHandler")
    public void pullErpOrderHandler() {
        try {
            log.info("定时拉取【订单】信息");
            String monthFirstDay  = DateUtil.getMonthFirstDay();
            String monthLastDay  = DateUtil.getMonthLastDay();
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(mediaType);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            String path = "/bm-sw/get-work-order-number";
            HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(erpOrderServiceUrl+path)
                    .queryParam("from", monthFirstDay)
                    .queryParam("to", monthLastDay);
            ResponseEntity<String> exchange = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, httpEntity, String.class);
            String body = exchange.getBody();
            ErpResultDto erpResultDto = JSONObject.parseObject(body, ErpResultDto.class);
            if(erpResultDto.getCode().equals(ResultCode.SUCCESS.getCode())){
                List<ErpOrderDto> erpOrderDtos = erpResultDto.getData();
                List<ErpOrderDto> ybErpOrderDto =  new ArrayList<>();
                List<ErpOrderDto> fbErpOrderDto =  new ArrayList<>();
                List<ErpOrderDto> xlErpOrderDto =  new ArrayList<>();
                if(CollectionUtil.isNotEmpty(erpOrderDtos)){
                    for(ErpOrderDto dto:erpOrderDtos){
                        String mocode  = dto.getMocode();
                        if(StringUtils.isNotBlank(mocode) && mocode.length() > SectionIndexRangeEnum.工单类型.getEndIndex()) {
                            String type = mocode.substring(SectionIndexRangeEnum.工单类型.getBeginIndex(), SectionIndexRangeEnum.工单类型.getEndIndex());
                            if("C".equals(type)){
                                ybErpOrderDto.add(dto);
                            }else if("M".equals(type)){
                                fbErpOrderDto.add(dto);
                            }else if("S".equals(type)){
                                xlErpOrderDto.add(dto);
                            }
                        }
                    }
                    //圆棒
                    if(CollectionUtil.isNotEmpty(ybErpOrderDto) && CollectionUtil.isNotEmpty(fbErpOrderDto)){
                        productionOrderService.handleErpOrder(ybErpOrderDto,fbErpOrderDto);
                    }
                    //方棒
                    if(CollectionUtil.isNotEmpty(fbErpOrderDto)){
                        fbFeignClients.handleErpOrder(fbErpOrderDto);
                    }
                    //洗料
                    if(CollectionUtil.isNotEmpty(xlErpOrderDto)){
                        materialCleanFeignClients.handleErpOrder(xlErpOrderDto);
                    }
                }

            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }

    }

}
