package com.xtd.project.assets.controller;

import com.xtd.common.utils.excel.ImportExcelUtil;
import com.xtd.framework.web.controller.BaseController;
import com.xtd.framework.web.domain.AjaxResult;
import com.xtd.project.assets.service.DbBulkImportService;
import com.xtd.project.assets.service.IDbAssetsStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

/**
 * 批量导入
 *
 * @author xtd
 * @date 2020-04-09
 */
@RestController
@RequestMapping("/assets/bulkimport")
public class DbBulkImportController extends BaseController {
    @Autowired
    private DbBulkImportService dbBulkImportService;

    /**
     * 描述：通过传统方式form表单提交方式导入excel文件
     *
     * @param request
     * @throws Exception
     */
    @PostMapping(value = "importExcel")
    public AjaxResult importExcel(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return AjaxResult.error("文件不存在！");
        }else{
            try {
                // 对读取Excel表格标题测试
                InputStream in = file.getInputStream();
                List<List<Object>> listob = ImportExcelUtil.getBankListByExcel(in, file.getOriginalFilename());
                //移除列名
                listob.remove(0);
                in.close();
                //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
                if (!StringUtils.isEmpty(listob)) {
                    dbBulkImportService.insertListData(listob);
                }
                return AjaxResult.success(listob);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("文件解析失败!");
            }
        }

    }
}
