package com.ozs.da.controller;

import com.ozs.da.entity.PageParams;
import com.ozs.da.entity.ReturnData;
import com.ozs.da.entity.remotedb.MdmInfoColumn;
import com.ozs.da.entity.remotedb.MdmInfoDatabase;
import com.ozs.da.entity.remotedb.MdmInfoTable;
import com.ozs.da.entity.task.JobOperateCmd;
import com.ozs.da.entity.task.Task;
import com.ozs.da.feign.AccountApi;
import com.ozs.da.service.task.TaskService;
import com.ozs.da.utils.ReturnUtil;
import com.github.pagehelper.Page;
import io.swagger.annotations.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 许明
 * on 2019/3/5.
 * @version 2.0.0
 */
@Api(value = "任务管理相关接口", description = "任务管理相关接口")
@RestController
public class TaskController {

    private static final Logger logger = LogManager.getLogger(TaskController.class);

    @Autowired
    private TaskService taskService;

    @Autowired
    private AccountApi accountApi;

    @ApiOperation(value = "数据中心-->数据采集-->新增采集任务", notes = "数据中心-->数据采集-->新增采集任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "放在请求头中的令牌", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping(value = "/task/add", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
    public ReturnData addTask(@RequestHeader(name = "token", required = true) String token,
                              @RequestBody @ApiParam Task task) {
        ReturnData returnData = new ReturnData();
        String userId = "";
        try {
            userId = accountApi.parseTokenId(token);
        } catch (Exception e) {
            logger.error("解析令牌错误：" + e.getMessage());
            return ReturnUtil.createExceptionReturn(e);
        }
        try {
            task.setUserId(userId);
            taskService.addTask(task);
            returnData.setMsg("新增成功");
            return returnData;
        } catch (Exception e) {
            logger.error("新增任务失败，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取当前任务列表", notes = "数据中心-->数据采集-->获取当前任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskName", value = "任务名称", dataType = "String", paramType = "query", required = false),
    })
    @GetMapping(value = "/task/list", produces = "application/json;charset=UTF-8")
    public ReturnData<List<Task>> listTask(@RequestParam(name = "taskName", required = false) String taskName,
                                           @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                           @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                           @RequestParam(name = "sort", required = false, defaultValue = "createTime") String sort,
                                           @RequestParam(name = "order", required = false, defaultValue = "desc") String order) {
        try {
            PageParams<Task> pageParams = new PageParams<>();
            Task task = new Task();
            task.setTaskName(taskName);
            pageParams.setData(task);
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setSort(sort);
            pageParams.setOrder(order);
            Page<Task> pageResult = taskService.listTask(pageParams);
            return ReturnUtil.assemblyReturnData(pageResult);
        } catch (Exception e) {
            return ReturnUtil.createExceptionReturn(e);
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取指定任务信息（回显）", notes = "数据中心-->数据采集-->获取指定任务信息（回显）")
    @GetMapping(value = "/task/toEdit/{id}", produces = "application/json;charset=UTF-8")
    public ReturnData<Task> getTaskById(@PathVariable(name = "id") String id) {
        ReturnData<Task> returnData = new ReturnData();
        try {
            Task task = taskService.getTaskInfoById(id);
            returnData.setData(task);
            return returnData;
        } catch (Exception e) {
            logger.error("获取指定任务信息失败，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->更新任务", notes = "数据中心-->数据采集-->更新任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "放在请求头中的令牌", dataType = "String", paramType = "header", required = true),
    })
    @PutMapping(value = "/task/update/{id}", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
    public ReturnData addTask(@RequestHeader(name = "token", required = true) String token,
                              @PathVariable(name = "id") String id,
                              @RequestBody @ApiParam Task task) {
        ReturnData returnData = new ReturnData();
        String userId = "";
        try {
        	userId = accountApi.parseTokenId(token);
        } catch (Exception e) {
            logger.error("解析令牌异常！");
            return ReturnUtil.createExceptionReturn(e);
        }
        try {
            task.setUserId(userId);
            taskService.updateTaskById(task);
            returnData.setMsg("更新成功");
            return returnData;
        } catch (Exception e) {
            logger.error("更新任务失败，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }
    
    @ApiOperation(value = "数据中心-->数据采集-->删除指定任务信息", notes = "数据中心-->数据采集-->删除指定任务信息")
    @DeleteMapping(value = "/task/toDel/{id}", produces = "application/json;charset=UTF-8")
    public ReturnData deleteTaskById(@PathVariable(name = "id") String id) {
        ReturnData returnData = new ReturnData();
        try {
            taskService.deleteTaskById(id);
            returnData.setMsg("删除成功");
            return returnData;
        } catch (Exception e) {
            logger.error("删除指定任务信息失败，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->启停任务，立即执行任务", notes = "数据中心-->数据采集-->启停任务，立即执行任务")
    @PutMapping(value = "/task/operate/{id}", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
    public ReturnData operateTask(@PathVariable(name = "id") String id,
                                  @RequestBody @ApiParam JobOperateCmd jobOperateCmd) {
        ReturnData returnData = new ReturnData();
        try {
            returnData = taskService.operateTask(jobOperateCmd);
            return returnData;
        } catch (Exception e) {
            logger.error("操作失败，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取当前数据库连接信息", notes = "数据中心-->数据采集-->获取当前库数据库连接信息")
    @GetMapping(value = "/task/list/database/{id}", produces = "application/json;charset=UTF-8")
    public ReturnData<MdmInfoDatabase> database(@PathVariable(name = "id", required = true) String id) {
        ReturnData<MdmInfoDatabase> returnData = new ReturnData();
        try {
            MdmInfoDatabase mdmInfoDatabase = taskService.database(id);
            returnData.setData(mdmInfoDatabase);
            return returnData;
        } catch (Exception e) {
            logger.error("获取当前数据库连接信息异常，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取当前数据库中所有表", notes = "数据中心-->数据采集-->获取当前数据库中所有表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "databaseId", value = "数据库id", dataType = "String", paramType = "query", required = true),
    })
    @GetMapping(value = "/task/list/listTableByDatabaseId", produces = "application/json;charset=UTF-8")
    public ReturnData<List<MdmInfoTable>> listTableByDatabaseId(@RequestParam(name = "databaseId", required = true) String databaseId) {
        ReturnData<List<MdmInfoTable>> returnData = new ReturnData();
        try {
            List<MdmInfoTable> mdmInfoTableList = taskService.listTableByDatabaseId(databaseId);
            returnData.setData(mdmInfoTableList);
            return returnData;
        } catch (Exception e) {
            logger.error("获取当前数据库中所有表异常，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取源库数据库列表", notes = "数据中心-->数据采集-->获取源库数据库列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceName", value = "数据库id", dataType = "String", paramType = "query", required = false),
    })
    @GetMapping(value = "/task/list/listOriginal", produces = "application/json;charset=UTF-8")
    public ReturnData<List<MdmInfoDatabase>> listOriginal(@RequestParam(name = "resourceName", required = false) String resourceName) {
        ReturnData<List<MdmInfoDatabase>> returnData = new ReturnData();
        try {
            List<MdmInfoDatabase> mdmInfoDatabaseList = taskService.listOriginal(resourceName);
            returnData.setData(mdmInfoDatabaseList);
            return returnData;
        } catch (Exception e) {
            logger.error("获取源库数据库列表异常，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取目标库数据库列表", notes = "数据中心-->数据采集-->获取目标库数据库列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceName", value = "数据库id", dataType = "String", paramType = "query", required = false),
    })
    @GetMapping(value = "/task/list/listDatabase", produces = "application/json;charset=UTF-8")
    public ReturnData<List<MdmInfoDatabase>> listDatabase(@RequestParam(name = "resourceName", required = false) String resourceName) {
        ReturnData<List<MdmInfoDatabase>> returnData = new ReturnData();
        try {
            List<MdmInfoDatabase> mdmInfoDatabaseList = taskService.listDatabase(resourceName);
            returnData.setData(mdmInfoDatabaseList);
            return returnData;
        } catch (Exception e) {
            logger.error("获取目标库数据库列表异常，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

    @ApiOperation(value = "数据中心-->数据采集-->获取当前库当前表的所有字段信息", notes = "数据中心-->数据采集-->获取当前库当前表的所有字段信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableId", value = "数据库id", dataType = "String", paramType = "query", required = false),
    })
    @GetMapping(value = "/task/list/listColumnByTableId", produces = "application/json;charset=UTF-8")
    public ReturnData<List<MdmInfoColumn>> listColumnByTableId(@RequestParam(name = "tableId", required = false) String tableId) {
        ReturnData<List<MdmInfoColumn>> returnData = new ReturnData();
        try {
            List<MdmInfoColumn> mdmInfoColumnList = taskService.listColumnByTableId(tableId);
            returnData.setData(mdmInfoColumnList);
            return returnData;
        } catch (Exception e) {
            logger.error("获取当前库当前表的所有字段信息异常，信息为：" + e.getMessage());
            returnData.setCode("-1");
            returnData.setMsg(e.getMessage());
            return returnData;
        }
    }

}
