package com.sw.mes.yb.scheduled;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.yb.report.dto.EmsPushInfoDto;
import com.sw.mes.yb.report.dto.EmsPushListDataDto;
import com.sw.mes.yb.report.service.CastMaterialInfoService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author wanghao
 * @Date: 2022/7/7
 * @Modified By:
 */
@Component
public class EnergyManageIssueScheduling {
    private static final Map<String,String> Input_Type = new HashMap<String, String>();

    public EnergyManageIssueScheduling() {
        //推送类型
        Input_Type.put("materialsWeight","feeding_quantity");//投料量
        Input_Type.put("inspectionYbWeight","round_bar_inspection_quantity");//圆棒过检量
        Input_Type.put("inspectionFbWeight","square_bar_inspection_quantity");//方棒过检量
        Input_Type.put("totalOpen","device_open_flag");//设备开机数量
        Input_Type.put("standby","device_standby_flag");//设备待机数量
    }

    @Autowired
    private CastMaterialInfoService castMaterialInfoService;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    /**
     * 每日9点05推送（分模块）EMS能源管理系统
     * 当前时间设备开启数量、设备总数量、设备计划待机数量；
     * 前一日（前一天早九点至当日早九点【前闭后开】）的投料量、圆棒过检量、方棒过检量
     */
    //    @Scheduled(cron = "0 05 09 * * ?")
    @XxlJob("energyManageIssueScheduling")
    public void energyManageIssueScheduling() {
        String url = "";
        String ak = "";
        List<DictionaryItem> emsUrl = dictionaryItemService.findByThemeValueAndEnable("emsUrl", true);
        if (emsUrl != null && emsUrl.size() > 0){
            url = emsUrl.get(0).getValue();
            ak = emsUrl.get(0).getExtendValue();
        }

        EmsPushInfoDto emsPushInfoDto = new EmsPushInfoDto();
        List<EmsPushListDataDto> listData = new ArrayList<>();
        emsPushInfoDto.setAk(ak);
        List<Map<String, Object>> rptData = castMaterialInfoService.energyStatisticsInfo();
        for (Map<String, Object> map : rptData) {
            for (Map.Entry<String, String> entry : Input_Type.entrySet()) {
                EmsPushListDataDto emsPushListDataDto = new EmsPushListDataDto();
                emsPushListDataDto.setUsedDate(String.valueOf(map.get("time")));
                emsPushListDataDto.setInputType(entry.getValue());
                emsPushListDataDto.setLocationId(String.valueOf(map.get("area")));
                emsPushListDataDto.setTopParentId("宁夏六期工厂");
                String value = String.valueOf(map.get(entry.getKey()));
                if(StringUtils.isNotBlank(value) && value != "null") {
                    emsPushListDataDto.setInputData(new BigDecimal(value));
                    //bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                if (emsPushListDataDto.getInputData() != null) {
                    listData.add(emsPushListDataDto);
                }
            }
        }
        emsPushInfoDto.setListData(listData);
        String result = "";

        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(mediaType);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<EmsPushInfoDto> httpEntity = new HttpEntity<>(emsPushInfoDto, headers);
            //使用exchange请求接口
            ResponseEntity<String> exchange = restTemplate.exchange(url + "/api/ems-cloud-service/common/inputData", HttpMethod.POST, httpEntity, String.class);
            result = JSON.toJSONString(exchange);
        }catch (Exception ex){
            result = "Result（接口调用异常）:" + ex.getMessage();
        }

        try {
            SysLog syslog = new SysLog();
            syslog.setCreateTime(new Date());
            syslog.setType("info");
            syslog.setCreateUserId(BaseContextHandler.getUserID());
            syslog.setCreateUserName("SYSTEM");
            syslog.setContent(JSON.toJSONString(emsPushInfoDto));
            syslog.setResult(result);
            syslog.setCreateUserId(-1);
            syslog.setMethodName("energyManageIssueScheduling()");
            syslog.setStatus(1);
            syslog.setName("MES->EMS能源管理系统");
            String serverAddr = url + "/api/ems-cloud-service/common/inputData";
            syslog.setServerAddr(serverAddr);
            syslog.setReqType("HTTP");
            syslog.setReqIp(IpUtils.getLocalIP());
            sysLogService.save(syslog);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
