package com.org.hktshop.controller.K3Id;

import com.org.hktshop.K3Id.Base.K3idFactory;
import com.org.hktshop.controller.BaseController;
import com.org.hktshop.utils.excel.ExcelUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/k3id")
public class K3IdController extends BaseController {

    @PostMapping(value = "/buildId")
    @ApiOperation(value = "K3编码生成接口", notes = "K3编码生成接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "file文件", required = true)
    })
    public ResponseEntity<ByteArrayResource> importExcel(@RequestParam("file") MultipartFile file) {
        //批量导入数据
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            StringBuffer sb = new StringBuffer();
            //文件为空
            if (file.isEmpty()) return null;
            is = file.getInputStream();
            // 由数字和26个英文字母组成的字符串
            Workbook workBook = WorkbookFactory.create(is);
            Sheet sheet = workBook.getSheetAt(0);
            Row titleRow = sheet.getRow(0);
            int cols = titleRow.getLastCellNum();
            int rows = sheet.getLastRowNum() + 1;

            //获取标题
            List<String> keyWorlds = new ArrayList<>();
            for (int i = 0; i < cols; i++) {
                Cell c = titleRow.getCell(i);
                // 判断是否具有合并单元格
                String value = ExcelUtil.getCellValue(c);
                keyWorlds.add(value);
            }
            List<List<String>> listList = new ArrayList<>();
            listList.add(keyWorlds);
            for (int i = 1; i < rows; i++) {
                titleRow = sheet.getRow(i);
                String[] tempArr = new String[cols - 1];
                for (int j = 1; j < cols; j++) {
                    Cell c = titleRow.getCell(j);
                    String value = ExcelUtil.getCellValue(c);
                    tempArr[j - 1] = value;
                }
                String k3id = K3idFactory.DeCodeToK3(tempArr);
                List<String> tempList = new ArrayList<>();
                tempList.add(k3id);
                tempList.addAll(Arrays.asList(tempArr));
                listList.add(tempList);
            }

            //根据参数生成对应的excel模板
            HSSFWorkbook sheets = ExcelUtil.createBook(listList);
            bos = new ByteArrayOutputStream();
            sheets.write(bos);
            //excel字节码
            byte[] excelBytes = bos.toByteArray();
            //用时间做excel名
            String sheetName = "wj.xlsx";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment;fileName=" + sheetName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity.ok().headers(headers).contentLength(excelBytes.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new ByteArrayResource(excelBytes));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) bos.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
            try {
                if (is != null) is.close();
            } catch (IOException e) {
            }
        }
    }
}
