UploadController.java 6.93 KB
package com.uccc.number.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.uccc.number.constants.NumberImportTaskStatus;
import com.uccc.number.domain.ImportPoolProgress;
import com.uccc.number.exception.ApiException;
import com.uccc.number.service.ImportService;
import com.uccc.number.util.ExcelUtil;
import com.uccc.pretty.common.Result;
import com.uccc.pretty.common.SystemLog;
import com.uccc.pretty.constants.ErrorCode;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
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.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.uccc.pretty.constants.ActionEnum.*;
import static com.uccc.pretty.constants.ResultEnum.RESULT_OK;

/**
 * @Author zhaochenqing
 * @Date 2021/11/8 1:05 PM
 * @Version 1.0
 */
@RestController
@RequestMapping("/number/")
public class UploadController {

    private Logger logger = LoggerFactory.getLogger(NumberController.class);

    @Autowired
    private ImportService importService;

    final private ExecutorService executorService = Executors.newFixedThreadPool(1);

    @PreDestroy
    public void destory() {
        executorService.shutdown();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result upload(@RequestParam("file") MultipartFile file,
                         @RequestParam String status, @RequestParam String ip, HttpServletRequest request) throws IOException, InvalidFormatException {
        int taskByStatus = importService.getTaskByStatus(1);
        if (taskByStatus > 0) {
            throw new ApiException(ErrorCode.FILEING_IS_UPLOAD);
        }
        if (file.isEmpty()) throw new ApiException(ErrorCode.FILE_IS_EMPTY);
        String filename = file.getOriginalFilename();
        if (!filename.endsWith(".xlsx")) throw new ApiException(ErrorCode.FILE_PREFIX_WRONG);

        int total = 0;
        Sheet sheet = null;
        InputStream inputStream = file.getInputStream();
        Workbook wb = WorkbookFactory.create(inputStream);
        sheet = wb.getSheetAt(0);
        wb.close();
        inputStream.close();
        if (sheet == null) {
            throw new ApiException(ErrorCode.FILE_IS_EMPTY);
        }
        total = this.collectTotal(sheet);
        if (total == 0) {
            return new Result().fail(ErrorCode.Export_DATA_NULL);
        }
//        if (total > 50000) {
//            throw new ApiException(ErrorCode.EXPORT_COUNT_OVERLOAD);
//        }

        //设置redis中导入进度
        String importKey = "import_" + UUID.randomUUID().toString() + "_xls";
        String fileName = file.getOriginalFilename();
        ImportPoolProgress importPoolProgress = new ImportPoolProgress(fileName, importKey, total);
        //redisTemplate.opsForValue().set(importKey, JSON.toJSONString(importSalescluePoolProgress));
        importPoolProgress.setStatus(NumberImportTaskStatus.NUMBER_TASK_RUN.getCode());
        importPoolProgress.setType(status);
        importService.saveImport(importPoolProgress);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", fileName);
        jsonObject.put("cts", System.currentTimeMillis());
        jsonObject.put("oldName", file.getOriginalFilename());
        jsonObject.put("status", status);
        String token = request.getHeader("token");
        String userId = JWT.decode(token).getAudience().get(0);
        jsonObject.put("seller", userId);

        final Sheet sheetThread = sheet;
        final String key = importKey;
        if ("putoff".equals(status))  {
            executorService.execute(() -> {
                importService.editImportNumber(sheetThread, key, 0, false, fileName);
            });
            SystemLog systemLog = new SystemLog(Long.parseLong(userId), XIAJIA_NUM_FILE.getMessage(), XIAJIA_NUM_FILE.getMessage(), new Date(), RESULT_OK.getMessage(), ip);
            importService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));

        } else if("puton".equals(status)) {
            executorService.execute(() -> {
                importService.editImportNumber(sheetThread, key, 2, false, fileName);
            });
            SystemLog systemLog = new SystemLog(Long.parseLong(userId), SHANGJIA_NUM_FILE.getMessage(), SHANGJIA_NUM_FILE.getMessage(), new Date(), RESULT_OK.getMessage(), ip);
            importService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        } else if("delete".equals(status)) {
            executorService.execute(() -> {
                importService.editImportNumber(sheetThread, key, null, true, fileName);
            });
            SystemLog systemLog = new SystemLog(Long.parseLong(userId), SHANGCHU_NUM_FILE.getMessage(), SHANGCHU_NUM_FILE.getMessage(), new Date(), RESULT_OK.getMessage(), ip);
            importService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        } else  {
            executorService.execute(() -> {
                // redisTemplate.opsForValue().set(import_salesclue_tenant, fileName);
                // redisTemplate.expire(import_salesclue_tenant, 5, TimeUnit.MINUTES);
                //异步执行excel导入
                importService.importNumber(sheetThread, key, jsonObject.toString());
                //redisTemplate.delete(import_salesclue_tenant);
            });
            SystemLog systemLog = new SystemLog(Long.parseLong(userId), EXPORT_NUM_FILE.getMessage(), EXPORT_NUM_FILE.getMessage(), new Date(), RESULT_OK.getMessage(), ip);
            importService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        }

        return new Result().success(importPoolProgress);
    }


    private int collectTotal(Sheet sheet) {
        int total = 0;
        //计算exce有效数据行
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            for (int i = 0; i < 5; i++) {
                String cellValue = ExcelUtil.getFromCell(row.getCell(i));
                if (!StringUtils.isEmpty(cellValue)) {
                    total++;
                    break;
                }
            }
        }
        return total;
    }
}