package org.springblade.command.timedTask;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.command.pojo.entity.FzyjEntity;
import org.springblade.command.pojo.vo.FzyjVO;
import org.springblade.command.pojo.vo.WaitedUrgentRisksVO;
import org.springblade.command.service.IFzyjService;
import org.springblade.command.utils.FzyjUtil;
import org.springblade.common.config.YamlParamsConfig;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.http.util.HttpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 反诈预警 定时任务
 */
@Slf4j
@Configuration
@EnableScheduling
public class FzyjTask extends BladeController {

	@Autowired
	private YamlParamsConfig yamlParamsConfig;

	private IFzyjService fzyjService;

	/**
	 * 拉取待处理的紧急高危反诈预警信息（只返回未处理的记录）
	 * 账号 account
	 * 调用时间 callTime，格式为yyyymmddhh24miss
	 * 加密后的指纹 signature
	 * 预警下发日期 issuedDay，格式为yyyymmdd
	 * 每5分钟
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	private void getWaitedUrgentRisks() {
		String calltime = LocalDateTime.now().format(FzyjUtil.formatter2);
		String issuedDay = LocalDateTime.now().format(FzyjUtil.formatter1);
		String signature = FzyjUtil.getSignature(yamlParamsConfig.getFzyjAccount(), yamlParamsConfig.getFzyjApiKey(), calltime, issuedDay);
		// 调用 拉取预警信息 的接口
		Map<String, Object> map = new HashMap<>();
		map.put("account", yamlParamsConfig.getFzyjAccount());
		map.put("calltime", calltime);
		map.put("issuedDay", issuedDay);
		map.put("signature", signature);
		String result = HttpUtil.post(yamlParamsConfig.getFzyjGetWaitedUrgentRisksUrl(), map);
		// 处理返回结果
		WaitedUrgentRisksVO waitedUrgentRisksVO = JSONObject.parseObject(result, WaitedUrgentRisksVO.class);
		List<FzyjVO> data = waitedUrgentRisksVO.getData();
		List<FzyjEntity> fzyjEntityList = new ArrayList<>();
		String[] risks = new String[data.size()];
		for (int i = 0; i < data.size(); i++) {
			FzyjEntity fzyjEntity = new FzyjEntity();
			BeanUtils.copyProperties(data.get(i), fzyjEntity);
			fzyjEntityList.add(fzyjEntity);
			// 将所有预警信息的syncId拼接成一个数组
			risks[i] = fzyjEntity.getSyncId().toString();
		}
		// 将拉取到的预警信息入库
		fzyjService.saveBatch(fzyjEntityList);
		// 调用 受理预警信息 的接口
		FzyjUtil.markUrgentRisks(yamlParamsConfig.getFzyjAccount(), yamlParamsConfig.getFzyjApiKey(), yamlParamsConfig.getFzyjMarkUrgentRisksUrl(), risks);
	}
}
