package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.store.BusinessInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderTaskReq;

import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @author Clover.z
 * @version 1.0.0
 * @since 1.0.0
 */
public class OrderTaskReqAdapter {

    /**
     * 设置申请退款时间
     * 如果时间的类型是2表示采用原来的48小时逻辑
     * 如果时间的类型是1表示在指定的时间之后进行退款
     * 为了防止同一时刻的退款量太大，需要将退款的订单分散到指定的时间后半小时内
     */
    public static OrderTaskReq convert(BusinessInfoDto config) {
        OrderTaskReq orderTask;

        if (config.getTimeTypeOfRefund() == null || Objects.equals(config.getTimeTypeOfRefund(), 2)) {
            // 48小时之后
            orderTask = new OrderTaskReq();
            orderTask.setTaskType(4);
            orderTask.setTimeout(1);
            //1000*60*60*24*2 毫秒（48小时）
            long timeout = 172800000;
            long timeMillis = System.currentTimeMillis();
            Date processingDate = new Date(timeMillis + timeout - 60000);
            Date taskTime = new Date(timeMillis + timeout);
            orderTask.setTaskTime(DateUtil.convert2String(taskTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
            //处理时间，当前时间加48小时减1分钟
            orderTask.setProcessingTime(DateUtil.convert2String(processingDate, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        } else if (config.getTimeTypeOfRefund() != null && config.getTimeTypeOfRefund().compareTo(1) == 0) {// 指定时间
            orderTask = new OrderTaskReq();
            orderTask.setTaskType(4);
            orderTask.setTimeout(1);
            // 获取门店配置的当天指定的退款时间
            String timeOfRefund = config.getTimeOfRefund();
            // 获取半小时的随机数
            Random r = new Random();
            int minute = r.ints(1, 31).findFirst().getAsInt() * 60000;
            String today = DateUtil.getCurrentDate(DateUtil.FORMAT_YMD);

            Date configTime = DateUtil.convert2Date(today + " " + timeOfRefund, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            // 判断当前时间是否已经超过门店设置的截至时间
            if (new Date().after(configTime)) {
                today = DateUtil.convert2String(DateUtil.addDays(new Date(), 1), DateUtil.FORMAT_YMD);
                configTime = DateUtil.convert2Date(today + " " + timeOfRefund, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            }
            Date processingDate = new Date(configTime.getTime() + minute);
            String processingStr = DateUtil.convert2String(processingDate, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            orderTask.setTaskTime(processingStr);
            orderTask.setProcessingTime(processingStr);
        } else {
            orderTask = null;
        }
        return orderTask;
    }

}
