package com.casic.PgInterface.overtimeInPG.task;

import com.casic.PgInterface.core.util.DateUtils;
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.domain.PGTagPosition;
import com.casic.PgInterface.overtimeInPG.dto.PGTagMacDto;
import com.casic.PgInterface.overtimeInPG.dto.PGTagPositionDto;
import com.casic.PgInterface.overtimeInPG.manager.PGTagMacManager;
import com.casic.PgInterface.overtimeInPG.manager.PGTagPositionManager;
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 GetTagStatus= configProperty.getString("GetTagStatus");//接口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);
    private static final String nullTimeStr = "0001-01-01T00:00:00+08:00";

    @Resource
    private  PGTagMacManager pgTagMacManager;
    @Resource
    private  PGTagPositionManager pgTagPositionManager;
    //查询所有设备
    public void getAllMac()
    {
        TypeRef<List<PGTagMacDto>> tagMacType = new TypeRef<List<PGTagMacDto>>() {
        };

        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().toUpperCase());
                        pgTagMac.setTagName(tagMac.getTagName());
                        if (pgTagMacTmp != null )
                            pgTagMac.setId(pgTagMacTmp.getId());
                        pgTagMacManager.save(pgTagMac);
                    }
                }
            }
        }
    }

    public void getMacPosition() throws ParseException
    {
        TypeRef<List<PGTagPositionDto>> tagPositionType = new TypeRef<List<PGTagPositionDto>>() {
        };
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String allTagPosition=null;
        //        String allTagPosition=null;
        allTagPosition = HttpClientUtils.get(getAllUrl,authorization);
        logger.info("allTagPosition:"+allTagPosition);
        if (StringUtils.isNotBlank(allTagPosition)) {
            ReadContext readContext = JsonPath.using(configuration).parse(allTagPosition);
            if ("true".equals(readContext.read("$.Success",String.class)))
            {
                List<PGTagPositionDto> tagPositionList = readContext.read("$.AllResult", tagPositionType);
                logger.info("size:" + tagPositionList.size());
                if (tagPositionList.size()>0) {
                    for (PGTagPositionDto tagPosition : tagPositionList) {
                        PGTagPosition pgTagPosition = new PGTagPosition();
//                        PGTagPosition pgTagPositionTmp = new PGTagPosition();
                        System.out.println("info:"+tagPosition.toString());
                        boolean bExist = false;
                        bExist = pgTagPositionManager.findTagPosition(tagPosition.getPostionUpdateTime(),tagPosition.getHostId());
                        if (bExist) continue;// only sync, no update for the record ,efficency

                        pgTagPosition.setY(tagPosition.getY());pgTagPosition.setHostId(tagPosition.getHostId());
                        pgTagPosition.setHostName(tagPosition.getHostName());
                        pgTagPosition.setTagId(tagPosition.getTagId());
                        pgTagPosition.setTagMac(tagPosition.getTagMac().toUpperCase());
                        pgTagPosition.setTagName(tagPosition.getTagName());
                        pgTagPosition.setX(tagPosition.getX());
                        pgTagPosition.setCoordinate(tagPosition.getCoordinatesId());
                        pgTagPosition.setCoordinatesName(tagPosition.getCoordinatesName());
                        pgTagPosition.setPositionUpdatetime(tagPosition.getPostionUpdateTime());
                        pgTagPosition.setParsedTime(simpleDateFormat.parse(tagPosition.getPostionUpdateTime().substring(0,19).replaceFirst("T"," ")));
//                        if (pgTagPositionTmp != null )
//                            pgTagPosition.setId(pgTagPositionTmp.getId());
                        pgTagPositionManager.save(pgTagPosition);
                    }
                }
            }
        }
    }

    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 PGTagPosition GetTagStatus(PGTagMac pgTagMac)
    {
        PGTagPosition pgTagPosition = new PGTagPosition();

        TypeRef<PGTagPositionDto> tagPositionType = new TypeRef<PGTagPositionDto>() {
        };
        String oneTagMac,tagMac = null;
        oneTagMac = HttpClientUtils.get(GetTagStatus+"?tagMac="+pgTagMac.getTagMac(),authorization);
        logger.info("Tag:"+oneTagMac);
        if (StringUtils.isNotBlank(oneTagMac)) {
//            ReadContext readContext = JsonPath.parse(oneTagMac);
            ReadContext readContext = JsonPath.using(configuration).parse(oneTagMac);
            if ("true".equals(readContext.read("$.Success",String.class))) {
                PGTagPositionDto pgTagPositionDto = readContext.read("$['CoordinatesId','CoordinatesName','X','Y','postionUpdateTime']\"",tagPositionType);

                pgTagPosition.setHostId(pgTagMac.getHostId());
                pgTagPosition.setHostName(pgTagMac.getHostName());
                pgTagPosition.setTagMac(pgTagMac.getTagMac());
                pgTagPosition.setTagName(pgTagMac.getTagName());

                pgTagPosition.setTagId(pgTagPositionDto.getTagId());
                pgTagPosition.setX(pgTagPositionDto.getX());
                pgTagPosition.setY(pgTagPositionDto.getY());
                pgTagPosition.setCoordinatesName(pgTagPositionDto.getCoordinatesName());
                pgTagPosition.setCoordinate(pgTagPositionDto.getCoordinatesId());

                pgTagPosition.setPositionUpdatetime(pgTagPositionDto.getPostionUpdateTime());
                try {
                    pgTagPosition.setParsedTime(DateUtils.sdf4.parse(pgTagPositionDto.getPostionUpdateTime().substring(0,19).replace('T',' ')));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }


        return pgTagPosition;
    }

    public void getMinInTime()
    {
        logger.info("getInTime:"+pgTagMacManager.getMinInTime());
        String dtFrom = pgTagMacManager.getMinInTime();
        if (StringUtils.isNotBlank(dtFrom))
            postInOut(dtFrom);
    }

    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();
                    String sOutTime = map.get("outTime").toString();
                    if (nullTimeStr.equals(sInTime)&&nullTimeStr.equals(sOutTime))
                        break;

                    try {
                        inTime = simpleDateFormat.parse(sInTime.substring(0,19).replace('T',' '));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (inTime != null && -1 == inTime.compareTo(limitDate) && StringUtils.isBlank(sOutTime)) {
//                        pgTagMacManager.inPGalarm(sHostId, sInTime);//remove
                        System.out.println("overTime In PG");
                    }
                    if (!nullTimeStr.equals(sOutTime) && StringUtils.isNotBlank(sOutTime))
                    {
                        sOutTime = sOutTime.substring(0,19).replace('T',' ');
                        try {
                            outTime = simpleDateFormat.parse(sOutTime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (outTime != null)
                            pgTagMacManager.updateINPGstatus(sHostId,sInTime,sOutTime);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws ParseException
    {
        TagmacRun tagmacRun = new TagmacRun();

        tagmacRun.getAllMac();
    }

}