package com.bcxin.autodownloadupload.controller;


import cn.hutool.core.io.FileUtil;
import com.bcxin.autodownloadupload.common.utils.Base64Util;
import com.bcxin.autodownloadupload.common.utils.FileUtils;
import com.bcxin.autodownloadupload.configs.PushConfig;
import com.bcxin.autodownloadupload.dtos.FerryReceiveTaskPushResult;
import com.bcxin.autodownloadupload.dtos.UploadFileRequestDto;
import com.bcxin.autodownloadupload.entity.PushRecord;
import com.bcxin.autodownloadupload.service.PushDataService;
import com.bcxin.autodownloadupload.service.PushRecordService;
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.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/push/data")
public class PushDataController {

    @Autowired
    private PushDataService pushDataService;

    @Autowired
    private PushRecordService pushRecordService;

    @Autowired
    private PushConfig pushConfig;


    /**
     * description: 推送文件，执行自动上传、自动执行sql
     * author: linchunpeng
     * date:  2023-04-23 17:49
     */
    @GetMapping("/{requestId}")
    public Map<String, Object> pushData(@PathVariable("requestId") String requestId) {
        Map<String, Object> resultMap = new HashMap<>();
        PushRecord exist = pushRecordService.getByRequestId(requestId);
        if (exist != null) {
            log.error("当前requestId：{}，已经执行了，无需重复执行", requestId);
            resultMap.put("code", "100000");
            resultMap.put("message", "当前requestId："+requestId+"，已经执行了，无需重复执行");
            return resultMap;
        }
        PushRecord pushRecord = pushDataService.pushData(requestId, true);
        resultMap.put("code", "200");
        resultMap.put("message", pushRecord.getSqlResult() + "\r\n" + pushRecord.getUploadResult());
        return resultMap;
    }

    /**
     * description: 推送文件，执行自动上传、自动执行sql
     * author: linchunpeng
     * date:  2023-04-23 17:49
     */
    @PostMapping("/{requestId}")
    public Map<String, Object> pushDataPost(@PathVariable("requestId") String requestId, Boolean isNeedUnzip) {
        Map<String, Object> resultMap = new HashMap<>();
        PushRecord exist = pushRecordService.getByRequestId(requestId);
        if (exist != null) {
            log.error("当前requestId：{}，已经执行了，无需重复执行", requestId);
            resultMap.put("code", "100000");
            resultMap.put("message", "当前requestId："+requestId+"，已经执行了，无需重复执行");
            return resultMap;
        }
        pushDataService.pushDataAsync(requestId, isNeedUnzip != null && isNeedUnzip);
        resultMap.put("code", "200");
        resultMap.put("message", "推送文件成功");
        return resultMap;
    }

    /**
     * description: 下载推送错误记录txt
     * author: linchunpeng
     * date:  2023-04-25 9:53
     */
    @GetMapping("/download/error/{requestId}")
    public void downloadErrorByRequestId(@PathVariable("requestId") String requestId, HttpServletResponse response) throws IOException {
        log.info("推送错误记录txt下载，requestId:{}", requestId);
        PushRecord pushRecord = pushRecordService.getByRequestId(requestId);
        if (pushRecord == null || StringUtils.isBlank(pushRecord.getExecuteErrorTxtPath()) || !FileUtil.exist(pushRecord.getExecuteErrorTxtPath())) {
            response.setContentType("text/html; charset=UTF-8"); //转码
            PrintWriter out = response.getWriter();
            out.flush();
            out.println("<script defer='defer' type='text/javascript'>");
            out.println("alert('无错误记录txt下载');");
            out.println("</script>");
            return;
        }
        FileUtils.responseWithFile(pushRecord.getExecuteErrorTxtPath(), response);
    }

    /**
     * description：查询自动摆渡推送结果
     * author：linchunpeng
     * date：2024/6/17
     */
    @PostMapping(value = "/query/result/{requestId}")
    public FerryReceiveTaskPushResult queryResult(@PathVariable("requestId") String requestId) {
        return pushDataService.queryAutoFerryPushResult(requestId);
    }


    /**
     * description：上传摆渡包文件
     * author：linchunpeng
     * date：2024/9/19
     */
    @PostMapping("/upload/file")
    public Map<String, Object> uploadFile(@RequestBody UploadFileRequestDto requestDto) {
        Map<String, Object> resultMap = new HashMap<>();
        String filePath = String.format(pushConfig.getFilePath(), requestDto.getRequestId());
        Base64Util.base64ToFile(requestDto.getFileBase64(), filePath);
        resultMap.put("code", "200");
        resultMap.put("message", "上传成功");
        return resultMap;
    }
}
