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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.HttpRequestMes;
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.trmmaterial.model.TRmMaterial;
import com.steerinfo.ems.trmmaterial.service.ITRmMaterialService;
import com.steerinfo.ems.trmproduct.model.TRmProduct;
import com.steerinfo.ems.trmproduct.service.ITRmProductService;
import com.steerinfo.ems.trmworkprocmaterial.model.TRmWorkprocMaterial;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import com.steerinfo.ems.trmworkprocproduct.model.TRmWorkprocProduct;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
import com.steerinfo.feigen.model.LgWeight;
import com.steerinfo.feigen.service.LgWeightFeigenService;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@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;
	@Autowired
	private LgWeightFeigenService lgWeightFeigenService;

	@Autowired
	ITRmMaterialService tRmMaterialService;

	@Autowired
	ITRmProductService tRmProductService;

	@Autowired
	ITRmWorkprocMaterialService tRmWorkprocMaterialService;

	@Autowired
	ITRmWorkprocProductService tRmWorkprocProductService;

	@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;
	}


	//获取炼钢的产出数据
	public void getLgDateProd() {
		List<LgWeight> lgWeights = lgWeightFeigenService.QueryWeightByTime();
		for (LgWeight lgWeight : lgWeights) {
			IfMesEmsSwapfile model = new IfMesEmsSwapfile();
			model.setType(lgWeight.getType());
			model.setWorks("AT2004");
			model.setProdline("1036LG1");
			model.setMaterialcode(lgWeight.getMaterialcode());
			model.setProdate(lgWeight.getDate());
			model.setMaterialname(lgWeight.getMaterialname());
			model.setUnit(lgWeight.getUnit());
			model.setQty(lgWeight.getWeight());
			model.setCreatetime(DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
			model.setStatus("0");
			model.setFid(lgWeight.getFid());
			IfMesEmsSwapfile ifMesEmsSwapfile = ifmesemsswapfilemapper.selectByPrimaryKey(lgWeight.getFid());
			if (ifMesEmsSwapfile != null) {
				ifmesemsswapfilemapper.updateByPrimaryKey(model);
			} else {
				ifmesemsswapfilemapper.insert(model);
			}
		}
		System.out.println("接收成功...");
	}

	//获取炼钢的投入数据
	public void getLgDateProd2() throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = sdf.parse(DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.DAY_OF_MONTH, -2);
		Date dt1 = rightNow.getTime();
		String reStr = sdf.format(dt1);
		List<LgWeight> lgWeights = lgWeightFeigenService.QueryWeightByTime2(reStr, DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
		for (LgWeight lgWeight : lgWeights) {
			IfMesEmsSwapfile model = new IfMesEmsSwapfile();
			model.setType(lgWeight.getType());
			model.setWorks("AT2004");
			model.setProdline("1036LG1");
			model.setMaterialcode(lgWeight.getMaterialcode());
			model.setProdate(lgWeight.getDate());
			model.setMaterialname(lgWeight.getMaterialname());
			model.setUnit(lgWeight.getUnit());
			model.setQty(lgWeight.getWeight());
			model.setCreatetime(DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
			model.setStatus("0");
			model.setFid(lgWeight.getFid());
			IfMesEmsSwapfile ifMesEmsSwapfile = ifmesemsswapfilemapper.selectByPrimaryKey(lgWeight.getFid());
			if (ifMesEmsSwapfile != null) {
				ifmesemsswapfilemapper.updateByPrimaryKey(model);
			} else {
				ifmesemsswapfilemapper.insert(model);
			}
		}
		System.out.println("接收成功...");
	}

	@Override
	public PageList<Map<String, Object>> getQueryList(HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		//Calendar cal = Calendar.getInstance();
		//cal.add(Calendar.HOUR_OF_DAY, 1);
		//cal.add(Calendar.DAY_OF_YEAR, -1);
		//String clock = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
		//parmas.put("clockt", clock); // 可以修改的clock
		//parmas.put("clocktm", clock.substring(0, 7)); // 可以修改的clock（月）
		if (parmas.get("workprocid") != null && !parmas.get("workprocid").toString().isEmpty()) {
			String workProcids = parmas.get("workprocid").toString();
			workProcids = "'" + workProcids.replaceAll(",", "','").replaceAll("，", "','") + "'";
			parmas.put("workProcids", workProcids);
		}
		List<Map<String, Object>> rows = ifmesemsswapfilemapper.getQueryList(parmas);
		PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
		return pageInfo;
	}

	@Override
	public PageList<Map<String, Object>> queryProductAndMaterial(HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		if (parmas.get("workprocid") != null && !parmas.get("workprocid").toString().isEmpty()) {
			String workProcids = parmas.get("workprocid").toString();
			workProcids = "'" + workProcids.replaceAll(",", "','").replaceAll("，", "','") + "'";
			parmas.put("workProcids", workProcids);
		}
		if (parmas.get("workproc") != null && !parmas.get("workproc").toString().isEmpty()) {
			String workProcs = parmas.get("workproc").toString();
			workProcs = "'" + workProcs.replaceAll(",", "','").replaceAll("，", "','") + "'";
			parmas.put("workProcs", workProcs);
		}
		List<Map<String, Object>> rows = ifmesemsswapfilemapper.queryProductAndMaterial(parmas);
		PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
		return pageInfo;
	}

	@Override
	public int updateProductAndMaterial(HashMap<String, Object> parmas) {
		return ifmesemsswapfilemapper.updateProductAndMaterial(parmas);
	}

	@Override
	public String generateProductAndMaterial() {
		HashMap hashMap = new HashMap<String, String>();
		List<TRmProduct> tRmProducts = tRmProductService.query(hashMap);
		List<TRmMaterial> trmMaterials = tRmMaterialService.query(hashMap);
		List<TRmWorkprocProduct> tRmWorkprocProducts = tRmWorkprocProductService.query(hashMap);
		List<TRmWorkprocMaterial> tRmWorkprocMaterials = tRmWorkprocMaterialService.query(hashMap);
		IfMesEmsSwapfile model = new IfMesEmsSwapfile();
		IfMesEmsSwapfile ifMesEmsSwapfile;
		String materialName;
		int addSize = 0;
		for (TRmWorkprocProduct tRmWorkprocProduct : tRmWorkprocProducts) {
			ifMesEmsSwapfile = ifmesemsswapfilemapper.selectByPrimaryKey(tRmWorkprocProduct.getProductid() + tRmWorkprocProduct.getMesProdline() + DateUtils.dateStr(new Date(), "yyyyMMdd"));
			if (ifMesEmsSwapfile == null) {
				materialName = tRmProductService.getById(tRmWorkprocProduct.getProductid()).getName();
				model.setType("2");
				model.setWorks(tRmWorkprocProduct.getWorkprocid());
				model.setProdline(tRmWorkprocProduct.getMesProdline());
				model.setProdate(DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
				model.setMaterialname(materialName);
				model.setMaterialcode(tRmWorkprocProduct.getMesMaterialcode());
				model.setUnit(tRmWorkprocProduct.getUnitid());
				model.setQty(new BigDecimal(0));
				// DateUtils.dateStr(new Date(),"yyyy-MM-dd HH-mm-ss")
				model.setCreatetime(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				model.setStatus("0");
				model.setFid(tRmWorkprocProduct.getProductid() + tRmWorkprocProduct.getMesProdline() + DateUtils.dateStr(new Date(), "yyyyMMdd"));
				addSize += ifmesemsswapfilemapper.insert(model);
			}
		}
		for (TRmWorkprocMaterial tRmWorkprocMaterial : tRmWorkprocMaterials) {
			ifMesEmsSwapfile = ifmesemsswapfilemapper.selectByPrimaryKey(tRmWorkprocMaterial.getMaterialid() + tRmWorkprocMaterial.getMesProdline() + DateUtils.dateStr(new Date(), "yyyyMMdd"));
			if (ifMesEmsSwapfile == null) {
				materialName = tRmMaterialService.getById(tRmWorkprocMaterial.getMaterialid()).getName();
				model.setType("1");
				model.setWorks(tRmWorkprocMaterial.getWorkprocid());
				model.setProdline(tRmWorkprocMaterial.getMesProdline());
				model.setProdate(DateUtils.dateStr(new Date(), "yyyy-MM-dd"));
				model.setMaterialname(materialName);
				model.setMaterialcode(tRmWorkprocMaterial.getMesMaterialcode());
				model.setUnit(tRmWorkprocMaterial.getUnitid());
				model.setQty(new BigDecimal(0));
				model.setCreatetime(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				model.setStatus("0");
				model.setFid(tRmWorkprocMaterial.getMaterialid() + tRmWorkprocMaterial.getMesProdline() + DateUtils.dateStr(new Date(), "yyyyMMdd"));
				addSize += ifmesemsswapfilemapper.insert(model);
			}
		}
		return "本次共生成" + addSize + "条";
	}
}
