package com.zhongshu.card.server.core.service.schedule;

import cn.hutool.json.JSONObject;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.client.type.ScheduleType;
import com.zhongshu.card.client.type.paySetting.RegularType;
import com.zhongshu.card.client.type.paySetting.SettlementRulesType;
import com.zhongshu.card.server.core.dao.projectAbout.ProjectMainPaySettingDao;
import com.zhongshu.card.server.core.dao.schedule.ScheduleTaskConfigDao;
import com.zhongshu.card.server.core.domain.paySetting.ProjectMainPaySetting;
import com.zhongshu.card.server.core.domain.schedule.ScheduleTaskConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 定时任务服务
 *
 * @author TRX
 * @date 2024/11/6
 */
@Slf4j
@Service
public class ScheduleTaskConfigService {

    @Autowired
    private ScheduleTaskConfigDao scheduleTaskConfigDao;

    @Autowired
    private ProjectMainPaySettingDao projectMainPaySettingDao;

    @Autowired
    private ScheduledTask scheduledTask;

    // 每天好多点、好多分
    private static final String CRON_TEMPLATE = "0 %s %s * * ?";

    /**
     * 加载系统的定时任务
     */
    public void initAllTaskLockSchedule() {
        this.loadAllSchedule();
    }

    //----------------------------定时任务数据组装 start-----------------------

    /**
     * 添加项目的结算定时任务
     *
     * @param entity
     * @return
     */
    public ResultContent initProjectSettlementRulesTask(ProjectMainPaySetting entity) {
        if (ObjectUtils.isNotEmpty(entity)) {
            try {
                String lockKey = projectMainPaySettingDao.acquire(entity.getId(), 5000L);
                if (StringUtils.isNotEmpty(lockKey)) {
//                    项目结算任务
                    String aboutDataId = entity.getProjectOid() + "_" + entity.getChannelType().name();
                    ScheduleTaskConfig taskConfig = scheduleTaskConfigDao.findTopByAboutDataId(aboutDataId);
                    if (ObjectUtils.isEmpty(taskConfig)) {
                        taskConfig = new ScheduleTaskConfig();
                    }
                    taskConfig.setAboutDataId(aboutDataId);
                    HashMap<String, Object> data = new HashMap<>();
                    data.put("projectOid", entity.getProjectOid());
                    data.put("id", entity.getId());
                    data.put("channelType", entity.getChannelType().name());

                    taskConfig.setData(data);
                    taskConfig.setDataState(DataState.Enable);
                    taskConfig.setScheduleType(ScheduleType.SettlementTask);
                    String expression = "";
                    String timeStr = entity.getTimeStr();

                    String[] timeParts = timeStr.split(":");
                    String hour = timeParts[0];
                    String minute = timeParts[1];

                    SettlementRulesType rulesType = entity.getSettlementRulesType();
                    if (rulesType == SettlementRulesType.Dn) {
                        // D+N  每天执行
                        expression = String.format(CRON_TEMPLATE, minute, hour);
                    } else if (rulesType == SettlementRulesType.Regular) {
                        // 定期
                        RegularType regularType = entity.getRegularType();
                        if (regularType == RegularType.Day) {
                            // 每天
                            expression = String.format(CRON_TEMPLATE, minute, hour);
                        } else if (regularType == RegularType.Week) {
                            // 每周 星期一
                            expression = String.format("0 %s %s ? * MON", minute, hour);
                        } else if (regularType == RegularType.Month) {
                            // 每月 1号
                            expression = String.format("0 %s %s 1 * ?", minute, hour);
                        }
                    }
                    taskConfig.setExpression(expression);
                    taskConfig.setRemark(String.format("项目结算定时任务: 项目oid=%s，支付渠道= %s",
                            entity.getProjectOid(), entity.getChannelType().getRemark()));
                    scheduleTaskConfigDao.save(taskConfig);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                projectMainPaySettingDao.release(entity.getId());
            }
        }
        this.loadAllSchedule();
        return ResultContent.buildSuccess();
    }

    /**
     * 重置所有的定时任务
     */
    private void loadAllSchedule() {
        try {
            log.info("================系统启动加载定时任务====开始===========");
            List<ScheduleTaskConfig> list = scheduleTaskConfigDao.findAll();
            log.info("================系统启动加载定时任务size: {}", list.size());
            scheduledTask.refreshTask(list);
            log.info("================系统启动加载定时任务====结束===========");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("================系统启动加载定时任务====异常=========== {}", e.getMessage());
        }
    }

    /**
     * 根据关联的业务数据ID 删除定时任务
     *
     * @param aboutDataId
     * @return
     */
    public ResultContent deleteTask(String aboutDataId) {
        if (StringUtils.isNotEmpty(aboutDataId)) {
            ScheduleTaskConfig entity = scheduleTaskConfigDao.findTopByAboutDataId(aboutDataId);
            scheduleTaskConfigDao.delete(entity);
        }
        return ResultContent.buildSuccess();
    }
}
