package com.yeejoin.amos.api.openapi.face.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.api.openapi.face.model.TaAccessConfigModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TaAccessConfigMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TaAccessConfig;
import com.yeejoin.amos.openapi.enums.TaAccessConfigBizeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 附件表 服务实现类
 *
 * @author duanwei
 * @date 2022-08-17
 */
@Service
public class TaAccessConfigServiceImpl extends BaseService<TaAccessConfigModel, TaAccessConfig, TaAccessConfigMapper> {

	static Map<String, String> licenseConfig = new HashMap<String, String>();

	@Autowired
	private TaLicenseDetailInfoServiceImpl taLicenseDetailInfoService;

	@Autowired
	private TaLicenseBaseInfoServiceImpl taLicenseBaseInfoService;

	/**
	 *
	 * 新增许可信息-接入配置表
	 *
	 * @param model 接入配置实体类集合
	 * @return 成功返回“OK”
	 */
	@Transactional(rollbackFor = { Exception.class })
	public String saveAccessConfig(List<TaAccessConfig> model) {
		// TODO Auto-generated method stub
		if (ValidationUtil.isEmpty(model)) {
			throw new BadRequest("接入配置表信息为空.");
		}
		for (TaAccessConfig models : model) {
//            checkModel(models);
			models.setRecDate(new Date());
//            models.setAppId(getAppId());
		}
		this.saveBatch(model);
		return "OK";
	}

	public void refreshConfig() {
		licenseConfig.clear();
		List<TaAccessConfig> list = this.list(new LambdaQueryWrapper<TaAccessConfig>().eq(TaAccessConfig::getBizType,
				TaAccessConfigBizeEnum.LICENSE.getAttribute()));
		for (TaAccessConfig ta : list) {
			licenseConfig.put(ta.getBizKey(), ta.getBizValue());
		}
	}

	public void startTask() {
		String cron = licenseConfig.get("cron");
		// 创建带线程池的调度器
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		// 手动初始化
		taskScheduler.initialize();
		// 设置线程池
		taskScheduler.setPoolSize(30);
		System.out.println(taskScheduler);
		taskScheduler.schedule(new Runnable() {
			@Override
			public void run() {
				try {
					taLicenseDetailInfoService.syncLicenseData();
					taLicenseBaseInfoService.syncLicenseData();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new CronTrigger(cron));// 这串字符串是cron表达式 代表每隔5秒执行一次
	}
}
