package com.friday.distributor.controller;

import com.friday.base.common.response.DubboResult;
import com.friday.base.file.dto.FileDownloadDto;
import com.friday.base.file.service.COSPlatformFileService;
import com.friday.base.web.response.ResponseAspect;
import com.friday.blank.api.dto.taskType.TaskTypeDetailDto;
import com.friday.distributor.bean.JobInvokeFilter;
import com.friday.distributor.common.ExecDataService;
import com.friday.distributor.common.PlatformInteractionService;
import com.friday.distributor.common.TaskExecConfigService;
import com.friday.operation.api.distributor.dto.BizConfigDto;
import com.friday.operation.api.distributor.dto.TaieJobCallbackDto;
import com.friday.operation.api.distributor.service.IDistributorInternalService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;

@RestController
@RequestMapping(value = "/task/distributor/internal")
@Slf4j
public class InternalController {

    @Autowired
    private TaskExecConfigService taskExecConfigService;
    @Autowired
    private ExecDataService execDataService;
    @Autowired
    private PlatformInteractionService platformInteractionService;
    @Autowired
    private IDistributorInternalService distributorInternalService;
    @Autowired(required = false)
    private COSPlatformFileService cosPlatformFileService;
    @Autowired
    private ResponseAspect responseAspect;


    @ApiOperation(value = "任务执行状态回调")
    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    public Object callback(@RequestBody TaieJobCallbackDto callBack) {
//        return distributorInternalService.callback(callBack);
        return responseAspect.response(distributorInternalService.callback(callBack));
    }

    @ApiOperation(value = "查询任务是否正在运行")
    @RequestMapping(value = "/checkTaskRunning", method = RequestMethod.POST)
    public Object checkTaskRunning(@RequestBody JobInvokeFilter filter ) {
        return distributorInternalService.checkTaskRunning(filter.getTaieTenant(), filter.getTaskTypeList());
    }

    @ApiOperation(value = "调试用修改管理端运行配置")
    @RequestMapping(value = "/setExecConfig", method = RequestMethod.POST)
    public void setExecConfig(@RequestBody TaskTypeDetailDto detail) {
        taskExecConfigService.setGeneralConfig(detail);
    }

    @ApiOperation(value = "初始化调试用修改管理端运行配置")
    @RequestMapping(value = "/initExecConfig", method = RequestMethod.GET)
    public Object initExecConfig() {
        return taskExecConfigService.initGeneralConfig();
    }

    @ApiOperation(value = "调试用清除管理端运行配置")
    @RequestMapping(value = "/deleteGeneralConfig", method = RequestMethod.POST)
    public void setExecConfig(@ApiParam(name = "taskType") String taskType, @ApiParam(name = "tenant") String tenant) {
        taskExecConfigService.deleteGeneralConfig(tenant, taskType);
    }


    @ApiOperation(value = "查询管理端配置")
    @RequestMapping(value = "/getTaskTypeInfo", method = RequestMethod.POST)
    public Object getTaskTypeInfo(@ApiParam(name = "taskType") String taskType, @ApiParam(name = "tenant") String tenant) {
        return taskExecConfigService.getTaskExecConfig(tenant, taskType);
    }

    @ApiOperation(value = "更新TAIE工位状态")
    @RequestMapping(value = "/updateTaieRobotState", method = RequestMethod.POST)
    public Object updateTaieRobotState(@ApiParam(name = "tenant") String tenant, @ApiParam(name = "machineName") String machineName, @ApiParam(name = "state") String state) {
        return platformInteractionService.syncRobotState(tenant, machineName, state);
    }

    @ApiOperation(value = "查询TAIE工位状态")
    @RequestMapping(value = "/getTaieRobotState", method = RequestMethod.POST)
    public Object getTaieRobotState(@ApiParam(name = "tenant") String tenant, @ApiParam(name = "machineName") String machineName) {
        return platformInteractionService.queryPlatformRobotState(tenant, machineName);
    }

    @ApiOperation(value = "查询TAIE运行配置")
    @RequestMapping(value = "/getTaieExecConfig", method = RequestMethod.POST)
    public Object getTaieExecConfig(@ApiParam(name = "tenant") String tenant, @ApiParam(name = "taskType") String taskType) {
        return platformInteractionService.getTaskExecConfig(tenant, taskType);
    }

    @ApiOperation(value = "新增运行配置")
    @RequestMapping(value = "/createBizConfig", method = RequestMethod.POST)
    public void createBizConfig(@RequestBody BizConfigDto bizConfig) {
        taskExecConfigService.createBizConfig(bizConfig);
    }

    @ApiOperation(value = "获取运行状态")
    @RequestMapping(value = "/getExecInfo", method = RequestMethod.POST)
    public void getExecInfo(@ApiParam(name = "tenant") String tenant, @ApiParam(name = "taskType") String taskType) {
        taskExecConfigService.getBizConfig(tenant, taskType);
    }

    @ApiOperation(value = "上传文件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public DubboResult uploadFile(MultipartFile file) throws IOException {
        if(file == null){
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "文件为空或文件不存在，请重新上传！");
        }
        HashMap<String, byte[]> filesBytes = new HashMap<>();
        filesBytes.put(file.getOriginalFilename(), file.getBytes());
        return cosPlatformFileService.uploadFileByCOS(filesBytes);
    }

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
    public DubboResult downLoadFile(HttpServletResponse response, String fileKey) throws IOException {
        if(StringUtils.isEmpty(fileKey)){
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION,"文件key为空！");
        }
        DubboResult<FileDownloadDto> downloadResult = cosPlatformFileService.downloadFileByCOS(fileKey);
        if (downloadResult.success()) {
            FileDownloadDto fileDownloadDto = downloadResult.getObject();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileDownloadDto.getFileName(), "UTF-8"));
            OutputStream os = response.getOutputStream();
            os.write(fileDownloadDto.getBytes());
            os.flush();
            os.close();
            response.flushBuffer();
            return DubboResult.newSuccess("文件下载成功！");
        }
        return downloadResult;
    }

    @ApiOperation(value = "发送kafka消息")
    @RequestMapping(value = "/sendKafka", method = RequestMethod.POST)
    public void sendKafka(@ApiParam(name = "taskId") String taskId) {
        execDataService.sendKafkaWhenTaskEnded(taskId);
    }

}
