package com.szpg.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.szpg.db.dao.PgMaintanceDao;
import com.szpg.db.dao.impl.PgMaintanceDaoImpl;
import com.szpg.db.data.PgMainJson;
import com.szpg.db.data.PgMaintance;
import com.szpg.util.HttpRequest;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

public class ReadMaintanceTask implements Runnable{
    private final Logger logger = Logger.getLogger(this.getClass().getName());
    final String tableName="V_MaintanceRecord_Head";
    final String url="http://10.10.2.31:9056/GLYW/api/Common/LoadIndexData";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run(){
        PgMaintanceDao pgMaintanceDao=new PgMaintanceDaoImpl();

        try {
            Date date = new Date();

            String startTime = pgMaintanceDao.findLastRecordTime();//上次同步数据最后记录时间
            String endTime = dateFormat.format(date);//当前时间

            if (startTime == null) {
                Date dt = new Date();
                startTime = new ReadAssetInSpectionTask().getStartDateStr(dt, -1);
            } else {
                Date dtStart = dateFormat.parse(startTime);
                startTime = new ReadAssetInSpectionTask().getStartDateStr(dtStart, 1);
            }

            StringBuilder sb = new StringBuilder();
            sb.append("tableName = ").append(tableName);
            sb.append("&page=-1");
            sb.append("&strWhere=采集时间");
            sb.append(" between '").append(startTime);
            sb.append("' and '").append(endTime);
            sb.append("'");

            logger.info("开始请求维护数据");
            String jsonStr = HttpRequest.sendPostByHttp(url, sb.toString());

            if (jsonStr.equals(""))
                logger.info("维护数据请求失败");
            else {
                insertDB(pgMaintanceDao, jsonStr);
                logger.info("维护数据存储成功");
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void insertDB(PgMaintanceDao pgMaintanceDao,String jsonStr){
        List<PgMaintance> pgMaintanceList= getMintanceByJsonString(jsonStr);
        pgMaintanceDao.addMaintanceRecord(pgMaintanceList);
    }

    private List<PgMaintance> getMintanceByJsonString(String jsonStr){
        PgMainJson pgMainJson = JSON.parseObject(jsonStr, new TypeReference<PgMainJson>() {});
        List<PgMaintance> pgMaintanceList=pgMainJson.getRows();

        return pgMaintanceList;
    }


}