package pwc.taxtech.atms.controller;

import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.common.message.ErrorMessage;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.datainit.DataInitDto;
import pwc.taxtech.atms.dto.datainit.DataInitMsgDto;
import pwc.taxtech.atms.exception.ApplicationException;
import pwc.taxtech.atms.service.impl.DataInitServiceImpl;
import pwc.taxtech.atms.service.impl.FileService;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("api/v1/init")
public class DataInitController {

    private static final Logger logger = LoggerFactory.getLogger(DataInitController.class);

    @Autowired
    private FileService fileService;
    @Autowired
    private DataInitServiceImpl dataInitService;

//    @ApiOperation(value = "Download basic data initialization template")
    @RequestMapping(value = {"/downloadTemplate"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void downloadTemplate(HttpServletResponse response) {

        String filePath;
        File templateFile = null;
        InputStream inputStream = null;
        try {
            filePath = EnterpriseAccountManagerController.class.getClassLoader().getResource("").toURI().getPath();
            templateFile = new File(filePath + CommonConstants.BasicDataTemplate);
            inputStream = new BufferedInputStream(new FileInputStream(templateFile));
            String customFileName = CommonConstants.BasicDataFileName + DateTime.now().toString("yyyyMMddHHmmss") + ".xlsx";//客户端保存的文件名
            response.setHeader("Content-Disposition", String.format("inline; filename=\"" + customFileName + "\""));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        } catch (FileNotFoundException e) {
            logger.error("Template file not found. Template file should be located at " + CommonConstants.BasicDataTemplate);
            throw new ApplicationException("Tempate file not found.");
        } catch (Exception e) {
            logger.error("Error downloading template file " + CommonConstants.BasicDataFileName + ".xlsx", e);
            throw new ApplicationException("Error downloading template file " + CommonConstants.BasicDataFileName + ".xlsx", e);
        } finally {
            try {
                templateFile = null;
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("Error closing inputstream. ", e);
            } finally {
                inputStream = null;
            }
        }
    }

//    @ApiOperation(value = "Upload initial data")
    @RequestMapping(value = {"/Upload"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    Object uploadInitData(@RequestParam String action,
                          @RequestParam(value = "file", required = false) CommonsMultipartFile inputFile) {

        if (inputFile == null || inputFile.getSize() <= 0) {
            return new OperationResultDto<>(false, ErrorMessage.NoFile);
        }

        logger.debug("file name: " + inputFile.getOriginalFilename());
        InputStream inputStream = null;
        try {
            inputStream = inputFile.getInputStream();
        } catch (IOException e) {
            throw Lang.wrapThrow(e);
        }

        //save file
        String filePath = FileUtils.getTempDirectory().getAbsolutePath() + File.separator + "DataInit" + File.separator
                + CommonUtils.getUUID() + "_" + inputFile.getOriginalFilename();
        logger.debug("Saving excel to {}", filePath);
        OperationResultDto<Object> saveResult = fileService.saveFile(inputStream, filePath);
        if (saveResult.getResult() != null && !saveResult.getResult()) {
            return saveResult;
        }


        DataInitDto dataInitDto = dataInitService.validateAndImportInitData(filePath);
        DataInitMsgDto dataMsgDto = new DataInitMsgDto();
        dataMsgDto.setErrorMsg(dataInitDto.getErrorMsgs());
        dataMsgDto.setValidMsg(dataInitDto.getValidMsgs());

        return dataMsgDto;
    }
}