package com.jsc.dsp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsc.dsp.model.ReturnT;
import com.jsc.dsp.utils.AutoExportAndUpload;
import com.jsc.dsp.utils.DatabaseConnector;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/export")
@ConditionalOnProperty(name = "switch.auto-export-and-upload", havingValue = "true", matchIfMissing = true)
public class ExportController {

    @Resource
    DatabaseConnector databaseConnector;

    @Resource
    AutoExportAndUpload autoExportAndUpload;

    @PostMapping("/exportExcel")
    public ReturnT<String> exportExcel(@RequestBody JSONObject object) {
        try {
            String startTime = object.getString("startTime");
            databaseConnector.exportToXlsx(startTime);
            return new ReturnT<>(200, "", "");
        } catch (Exception e) {
            return new ReturnT<>(500, e.getMessage(), "");
        }
    }

    @PostMapping("/triggerTask")
    public ReturnT<String> triggerTask() {
        try {
            new Thread(() -> autoExportAndUpload.exportDataAndUpload()).start();
            return new ReturnT<>(200, "", "");
        } catch (Exception e) {
            return new ReturnT<>(500, e.getMessage(), "");
        }
    }

}
