package com.steerinfo.ems.ifmesemsswapfile.service.impl;

import com.steerinfo.ems.ifmesemsswapfile.mapper.IfMesEmsSwapfileMapper;
import com.steerinfo.ems.ifmesemsswapfile.model.IfMesEmsSwapfile;
import com.steerinfo.ems.ifmesemsswapfile.service.IIfMesEmsSwapfileService;
import com.steerinfo.ems.Utils.HttpRequestMes;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value = "ifMesEmsSwapfileService")
public class IfMesEmsSwapfileServiceImpl extends BaseServiceImpl<IfMesEmsSwapfile, String> implements IIfMesEmsSwapfileService {
	
	private static final Logger logger = LoggerFactory.getLogger(IfMesEmsSwapfileServiceImpl.class);

    @Autowired
    private IfMesEmsSwapfileMapper ifmesemsswapfilemapper;

    @Override
    protected IBaseMapper<IfMesEmsSwapfile, String> getMapper() {
        return ifmesemsswapfilemapper;
    }

    public String synchronousMesAnEmsData() {
		int addSize = 0;
		int updateSize = 0;
		String url = "http://172.16.100.91:8093/mes_interface/mesdata"; // 投入产出数据
		/*
		 * {"fid":"202102200037","createtime":1614001724000,"works":"8004","orderno":"000010022368",
		 * "materialname":"二体系︱铁水","memo":"铁区报工","mespzid":"CC_1011GL2_000010022368_2021-02-20",
		 * "type":"2","prodline":"1011GL2","unit":"吨","toemsid":"CC_1011GL2_000010022368_2021-02-20_1",
		 * "prodate":1613750400000,"qty":2974.9,"materialcode":"7300000001","sendtime":"2021-02-21 08:49:29","status":"9"}
		 * */
		while (true) {
			try {
				String res = HttpRequestMes.httpRequestMes(url, "get", null);
				JSONArray ja = JSONArray.parseArray(res);
				if (ja != null && !ja.isEmpty()) {
					logger.info("获取投入产出数据条数：" + ja.size());
					for (int i = 0; i < ja.size(); i++) {
						JSONObject jo = (JSONObject) ja.get(i);
						if(!jo.containsKey("fid")){
							continue;
						}
						// 新数据
						IfMesEmsSwapfile model = new IfMesEmsSwapfile();
						model.jsonobjectToIfMesEmsSwapfile(jo);
						// 原数据
						String fid = jo.getString("fid");
						IfMesEmsSwapfile ime = ifmesemsswapfilemapper.selectByPrimaryKey(fid);
						if(ime!=null){
							ifmesemsswapfilemapper.updateByPrimaryKey(model);
							updateSize +=1;
							logger.info("修改数据：" + jo.toJSONString());
							if (!model.getStatus().equals("9")) {
								logger.error("有重复不正常的数据，fid:"+ fid + ",status:" + model.getStatus());
							}
						}else{
							addSize += ifmesemsswapfilemapper.insert(model);
							if (!model.getStatus().equals("0")) {
								logger.error("有新增不正常的数据，fid:"+ fid + ",status:" + model.getStatus());
							}
						}
						HttpRequestMes.httpRequestMes(url, "post", "[{\"id\":\"" + jo.getString("fid") + "\",\"status\":\"1\"}]");
					}
					logger.info("结束一次投入产出数据同步。");
				} else {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("投入产出数据同步出错了。", e);
				break;
			}
		}
		logger.info("本次总共新增投入产出数据条数：" + addSize);
		logger.info("本次总共更新投入产出数据条数：" + updateSize);
        return "本次新增" + addSize + "条,更新" + updateSize + "条。";
	}

	public List<IfMesEmsSwapfile> selectNewMaterial(HashMap<String, Object> model) {
		List<IfMesEmsSwapfile> list = ifmesemsswapfilemapper.selectNewMaterial(model);
		return list;
	};

	public int updateStatus(HashMap<String, Object> m) {
		return ifmesemsswapfilemapper.updateStatus(m);
	}

	public BigDecimal getSUM(HashMap<String, Object> map) {
		BigDecimal sum = ifmesemsswapfilemapper.getSUM(map);
		return sum;	
	}

	@Override
	public String synchronousMesFromProd(Date d) {
		String clock = new SimpleDateFormat("yyyy-MM-dd").format(d);
		String url = "http://ems.sxzygc.com.cn/zhongsteel.pass.web/pass/ems/v1/ifmesemsswapfile/?pageNum=1&pageSize=2000&prodate=" + clock; // 投入产出数据
		String res = HttpRequestMes.httpRequestMes(url, "get", null);
		JSONObject jo = JSONObject.parseObject(res);
		if (jo != null && !jo.isEmpty() && jo.getString("code").equals("0")){
			JSONObject jo2 = (JSONObject)jo.get("data");
			JSONArray ja = (JSONArray)jo2.get("list");
			if (ja != null && !ja.isEmpty()) {
				for (int i = 0; i < ja.size(); i++) {
					JSONObject jo3 = (JSONObject) ja.get(i);
					IfMesEmsSwapfile model = new IfMesEmsSwapfile();
					model.setFid(jo3.getString("fid"));
					model.setId(jo3.getString("fid"));
					model.setCreatetime(jo3.getString("createtime")!=null?jo3.getString("createtime").substring(0, 19):"");
					model.setWorks(jo3.getString("works"));
					model.setMaterialcode(jo3.getString("materialcode"));
					model.setMaterialname(jo3.getString("materialname"));
					model.setOrderno(jo3.getString("orderno"));
					model.setProdate(jo3.getString("prodate")!=null?jo3.getString("prodate").substring(0, 19):"");
					model.setProdline(jo3.getString("prodline"));
					model.setQty(jo3.getBigDecimal("qty"));
					model.setSendtime(jo3.getString("sendtime")!=null?jo3.getString("sendtime").substring(0, 19):"");
					model.setStatus(jo3.getString("status"));
					model.setType(jo3.getString("type"));
					model.setUnit(jo3.getString("unit"));
					ifmesemsswapfilemapper.insert(model);
				}
			}
		}
		logger.info("从正式环境同步MES投入产出数据--执行完毕--");
		return null;
	}
}
