package com.product.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.product.common.lang.StringUtils;
import com.product.core.config.CoreConst;
import com.product.core.controller.support.AbstractBaseController;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.config.CmnConst;
import com.product.file.config.FileCode;
import com.product.file.service.FileManagerService;
import com.product.module.sys.version.ApiVersion;
import com.product.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Copyright  LX-BASE
 *
 * @Title: FileManagerController
 * @Project: LX-BASE-SERVER
 * @Date: 2020-06-17 16:54
 * @Author: LiuChao
 * @Description: 鏂囦欢绠$悊
 */
@RequestMapping("/api/fileManager")
@RestController
public class FileManagerController extends AbstractBaseController {

    @Autowired
    public FileManagerService fileManagerService;


    /**
     * @param uuid
     * @param response
     * @return
     */
    @GetMapping("/get-static-file/{version}")
    @ApiVersion(1)
    public String getStaticFile(@RequestParam("uuid") String uuid, HttpServletResponse response) {
        try {
            // 娌℃湁鐧诲綍锛岀櫧鍚嶅崟涓� 璇ユ帴鍙d腑涓嶈兘鑾峰彇 token 鍜� 褰撳墠鐢ㄦ埛
            fileManagerService.getStaticFile(uuid, response);
            return OK();
        } catch (BaseException e) {
            e.printStackTrace();
            return error(e);
        } catch (Exception e) {
            e.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().error(e);
            return error(FileCode.GET_FILE_FAIL);
        }
    }


    /**
     * 鑾峰彇瀹㈡埛涓婁紶鐨勬枃浠舵€诲ぇ灏�
     *
     * @param request 璇锋眰
     * @return 缁撴灉
     */
    @RequestMapping(value = "/find-client-file-uesd-capacity/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String findClientFileUsedCapacity(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }

            long usedCapacity = fileManagerService.findClientFileUsedCapacity(fse.getString("client_uuid"));
            JSONObject data = new JSONObject();
            data.put("used_capacity", String.valueOf(usedCapacity));
            JSONObject result = new JSONObject();
            result.put("data", data);
            result.put("msg", FileCode.SUCCESS.getText());
            result.put("code", "200");
            result.put("status", "success");
            return result.toString();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.GET_DATA_FAIL.getValue(), FileCode.GET_DATA_FAIL.getText());
        }
    }

    /**
     * 鑾峰彇瀹㈡埛鍓╀綑鐨勬枃浠舵€诲ぇ灏�
     *
     * @param request 璇锋眰
     * @return 缁撴灉
     */
    @RequestMapping(value = "/find-client-file-residue-capacity/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String findClientFileResidueCapacity(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }

            long residueCapacity = fileManagerService.findClientFileResidueCapacity(fse.getString("client_uuid"));
            JSONObject data = new JSONObject();
            data.put("residue_capacity", String.valueOf(residueCapacity));
            JSONObject result = new JSONObject();
            result.put("data", data);
            result.put("msg", FileCode.SUCCESS.getText());
            result.put("code", "200");
            result.put("status", "success");
            return result.toString();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.GET_DATA_FAIL.getValue(), FileCode.GET_DATA_FAIL.getText());
        }
    }

    /**
     * 楠岃瘉鏄惁鍏佽涓婁紶鐨勬枃浠剁被鍨�
     *
     * @param request 璇锋眰
     * @return 缁撴灉
     */
    @RequestMapping(value = "/check-is-allowed-file-type/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String checkIsAllowedFileType(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }

            boolean f = fileManagerService.checkIsAllowedFileType(fse.getString("attachment_name"));
            return f ? this.OK() : this.error(FileCode.CHECK_FAIL.getValue(), FileCode.CHECK_FAIL.getText());
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.CHECK_FAIL.getValue(), FileCode.CHECK_FAIL.getText());
        }
    }

    /**
     * 鑾峰彇鍘熷鍩熷悕
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/find-source-domain/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String findSourceDomain() {
        try {
            String sourceDomain = fileManagerService.findSourceDomain();

            JSONObject data = new JSONObject();
            data.put("source_domain", sourceDomain);
            JSONObject result = new JSONObject();
            result.put("data", data);
            result.put("msg", FileCode.SUCCESS.getText());
            result.put("code", "200");
            result.put("status", "success");
            return result.toString();
        } catch (Exception e) {

            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.FIND_SOURCE_DOMAIN_FAIL.getValue(), FileCode.FIND_SOURCE_DOMAIN_FAIL.getText());
        }
    }

    /**
     * 鎵嬪姩瑙﹀彂鏃犵敤鏁版嵁娓呯┖
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/clear-no-used-data/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String clearNoUsedData() {
        try {
            boolean reuslt = fileManagerService.autoClearNoUsedData();
            JSONObject result = new JSONObject();
            result.put("msg", FileCode.SUCCESS.getText());
            result.put("code", "200");
            result.put("status", reuslt);
            return result.toString();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.CLEAR_NO_USED_DATA_FAIL.getValue(), FileCode.CLEAR_NO_USED_DATA_FAIL.getText());
        }
    }


    /**
     * 鏂囦欢鍒櫎
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete-file/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String deleteFile(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }
            return BaseUtil.success(fileManagerService.delFiles(fse), null);
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.CLEAR_NO_USED_DATA_FAIL.getValue(), FileCode.CLEAR_NO_USED_DATA_FAIL.getText());
        }
    }


    /**
     * 涓婁紶鏂囦欢
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/upload-file/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String uploadFile(HttpServletRequest request) {
        try {
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            FieldSetEntity fieldSetEntity = fileManagerService.uploadFile(rpe);
            return OK_List(fieldSetEntity);
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.UPLOAD_FILE_FAIL.getValue(), FileCode.UPLOAD_FILE_FAIL.getText());
        }
    }
    /**
     * 涓嬭浇鏂囦欢鎴栬€呭湪绾块瑙�
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/get-file-content/{version}", method = RequestMethod.GET)
    @ApiVersion(1)
    public String getFileContents(HttpServletRequest request, HttpServletResponse response) {
        try {
            FieldSetEntity fse = null;
            String uuid = request.getParameter(CoreConst.UUID);
            String onlineView = request.getParameter(CmnConst.NEED_ONLINE_VIEW);
           
            if (StringUtils.isEmpty(uuid)) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }
            fse=new FieldSetEntity();
            fse.setTableName(CmnConst.PRODUCT_SYS_ATTACHMENTS);
            fse.setValue(CoreConst.UUID, uuid);
            fse.setValue(CmnConst.NEED_ONLINE_VIEW, onlineView);
            SpringMVCContextHolder.getSystemLogger().info("閫氳繃GET璇锋眰鑾峰彇闄勪欢鍐呭");
            // 姝e紡浠g爜
            fileManagerService.getFileContent(fse, response);
            return OK();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.GET_FILE_CONTENT_FAIL.getValue(), FileCode.GET_FILE_CONTENT_FAIL.getText());
        }
    }
    /**
     * 涓嬭浇鏂囦欢鎴栬€呭湪绾块瑙�
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/get-file-content/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String getFileContent(HttpServletRequest request, HttpServletResponse response) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }
            // 姝e紡浠g爜
            fileManagerService.getFileContent(fse, response);
            /*===test-start===*/
//            String tempPath = fse.getString("tempPath");
//            File file = new File(tempPath);
//            OutputStream sos = new FileOutputStream(file);
//            fileManagerService.getFileContent(fse, sos);
//            sos.close();
            /*===test-start===*/
            return OK();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.GET_FILE_CONTENT_FAIL.getValue(), FileCode.GET_FILE_CONTENT_FAIL.getText());
        }
    }

    /**
     * 鎵归噺鎵撳寘涓嬭浇
     *
     * @return 缁撴灉
     */
    @RequestMapping(value = "/download-file-zip/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String downLoadFileZip(HttpServletRequest request, HttpServletResponse response) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
                return this.error(FileCode.FORM_NODATA.getValue(), FileCode.FORM_NODATA.getText());
            }

            response.setContentType("multipart/form-data");
            // 姝e紡浠g爜
            fileManagerService.downLoadFileZip(fse, response);

            /*===test-start===*/
//            String tempPath ="D:\\Desktop\\ccc.zip";
//            File file = new File(tempPath);
//            OutputStream sssos = new FileOutputStream(file);
//            fileManagerService.downLoadFileZip(fse, sssos);
//            sssos.close();
            /*===test-start===*/
            return OK();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.GET_FILE_CONTENT_FAIL.getValue(), FileCode.GET_FILE_CONTENT_FAIL.getText());
        }
    }
}