package com.reptileclient.jlifeapp.schedule;

import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.config.SendSms;
import com.reptileclient.jlifeapp.constant.HemaConstant;
import com.reptileclient.jlifeapp.constant.JlifeConstant;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dto.HmBookTradeOrderDTO;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.service.HmSalesOrderService;
import com.reptileclient.jlifeapp.util.DateUtils;
import com.reptileclient.jlifeapp.util.HttpUtil;
import com.reptileclient.jlifeapp.util.OkHttpUtil;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 *  token超时处理通知
 * @author lu
 *
 */
@Component
public class NoticeTokenTask {


	private static final Logger logger = LoggerFactory.getLogger(NoticeTokenTask.class);


	@Autowired
	HmTokenMapper hmtk;

	@Autowired
	SendSms sms;

	private static String runDate;

	@Scheduled(cron = "0 0 20 * * ?") // 每天20点执行一次
	public void startJob() {

		if (LocalDateTime.now().getHour() == 20 && StringUtils.isNotEmpty(runDate) && runDate.equals(DateUtils.getCurrentDay()))
			return;

		logger.info("开始  验证token.........................");
		try {
			HmToken hm = hmtk.selectAll();
			OkHttpUtil.hmToken = hm.getToken();//刷新token变量

			//随机延迟
			int waitTime = new Random().nextInt(60);
			logger.info("开始等待 " + waitTime + " 分...");
			Thread.sleep(waitTime * 60 * 1000);

			  HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
	            hmBookTradeOrderDTO.setPageSize(50);
	            hmBookTradeOrderDTO.setPageIndex(1);
	            hmBookTradeOrderDTO.setBeginTime(DateUtil.formatDate(DateUtil.offsetDay(new DateTime(), -3)));
	            hmBookTradeOrderDTO.setEndTime(DateUtil.formatDate(DateUtil.offsetDay(new DateTime(), -1)));

//			String parmJson = HemaConstant.test_parm;
//	            Map<String, Object> request = HttpUtil.request(hm.getToken(), parmJson, HemaConstant.HEMADATA_LYSJYJXS_URL);

			Map<String, Object> request = HttpUtil.request(hm.getToken(), JSONObject.toJSONString(hmBookTradeOrderDTO), JlifeConstant.BOOK_TRADE_URL);

			logger.info("接口返回信息：" + request);
			if (request.get("success").toString().equals("true")
					|| request.get("success").toString().equals("false")) {
				//true 或false都可以，token失效会报错页面，不会返回 success信息
			} else {
				//失败处理发短信
				SendSms.toSendMs();
			}

		} catch (Exception e) {
			SendSms.toSendMs();
			e.printStackTrace();

		}


	}




}
