package com.quantgroup.asset.distribution.controller;

import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.quantgroup.asset.distribution.service.redis.IRedisService;
import com.quantgroup.asset.distribution.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.asset.IAssetService;
import com.quantgroup.asset.distribution.service.jpa.entity.DistributeFailLog;
import com.quantgroup.asset.distribution.service.jpa.repository.IDistributeFailLogRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 重试Controller
 * 
 * @author liwenbin
 *
 */
@RestController
@Slf4j
@RequestMapping("/retry")
public class RetryController {

	@Autowired
	private IDistributeFailLogRepository distributeFailLogRepository;
	@Autowired
	private IAssetService assetService;
	@Autowired
	private IRedisService<String> redisService;

	@RequestMapping("/orders")
	public GlobalResponse retryOrders(String startTime, String endTime) {
		try {
			Page<DistributeFailLog> pageableFailAuditLog = distributeFailLogRepository.findByCreatedAtBetweenAndEnable(
					Timestamp.valueOf(startTime), Timestamp.valueOf(endTime), true, new PageRequest(0, 1000));
			List<DistributeFailLog> distributeFailLogList = pageableFailAuditLog.getContent();
			retryDistributeFailLogList(distributeFailLogList);
		} catch (Exception e) {
			log.error("资产分发失败订单重新分发异常!", e);
		}
		return GlobalResponse.success();
	}

	@Async
	@RequestMapping("/repeat_db_distribute")
	public void repeatDBAudit() {
		String lockKey = "ASSET_DISTRIBUTION:REPEAT_DB_ATTRIBUTE:@88JMS";
		try {
			log.info("数据库资产分发失败订单重新分发开始");
			boolean b = redisService.setIfAbsent(lockKey, "1", 1, TimeUnit.DAYS);
			if (!b) { return; }
			String startTime = DateUtil.getStrFormatDate("yyyy-MM-dd HH:mm:ss", -7);
			String endTime = DateUtil.timestamp2Str(System.currentTimeMillis() + "", "yyyy-MM-dd HH:mm:ss");
			int i = 1;
			while (i > 0 && !CheckController.isOffLine()) {
				Page<DistributeFailLog> pageableFailDistributeLog = distributeFailLogRepository.findByCreatedAtBetweenAndEnable(Timestamp.valueOf(startTime),
						Timestamp.valueOf(endTime), true, new PageRequest(0, 50));
				List<DistributeFailLog> distributeFailLogList = pageableFailDistributeLog.getContent();
				retryDistributeFailLogList(distributeFailLogList);
				TimeUnit.SECONDS.sleep(30);
				++i;
				if (distributeFailLogList == null || distributeFailLogList.size() < 50) {
					i = -1;
				}
			}
			log.info("数据库资产分发失败订单重新分发完成!");
		} catch (Exception e) {
			log.error("数据库资产分发失败订单重新分发出现异常!", e);
		} finally {
			redisService.del(lockKey);
		}
	}


	private void retryDistributeFailLogList(List<DistributeFailLog> distributeFailLogList) {
		if (CollectionUtils.isNotEmpty(distributeFailLogList)) {
			log.info("分发失败查询数量为:{}", distributeFailLogList.size());
			distributeFailLogList.forEach(distributeFailLog -> {
				AssetForm assetForm = JSON.parseObject(distributeFailLog.getContext(), AssetForm.class);
				// 重新审核
				assetService.assetsIn(assetForm);

				distributeFailLog.setEnable(false);
				distributeFailLogRepository.save(distributeFailLog);
			});
		}
	}
}
