package com.jay.monitor.data.server.controllers.monitor;

import cn.hutool.core.date.DateUtil;
import com.jay.monitor.data.core.enums.MsgTypeEnums;
import com.jay.monitor.data.core.model.response.PageResponseModel;
import com.jay.monitor.data.server.models.request.trace.PageRequest;
import com.jay.monitor.data.server.store.TranceJsonManager;
import com.jay.monitor.data.server.utils.DataUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 基础加载监控数据路由
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/26 - 10:47
 */
public abstract class BaseLoadMonitorController<T extends PageRequest> {

    @Autowired
    private TranceJsonManager tranceJsonManager;

    /**
     * 监控数据类型，需要实现类回填
     *
     * @return
     */
    public abstract MsgTypeEnums type();

    @RequestMapping(value = "/pageList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public PageResponseModel pageList(@RequestBody T request) throws Exception {
        String date = DataUtils.parseDayString(request.getDate());

        formatDate(request);

        processBefore(request);

        // 将参数对应的全部匹配赋值
        PageResponseModel pageResponseModel =
            tranceJsonManager.searchDataByList(type(), date, request.getPageNo(), request.getPageSize(), request);

        processAfter(request, pageResponseModel);

        return pageResponseModel;
    }

    /**
     * 执行之前
     *
     * @param req
     */
    protected void processBefore(T req) {

    }

    /**
     * 执行之后
     *
     * @param req
     */
    protected void processAfter(T req, PageResponseModel pageResponseModel) {

    }

    protected void formatDate(PageRequest request) {
        String day = DateUtil.formatDate(request.getDate());
        String rangTime = request.getRangTime();
        if (StringUtils.isNotEmpty(rangTime)) {
            String[] range = rangTime.split(",");
            if (range.length == 1) {
                String startDate = range[0];
                String s = day + " " + startDate;
                request.setEndDate(DateUtil.parseDateTime(s).toJdkDate());
            } else {
                String startDate = range[0];
                String s = day + " " + startDate;
                String endDate = range[1];
                String e = day + " " + endDate;
                request.setStartDate(DateUtil.parseDateTime(s).toJdkDate());
                request.setEndDate(DateUtil.parseDateTime(e).toJdkDate());
            }

        }
    }

}
