package com.tofly.base.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.base.entity.DataBack;
import com.tofly.base.entity.DataBackPolicy;
import com.tofly.base.mapper.DataBackPolicyMapper;
import com.tofly.base.service.DataBackService;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.oauth.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 备份与还原
 * 该功能要求在模块部署服务器已安装oracle（客户端）或者mysql客户端
 * 功能通过执行脚本异步执行备份
 *
 * @author zhoux
 * @date Wed Mar 10 00:00:00 CST 2021
 */
@RestController
@RequestMapping("/dataBack")
@Api(tags="数据备份接口")
public class DataBackController {
	
	@Autowired
    private DataBackService dataBackService;
	@Autowired
    private DataBackPolicyMapper dataBackPolicyMapper;

		
    /**
    * 分页查询
    * @param page 分页对象
    * @param dataBack
    * @return
    */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getDataBackPage(Page page, @ModelAttribute DataBack dataBack) {
  	  	return ResultRespone.success(dataBackService.getDataBackPage(page, dataBack));
    }
    
    
    /**
     * 人工执行数据备份
     * @param request 执行数据备份
     * @return
     */
     @PostMapping("/doDataBack" )
     @ApiOperation(value = "执行数据备份")
     public ResultRespone doDataBack(HttpServletRequest request) {
    	 try {
    		 dataBackService.backUpMysqlManual();
    		 return ResultRespone.success("数据库备份操作中，请稍后。");
    	 }catch (Exception e) {
			e.printStackTrace();
			return ResultRespone.failed(e.getMessage());
		 }
     }
     
     /**
      * 修改备份策略
      * @param dataBackPolicy  修改备份策略
      * @return
      */
     @PutMapping("/backPolicy" )
     @ApiOperation(value = "修改备份策略")
     public ResultRespone backPolicy(@RequestBody DataBackPolicy dataBackPolicy) {
    	     	 
    	 String days = dataBackPolicy.getIntervalDays();
    	 dataBackPolicy.setCronVal("0 0 0 */"+days+" * ?");    	 
    	 dataBackPolicy.setBackRemark("每天0点，每隔"+days+"天执行备份。");    	 
    	 dataBackPolicy.setCreateTime(new Date());
    	 dataBackPolicy.setCreateUser(SecurityUtils.getUserId());
    	     	 
    	 dataBackPolicyMapper.updateById(dataBackPolicy);
    	 return ResultRespone.success("数据备份策略修改成功");
     }
     
     /**
      * 备份策略获取
      * @return
      */
     @GetMapping("/getBackPolicy" )
     @ApiOperation(value = "获取数据备份策略")
     public ResultRespone getBackPolicy() { 	
    	 return ResultRespone.success(dataBackPolicyMapper.selectById(1));
     }
     
}