package com.reptileclient.jlifeapp.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.reptileclient.jlifeapp.constant.HemaConstant;
import com.reptileclient.jlifeapp.dao.hm.HmDownHistoryMapper;
import com.reptileclient.jlifeapp.entity.hm.HmDownHistory;
import com.reptileclient.jlifeapp.service.HmDownHistoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Map;

@Service
public class HmDownHistoryServiceImpl implements HmDownHistoryService {

	@Autowired
	HmDownHistoryMapper hmDownHistoryMapper;

	public static Gson gson = new Gson();
	public static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// .SSS

	@Override
	public HmDownHistory insertDownLog(String url, String parmJson, String durl, String localAddress, Map<String,Object> bodyjson,
			String exportName, String parmStartTime, String parmEndTime) {

		// TODO Auto-generated method stub
		HmDownHistory record = new HmDownHistory();
		record.setExportName(exportName);
		record.setExportParm(parmJson);
		record.setExportUrl(url);
		record.setHmExcelAddress(durl);
		record.setReturnData(gson.toJson(bodyjson));
		
		record.setIsRead(0);
		if(!bodyjson.get("success").toString().equals("true")) {
			record.setIsRead(-1);//失败的
		}

		record.setParmStartTime(DateUtil.parse(parmStartTime));
		record.setParmEndTime(DateUtil.parse(parmEndTime));

		if (!bodyjson.toString().contains("false")) {
			record.setLocalAddress(localAddress);// /ftpsrv/export_file/2020/12/02/11.sql
			String ld = localAddress.substring(localAddress.indexOf("export_file") + 12, localAddress.length());// 2020/12/02/11.sql
			record.setLocalDownUrl(HemaConstant.LOCAL_BASE_URL + ld);
		}

		hmDownHistoryMapper.insertSelective(record);
		return record;
	}

	@Override
	public HmDownHistory insertDownLog(String exportName,String url, String parmJson,String startTime,String endTime,int state) {
		HmDownHistory record = new HmDownHistory();
		record.setExportName(exportName);
		record.setExportUrl(url);
		record.setExportParm(parmJson);

		if(StringUtils.isNotBlank(startTime)) {
			record.setParmStartTime(DateUtil.parse(startTime));
		}
		if(StringUtils.isNotBlank(endTime)) {
			record.setParmEndTime(DateUtil.parse(endTime));
		}

		record.setIsRead(state);//0成功，1失败
		hmDownHistoryMapper.insertSelective(record);
		return record;
	}

}
