package com.jianshui.api.controller.http.file;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.exception.jianshui.JianshiSystemErrorException;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.storage.domain.StorageUrlDTO;
import com.jianshui.storage.factory.StorageFactory;
import com.jianshui.storage.service.IStorageService;
import com.jianshui.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @Author 巩权林
 * @Date 2022-09-16 8:45
 **/
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private StorageFactory storageFactory;
    @Autowired
    private ISysConfigService iSysConfigService;

    @GetMapping("/query/{dto}")
    public void queryFile(HttpServletResponse response, @PathVariable("dto") String dto) throws IOException {
        if (StringUtils.isEmpty(dto)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        StorageUrlDTO storageUrlDTO = null;
        try {
            String decodeDto = Base64.decodeStr(dto);
            storageUrlDTO = JSONObject.parseObject(decodeDto, StorageUrlDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        IStorageService service = null;
        try {
            service = storageFactory.getStorageInstance(storageUrlDTO.getServiceProvider());
        } catch (JianshiSystemErrorException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        if (service == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        AjaxResult queryResult = service.getFile(storageUrlDTO);
        if (queryResult.isError()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        if (StringUtils.isNotEmpty(storageUrlDTO.getContentType())) {
            if (StringUtils.equals(storageUrlDTO.getContentType(), "pdf")) {
                response.setContentType("application/pdf");
            }
            if (StringUtils.equals(storageUrlDTO.getContentType(), "ofd")) {
                response.setContentType("application/octet-stream");
            }
        }

        response.sendRedirect((String) queryResult.get("data"));
    }



    @GetMapping("/cleanRedisConfig/{redisSysconfig}")
    public void cleanRedisConfig(@PathVariable("redisSysconfig") String redisSysconfig) throws IOException {
        iSysConfigService.cleanRedisConfig(redisSysconfig);
    }

}
