package com.chinaitop.depot.intelligent.grainsituation.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chinaitop.depot.intelligent.grainsituation.mapper.TemperImportMapper;
import com.chinaitop.depot.intelligent.grainsituation.model.TTestdata;
import com.chinaitop.depot.intelligent.grainsituation.service.TemperImportService;
import com.chinaitop.depot.intelligent.pushs.service.GrainPushsService;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.ParameterUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author qingsong.han
 * @description:
 * @create 2020-08-03 15:00
 */
@Service
public class TemperImportServiceImpl implements TemperImportService {
    @Resource
    private TemperImportMapper temperImportMapper;
    @Resource
    private GrainPushsService pushsService;

    @Override
    public String importData(List<List<String>> list, Integer orgId, Map<String, Object> agentMap) {
        String msg = "";

        TTestdata agentTemper = new TTestdata();
        Map<String, Object> enumData = new HashMap<>();

        Map<String, Object> agentsMap = temperImportMapper.getNameId(agentMap);
        if (ParameterUtil.isnull(agentsMap) || ParameterUtil.isnull(agentsMap.get("depotid"))) {
            msg = "粮库信息查询不到，请确认后再导入！";
            return msg;
        }

        //仓房名称
        enumData.put("storehouseName", agentMap.get("storehouseName"));
        enumData.put("depotId", agentsMap.get("depotid"));
        Map<String, Object> storehouseId = temperImportMapper.getStorehouseId(enumData);
        if (ParameterUtil.isnull(storehouseId)) {
            msg = "仓房信息查询不到，请确认后再导入！";
            return msg;
        }
        //货位名称
        enumData.put("warehouseName", agentMap.get("warehouseName"));
        enumData.put("storehouseId", storehouseId.get("storehouseid"));
        Map<String, Object> warehouseId = temperImportMapper.getWarehouseId(enumData);
        if (ParameterUtil.isnull(warehouseId)) {
            msg = "货位信息查询不到，请确认后再导入！";
            return msg;
        }
        agentTemper.setStorehouse(storehouseId.get("storehouse").toString());
        if (!(agentMap.get("houseTemperature") != null && agentMap.get("houseTemperature").toString().matches("^(-)?\\d+(.\\d{1,2})?$"))) { // 带1-2位小数的正数或负数
            msg = "仓温输入值为字符！";
            return msg;
        }
        agentTemper.setInh(new BigDecimal(agentMap.get("houseTemperature").toString()));
        if (!(agentMap.get("houseHumidity") != null && agentMap.get("houseHumidity").toString().matches("^[0.0-9.0]+$"))) { // [0-9]没办法识别小数，[0.0-9.0]可以识别小数和整数
            msg = "仓湿输入值为字符！";
            return msg;
        }
        agentTemper.setOuttemp(new BigDecimal(agentMap.get("houseHumidity").toString()));
        if (!(agentMap.get("gasTemperature") != null && agentMap.get("gasTemperature").toString().matches("^(-)?\\d+(.\\d{1,2})?$"))) { // 带1-2位小数的正数或负数
            msg = "气温输入值为字符！";
            return msg;
        }
        agentTemper.setOuth(new BigDecimal(agentMap.get("gasTemperature").toString()));
        if (!(agentMap.get("gasHumidity") != null && agentMap.get("gasHumidity").toString().matches("^[0.0-9.0]+$"))) {
            msg = "气湿输入值为字符！";
            return msg;
        }
        // 格式化效验时间
        String vDate = agentMap.get("detectionTime").toString();
        if (StringUtils.isNotBlank(vDate)) {
            if (!(DateUtils.dateStringInterval(vDate))) {
                return "检测时间格式为(2020-08-08 10:52:13),其中:为英文符号！";
            }
        } else {
            return "检测时间为空！";
        }

        Map<String, Object> pointMap = new HashMap<>();//一行温度数据
        List<Map<String, Object>> pointList = new ArrayList<>();//温度集合数据

        // mapList 数据封装
        List<String> listMap = new ArrayList<>();
        // 仓房信息map数据
        Map<String, Object> houseMap = new HashMap<>();

        houseMap.put("storehouse", storehouseId.get("storehouse"));
        houseMap.put("house", warehouseId.get("house"));
        // 处理时间
        String string = agentMap.get("detectionTime").toString();
        Date date = DateUtils.stringToData(string);
        String s = DateUtils.formatDateYMDHMS(date);
        houseMap.put("time", s);

        houseMap.put("ilqYq", "0");
        houseMap.put("intemp", agentMap.get("houseTemperature"));
        houseMap.put("inh", agentMap.get("houseHumidity"));
        houseMap.put("outtemp", agentMap.get("gasTemperature"));
        houseMap.put("outh", agentMap.get("gasHumidity"));

        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        // z值顺序效验容器
        Integer zV = 1;
        for (int i = 0; i < list.size(); i++) {
            List<String> revList = list.get(i);
            for (int j = 0; j < revList.size(); j++) {
                switch (j) {
                    case 0:
                        //测温线缆行号(X)
                        pointMap = new HashMap<>();
                        if (!pattern.matcher(revList.get(j)).matches()) {
                            msg = "行不是整数，请确认后再导入！";
                            return msg;
                        }
                        pointMap.put("x", revList.get(j));
                        break;
                    case 1:
                        //测温线缆列号(Y)
                        pointMap.put("y", revList.get(j));
                        if (!pattern.matcher(revList.get(j)).matches()) {
                            msg = "列不是整数，请确认后再导入！";
                            return msg;
                        }
                        break;
                    case 2:
                        //测温点高度(Z)
                        pointMap.put("z", revList.get(j));
                        if (!pattern.matcher(revList.get(j)).matches()) {
                            msg = "高度不是整数，请确认后再导入！";
                            return msg;
                        }
                        // z值顺序效验
                        if (zV <= Integer.parseInt(revList.get(j))) {
                            zV = Integer.parseInt(revList.get(j));
                        } else {
                            msg = "测温点高度(Z)，请顺序填写(1,1,1.2,2,2.3,3,3)！";
                            return msg;
                        }
                        break;
                    case 3:
                        //温度值
                        pointMap.put("temp", revList.get(j));
                        break;
                    default:
                        break;
                }
            }
            pointList.add(pointMap);
        }
        /*// 导入数据层倒叙重新赋值
        // 计算层数
        Map<Integer, List<Map<String, Object>>> z = pointList.stream().collect(Collectors.groupingBy(tem -> Integer.parseInt(tem.get("z").toString())));
        Integer size = z.size();
        // 初始比对计数器
        int i1 = 1;
        // 执行+1时机
        int i = pointList.size() / size;
        // 修改z层(倒叙)
        for (Map<String, Object> pm : pointList) {
            for (String k : pm.keySet()) {
                if ("z".equals(k)) {
                    pm.put(k, size.toString());
                }
            }
            if (i1 == i) {
                size--;
            }
            i1++;
            if (i1 > i) {
                i1 = 1;
            }
        }*/
        houseMap.put("points", pointList); // 层温数据
        listMap.add(JSONObject.toJSONString(houseMap));
        String replace = listMap.toString().replace(" ", "");
        pushsService.uploadGrainTemperatureData("source_ls", replace);
        return msg;
    }

}
