package com.bcxin.autodownloadupload.controller;


import cn.hutool.core.io.FileUtil;
import com.bcxin.autodownloadupload.common.utils.FileUtils;
import com.bcxin.autodownloadupload.dtos.ChangeLogsRequestDto;
import com.bcxin.autodownloadupload.dtos.FerryTaskPullResult;
import com.bcxin.autodownloadupload.entity.PullRecord;
import com.bcxin.autodownloadupload.service.PullDataService;
import com.bcxin.autodownloadupload.service.PullRecordService;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pull/data")
public class PullDataController {

    @Autowired
    private PullDataService pullDataService;

    @Autowired
    private PullRecordService pullRecordService;


    /**
     * description: 旧数据迁移
     * author: linchunpeng
     * date:  2023-04-25 9:53
     */
    @GetMapping("/oldDataProcessor/{beginEnd}")
    public void oldDataProcessor(@PathVariable("beginEnd") String beginEnd) {
        String[] split = beginEnd.split("-");
        pullDataService.oldDataProcessor(Long.parseLong(split[0]), Long.parseLong(split[1]));
    }

    /**
     * description: 手动执行拉取数据
     * author: linchunpeng
     * date:  2023-04-25 9:53
     */
    @RequestMapping(value = "/manual", method ={RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> manual(@RequestBody ChangeLogsRequestDto requestDto) {
        Map<String, Object> resultMap = new HashMap<>();
        ChangeLogsRequestDto changeLogsRequestDto = pullDataService.pullDataAsync(requestDto, 1);
        resultMap.put("code", 200);
        resultMap.put("message", changeLogsRequestDto != null ? changeLogsRequestDto : "调用成功");
        return resultMap;
    }

    /**
     * description: 下载拉取结果zip
     * author: linchunpeng
     * date:  2023-04-25 9:53
     */
    @GetMapping("/download/{requestId}")
    public void downloadByRequestId(@PathVariable("requestId") String requestId, HttpServletResponse response) throws IOException {
        log.info("拉取数据zip包下载，requestId:{}", requestId);
        PullRecord pullRecord = pullRecordService.getByRequestId(requestId);
        if (pullRecord == null || StringUtils.isBlank(pullRecord.getCompleteZipPath()) || !FileUtil.exist(pullRecord.getCompleteZipPath())) {
            response.setContentType("text/html; charset=UTF-8"); //转码
            PrintWriter out = response.getWriter();
            out.flush();
            out.println("<script defer='defer' type='text/javascript'>");
            out.println("alert('无zip包下载，请确认前一天是否产生变更数据，如果没有产生变更数据，则不会生成zip包');");
            out.println("</script>");
            return;
        }
        FileUtils.responseWithFile(pullRecord.getCompleteZipPath(), response);
    }

   /**
    * description：自动摆渡查询拉取结果
    * author：linchunpeng
    * date：2024/6/17
    */
    @PostMapping(value = "/query/result")
    public FerryTaskPullResult queryResult(@RequestBody ChangeLogsRequestDto requestDto) {
        return pullDataService.queryAutoFerryPullResult(requestDto.getAutoFerryTaskId());
    }

}
