package com.casic.PgInterface.overtimeInPG.task;

import com.casic.PgInterface.core.util.HttpClientUtils;
import com.casic.PgInterface.core.util.StringUtils;
import com.casic.PgInterface.core.util.configProperty;
import com.casic.PgInterface.overtimeInPG.domain.PGTagMac;
import com.casic.PgInterface.overtimeInPG.dto.PGTagMacDto;
import com.casic.PgInterface.overtimeInPG.manager.PGInOutRecManager;
import com.casic.PgInterface.overtimeInPG.manager.PGTagMacManager;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.TypeRef;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.jayway.jsonpath.spi.json.JsonProvider;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TagmacRun {
    private static final Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider())
            .mappingProvider(new JacksonMappingProvider()).build();
    private static final String authorizationInput = configProperty.getString("anthInput");
    private static final String authorization =configProperty.getString("auth");//Base64加密
    private static final String getTagMacUrl= configProperty.getString("GetTagStatusByHostID");//接口url
    private static final String getInOutUrl=configProperty.getString("GetAreaInOutResult");//接口url
    private static final String getAllUrl=configProperty.getString("AllResult");//接口url
    private static final Logger logger = LoggerFactory.getLogger(TagmacRun.class);
    @Resource
    private  PGTagMacManager pgTagMacManager;
    public void getAllMac()
    {
        TypeRef<List<PGTagMacDto>> tagMacType = new TypeRef<List<PGTagMacDto>>() {
        };
//        String allTagMac="{\"Success\":true,\"ErrorCode\":0,\"ErrorText\":\"\",\"AllResult\":[{\"Success\":true,\"ErrorCode\":0,\"ErrorText\":\"\",\"TagId\":29189,\"TagMac\":\"B0:8E:1A:41:1B:48\",\"TagName\":\"48\",\"SerialNo\":\"\",\"MapId\":2,\"CoordinatesName\":\"研发西北\",\"CoordinatesId\":24,\"X\":54.12,\"Y\":54.62,\"IsLowBattery\":true,\"IsAreaWarning\":false,\"IsDisappeared\":false,\"IsBeltBroken\":false,\"IsReset\":false,\"IsStill2Move\":false,\"IsMove2Still\":false,\"IsButtonPress\":false,\"HostName\":\"48\",\"HostId\":203,\"HostGroupIds\":[1,15],\"HostStatusId\":0,\"HostExternalId\":\"1\",\"HostExternalInfo\":null,\"postionUpdateTime\":\"2019-05-22T11:44:04.0919002+08:00\"},{\"Success\":true,\"ErrorCode\":0,\"ErrorText\":\"\",\"TagId\":11003,\"TagMac\":\"B0:8E:1A:50:54:88\",\"TagName\":\"马桶监测505488\",\"SerialNo\":\"\",\"MapId\":2,\"CoordinatesName\":\"101洗漱间\",\"CoordinatesId\":38,\"X\":-88.7699966430664,\"Y\":-24.059999465942383,\"IsLowBattery\":false,\"IsAreaWarning\":false,\"IsDisappeared\":true,\"IsBeltBroken\":false,\"IsReset\":false,\"IsStill2Move\":false,\"IsMove2Still\":false,\"IsButtonPress\":true,\"HostName\":\"马桶监测505488\",\"HostId\":96,\"HostGroupIds\":[1,9],\"HostStatusId\":0,\"HostExternalId\":\"5488\",\"HostExternalInfo\":\"\",\"postionUpdateTime\":\"2019-05-22T11:09:31.9387103+08:00\"}]}";
        String allTagMac=null;
        allTagMac = HttpClientUtils.get(getAllUrl,authorization);
        logger.info("allTag:"+allTagMac);
        if (StringUtils.isNotBlank(allTagMac)) {
            ReadContext readContext = JsonPath.using(configuration).parse(allTagMac);
            if ("true".equals(readContext.read("$.Success",String.class)))
            {
                List<PGTagMacDto> tagMacList = readContext.read("$.AllResult", tagMacType);
                logger.info("size:" + tagMacList.size());
                if (tagMacList.size()>0) {
                    for (PGTagMacDto tagMac : tagMacList) {
                        PGTagMac pgTagMac = new PGTagMac();
                        PGTagMac pgTagMacTmp = pgTagMacManager.findUniqueBy("hostId",tagMac.getHostId());
                        if (pgTagMacTmp != null) continue;// only sync, no update for the record ,efficency
                        pgTagMac.setHostId(tagMac.getHostId());
                        pgTagMac.setHostName(tagMac.getHostName());
                        pgTagMac.setTagMac(tagMac.getTagMac());
                        pgTagMac.setTagName(tagMac.getTagName());
                        if (pgTagMacTmp != null )
                            pgTagMac.setId(pgTagMacTmp.getId());
                        pgTagMacManager.save(pgTagMac);
                    }
                }
            }
        }
    }

    public  void postInOut(String strFrom) {
        Calendar calendar = Calendar.getInstance();
        Date dtTo = calendar.getTime();
        calendar.add(Calendar.HOUR,-1);
        Date limitDate = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("dtFrom", strFrom);
        jsonBody.put("dtTo", simpleDateFormat.format(dtTo));
        logger.info("body:" + jsonBody.toString());
        String allInOut;
        List<Map<String, Object>> listInOut = new ArrayList<>();
        allInOut = HttpClientUtils.post(getInOutUrl, jsonBody.toString(), authorization);
//        logger.info("allInOut:" + allInOut);
        if (StringUtils.isNotBlank(allInOut)) {
            ReadContext readContext = JsonPath.parse(allInOut);
            if ("true".equals(readContext.read("$.Suceess", String.class))) {
                listInOut = readContext.read("$.AreaInOutInfo");
                for (Map<String,Object> map :listInOut)
                {
                    Date inTime = null;
                    Date outTime = null;
                    String sHostId = map.get("hostId").toString();
                    String sInTime = map.get("inTime").toString().replace('T',' ');
                    String sOutTime = map.get("outTime").toString();

                    try {
                        inTime = simpleDateFormat.parse(sInTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (inTime != null && -1 == inTime.compareTo(limitDate) && StringUtils.isBlank(sOutTime)) {
                        pgTagMacManager.inPGalarm(sHostId, sInTime);
                    }
                    if (StringUtils.isNotBlank(sOutTime))
                    {
                        sOutTime = sOutTime.replace('T',' ');
                        try {
                            outTime = simpleDateFormat.parse(sOutTime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (outTime != null)
                            pgTagMacManager.updateINPGstatus(sHostId,sInTime,sOutTime);
                    }
                }
            }
        }
    }

    public  String getViaHostId(String sHostId)
    {
        TypeRef<List<PGTagMacDto>> tagMacType = new TypeRef<List<PGTagMacDto>>() {
        };
        String oneTagMac,tagMac = null;
        oneTagMac = HttpClientUtils.get(getTagMacUrl+"?hostId="+sHostId,authorization);
//        logger.info("Tag:"+oneTagMac);
        if (StringUtils.isNotBlank(oneTagMac)) {
            ReadContext readContext = JsonPath.parse(oneTagMac);
            if ("true".equals(readContext.read("$.Success",String.class))) {
                tagMac = readContext.read("$.TagMac");
//                logger.info("content:" + tagMac);
            }
        }
        return tagMac;
    }
    public void getMinInTime()
    {
        logger.info("getInTime:"+pgTagMacManager.getMinInTime());
        String dtFrom = pgTagMacManager.getMinInTime();
        if (StringUtils.isNotBlank(dtFrom))
            postInOut(dtFrom);
    }
    public void test()
    {
//        logger.info("testProc:"+pgTagMacManager.testProc());
//        logger.info(String.valueOf(pgTagMacManager.inPGalarm("210","2019-05-22 12:00:00")));
//        logger.info(String.valueOf(pgTagMacManager.updateINPGstatus ("187","2019-05-23 07:28:00","2019-05-23 08:18:00")));

//        logger.info("query:"+pgInOutRecManager.getInOutRec("2019-01-01","2019-06-02").toString());
//        logger.info("query:"+pgInOutRecManager.getInOutRec("2019-01-01","2019-06-02").toString());
    }

    public static void main(String[] args) {
//        getAllMac();
    }

}
