package com.mortals.xhx.common.utils;

import cn.hutool.core.io.FileUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.gentable.model.GentableColumnEntity;
import com.mortals.xhx.base.system.gentable.model.GentableEntity;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: zxfei
 * @date: 2021/10/11 21:40
 */
@Slf4j
public class ReadDoc {

    public static void main(String[] args) {
    }

    /**
     * 读取文档中表格
     *
     * @param file
     */
    public static List<GentableEntity> readWord(MultipartFile file) {
        List<GentableEntity> docTables = new ArrayList<>();
        try {
            // 处理docx格式 即office2007以后版本
            InputStream ins = FileMagic.prepareToCheckMagic(file.getInputStream());

            if (FileMagic.valueOf(ins) == FileMagic.OLE2) {
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(file.getInputStream());

                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator it = new TableIterator(range);
                while (it.hasNext()) {
                    List<GentableColumnEntity> columns = new ArrayList<GentableColumnEntity>();

                    Table table = it.next();
                    // XWPFTable table = (XWPFTable) next;
                    GentableEntity docTable = new GentableEntity();
                    TableRow firstRow = table.getRow(0);
                    TableCell firstTdCell = firstRow.getCell(0);
                    String firstStr = firstTdCell.text();
                    String[] split = firstStr.split("：");
                    if (split.length < 2) {
                        continue;
                    }

                    String tableName = split[1];
                    String[] vals = tableName.split("_");

                    if (tableName.toLowerCase().indexOf("yyyymmdd") != -1) {
                        docTable.setDividedTableType(1);
                    } else if (tableName.toLowerCase().indexOf("yyyyww") != -1) {
                        docTable.setDividedTableType(2);
                    } else if (tableName.toLowerCase().indexOf("yyyymm") != -1) {
                        docTable.setDividedTableType(3);
                    } else if (tableName.toLowerCase().indexOf("yyyy") != -1) {
                        docTable.setDividedTableType(4);
                    } else {
                        docTable.setDividedTableType(0);
                    }

                    if (vals[vals.length - 1].toLowerCase().startsWith("yyyy")) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < vals.length - 1; i++) {
                            sb.append(vals[i]);
                            if (i < vals.length - 2) {
                                sb.append("_");
                            }
                        }
                        tableName = sb.toString();
                    }

                    docTable.setTableName(tableName.trim());
                    docTable.setTableComment(split[0].replace("，表名", "").trim());
                    // System.out.println("这是第" + num + "个表的数据");

                    int rows = table.numRows();
                    //读取每一行数据,每一行为一列
                    for (int i = 2; i < rows; i++) {
                        GentableColumnEntity column = new GentableColumnEntity();
                        TableRow row = table.getRow(i);
                        //判断是否第一个列数据为空 如果为空 跳过
//                        if ("".equals(row.getCell(0).getText().trim())) {
//                            continue;
//                        }
                        //读取每一列数据
                        // List<TableCell> cells = row.getCell();
                        //列名
                        TableCell cell = row.getCell(1);
                        column.setColumnName(cell.text().trim());
                        //数据类型
                        cell = row.getCell(2);
                        column.setColumnType(cell.text().trim());
                        //是否必填
                        cell = row.getCell(3);
                        column.setIsRequired("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否主键
                        cell = row.getCell(4);
                        column.setIsPrimaryKey("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否自增
                        cell = row.getCell(5);
                        column.setIsIncrement("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否列表
                        cell = row.getCell(6);
                        column.setIsList("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否导入导出
                        cell = row.getCell(7);
                        column.setIsExport("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否查询
                        cell = row.getCell(8);
                        column.setIsQuery("是".equals(cell.text().trim()) ? 1 : 0);
                        //默认值
                        cell = row.getCell(9);
                        if (!ObjectUtils.isEmpty(cell.text().trim())) {
                            column.setDefaultValue(cell.text().trim());
                        } else {
                            column.setDefaultValue("");
                        }
                        //备注信息
                        cell = row.getCell(10);
                        column.setColumnComment(cell.text().trim());

                        columns.add(column);

                    }
                    docTable.setColumns(columns);
                    docTables.add(docTable);
                }
            } else if (FileMagic.valueOf(ins) == FileMagic.OOXML) {
                XWPFDocument xwpf = new XWPFDocument(file.getInputStream());//得到word文档的信息
                Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
                while (it.hasNext()) {
                    List<GentableColumnEntity> columns = new ArrayList<>();
                    XWPFTable table = it.next();
                    GentableEntity docTable = new GentableEntity();
                    XWPFTableRow firstRow = table.getRow(0);

                    XWPFTableCell firstTdCell = firstRow.getCell(0);
                    String firstStr = firstTdCell.getText();
                    String[] split = firstStr.split("：");
                    if (split.length < 2) {
                        continue;
                    }
                    String tableName = split[1];
                    String[] vals = tableName.split("_");
                    if (tableName.toLowerCase().indexOf("yyyymmdd") != -1) {
                        docTable.setDividedTableType(1);
                    } else if (tableName.toLowerCase().indexOf("yyyyww") != -1) {
                        docTable.setDividedTableType(2);
                    } else if (tableName.toLowerCase().indexOf("yyyymm") != -1) {
                        docTable.setDividedTableType(3);
                    } else if (tableName.toLowerCase().indexOf("yyyy") != -1) {
                        docTable.setDividedTableType(4);
                    } else {
                        docTable.setDividedTableType(0);
                    }

                    if (vals[vals.length - 1].toLowerCase().startsWith("yyyy")) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < vals.length - 1; i++) {
                            sb.append(vals[i]);
                            if (i < vals.length - 2) {
                                sb.append("_");
                            }
                        }
                        tableName = sb.toString();
                    }

                    docTable.setTableName(tableName.trim());
                    docTable.setTableComment(split[0].replace("，表名", "").trim());
                    // System.out.println("这是第" + num + "个表的数据");
                    List<XWPFTableRow> rows = table.getRows();
                    //读取每一行数据,每一行为一列
                    for (int i = 2; i < rows.size(); i++) {
                        GentableColumnEntity column = new GentableColumnEntity();
                        XWPFTableRow row = rows.get(i);
                        //判断是否第一个列数据为空 如果为空 跳过
//                        if ("".equals(row.getCell(0).getText().trim())) {
//                            continue;
//                        }
                        //读取每一列数据
                        List<XWPFTableCell> cells = row.getTableCells();
                        //列名
                        XWPFTableCell cell = cells.get(1);
                        column.setColumnName(cell.getText().trim());
                        //数据类型
                        cell = cells.get(2);
                        column.setColumnType(cell.getText().trim());
                        //是否必填
                        cell = cells.get(3);
                        column.setIsRequired("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否主键
                        cell = cells.get(4);
                        column.setIsPrimaryKey("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否自增
                        cell = cells.get(5);
                        column.setIsIncrement("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否列表
                        cell = cells.get(6);
                        column.setIsList("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否导入导出
                        cell = cells.get(7);
                        column.setIsExport("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否查询
                        cell = cells.get(8);
                        column.setIsQuery("是".equals(cell.getText().trim()) ? 1 : 0);
                        //默认值
                        cell = cells.get(9);
                        if (!ObjectUtils.isEmpty(cell.getText().trim())) {
                            column.setDefaultValue(cell.getText().trim());
                        } else {
                            column.setDefaultValue("");
                        }
                        //备注信息
                        cell = cells.get(10);
                        column.setColumnComment(cell.getText().trim());

                        columns.add(column);

                    }
                    docTable.setColumns(columns);
                    docTables.add(docTable);
                }
            } else {
                throw new AppException("当前未知文档类型");
            }
/*

            if (FileUtil.getSuffix(file.getOriginalFilename()).toLowerCase().endsWith("docx")) {
                XWPFDocument xwpf = new XWPFDocument(file.getInputStream());//得到word文档的信息
                Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
                while (it.hasNext()) {
                    List<GentableColumnEntity> columns = new ArrayList<>();
                    XWPFTable table = it.next();
                    GentableEntity docTable = new GentableEntity();
                    XWPFTableRow firstRow = table.getRow(0);

                    XWPFTableCell firstTdCell = firstRow.getCell(0);
                    String firstStr = firstTdCell.getText();
                    String[] split = firstStr.split("：");
                    if (split.length < 2) {
                        continue;
                    }
                    String tableName = split[1];
                    String[] vals = tableName.split("_");
                    if (tableName.toLowerCase().indexOf("yyyymmdd") != -1) {
                        docTable.setDividedTableType(1);
                    } else if (tableName.toLowerCase().indexOf("yyyyww") != -1) {
                        docTable.setDividedTableType(2);
                    } else if (tableName.toLowerCase().indexOf("yyyymm") != -1) {
                        docTable.setDividedTableType(3);
                    } else if (tableName.toLowerCase().indexOf("yyyy") != -1) {
                        docTable.setDividedTableType(4);
                    } else {
                        docTable.setDividedTableType(0);
                    }

                    if (vals[vals.length - 1].toLowerCase().startsWith("yyyy")) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < vals.length - 1; i++) {
                            sb.append(vals[i]);
                            if (i < vals.length - 2) {
                                sb.append("_");
                            }
                        }
                        tableName = sb.toString();
                    }

                    docTable.setTableName(tableName.trim());
                    docTable.setTableComment(split[0].replace("，表名", "").trim());
                    // System.out.println("这是第" + num + "个表的数据");
                    List<XWPFTableRow> rows = table.getRows();
                    //读取每一行数据,每一行为一列
                    for (int i = 2; i < rows.size(); i++) {
                        GentableColumnEntity column = new GentableColumnEntity();
                        XWPFTableRow row = rows.get(i);
                        //判断是否第一个列数据为空 如果为空 跳过
//                        if ("".equals(row.getCell(0).getText().trim())) {
//                            continue;
//                        }
                        //读取每一列数据
                        List<XWPFTableCell> cells = row.getTableCells();
                        //列名
                        XWPFTableCell cell = cells.get(1);
                        column.setColumnName(cell.getText().trim());
                        //数据类型
                        cell = cells.get(2);
                        column.setColumnType(cell.getText().trim());
                        //是否必填
                        cell = cells.get(3);
                        column.setIsRequired("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否主键
                        cell = cells.get(4);
                        column.setIsPrimaryKey("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否自增
                        cell = cells.get(5);
                        column.setIsIncrement("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否列表
                        cell = cells.get(6);
                        column.setIsList("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否导入导出
                        cell = cells.get(7);
                        column.setIsExport("是".equals(cell.getText().trim()) ? 1 : 0);
                        //是否查询
                        cell = cells.get(8);
                        column.setIsQuery("是".equals(cell.getText().trim()) ? 1 : 0);
                        //默认值
                        cell = cells.get(9);
                        if (!ObjectUtils.isEmpty(cell.getText().trim())) {
                            column.setDefaultValue(cell.getText().trim());
                        } else {
                            column.setDefaultValue("");
                        }
                        //备注信息
                        cell = cells.get(10);
                        column.setColumnComment(cell.getText().trim());

                        columns.add(column);

                    }
                    docTable.setColumns(columns);
                    docTables.add(docTable);
                }
            } else {
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(file.getInputStream());

                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator it = new TableIterator(range);
                while (it.hasNext()) {
                    List<GentableColumnEntity> columns = new ArrayList<GentableColumnEntity>();

                    Table table = it.next();
                    // XWPFTable table = (XWPFTable) next;
                    GentableEntity docTable = new GentableEntity();
                    TableRow firstRow = table.getRow(0);
                    TableCell firstTdCell = firstRow.getCell(0);
                    String firstStr = firstTdCell.text();
                    String[] split = firstStr.split("：");
                    if (split.length < 2) {
                        continue;
                    }

                    String tableName = split[1];
                    String[] vals = tableName.split("_");

                    if (tableName.toLowerCase().indexOf("yyyymmdd") != -1) {
                        docTable.setDividedTableType(1);
                    } else if (tableName.toLowerCase().indexOf("yyyyww") != -1) {
                        docTable.setDividedTableType(2);
                    } else if (tableName.toLowerCase().indexOf("yyyymm") != -1) {
                        docTable.setDividedTableType(3);
                    } else if (tableName.toLowerCase().indexOf("yyyy") != -1) {
                        docTable.setDividedTableType(4);
                    } else {
                        docTable.setDividedTableType(0);
                    }

                    if (vals[vals.length - 1].toLowerCase().startsWith("yyyy")) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < vals.length - 1; i++) {
                            sb.append(vals[i]);
                            if (i < vals.length - 2) {
                                sb.append("_");
                            }
                        }
                        tableName = sb.toString();
                    }

                    docTable.setTableName(tableName.trim());
                    docTable.setTableComment(split[0].replace("，表名", "").trim());
                    // System.out.println("这是第" + num + "个表的数据");

                    int rows = table.numRows();
                    //读取每一行数据,每一行为一列
                    for (int i = 2; i < rows; i++) {
                        GentableColumnEntity column = new GentableColumnEntity();
                        TableRow row = table.getRow(i);
                        //判断是否第一个列数据为空 如果为空 跳过
//                        if ("".equals(row.getCell(0).getText().trim())) {
//                            continue;
//                        }
                        //读取每一列数据
                        // List<TableCell> cells = row.getCell();
                        //列名
                        TableCell cell = row.getCell(1);
                        column.setColumnName(cell.text().trim());
                        //数据类型
                        cell = row.getCell(2);
                        column.setColumnType(cell.text().trim());
                        //是否必填
                        cell = row.getCell(3);
                        column.setIsRequired("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否主键
                        cell = row.getCell(4);
                        column.setIsPrimaryKey("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否自增
                        cell = row.getCell(5);
                        column.setIsIncrement("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否列表
                        cell = row.getCell(6);
                        column.setIsList("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否导入导出
                        cell = row.getCell(7);
                        column.setIsExport("是".equals(cell.text().trim()) ? 1 : 0);
                        //是否查询
                        cell = row.getCell(8);
                        column.setIsQuery("是".equals(cell.text().trim()) ? 1 : 0);
                        //默认值
                        cell = row.getCell(9);
                        if (!ObjectUtils.isEmpty(cell.text().trim())) {
                            column.setDefaultValue(cell.text().trim());
                        } else {
                            column.setDefaultValue("");
                        }
                        //备注信息
                        cell = row.getCell(10);
                        column.setColumnComment(cell.text().trim());

                        columns.add(column);

                    }
                    docTable.setColumns(columns);
                    docTables.add(docTable);
                }

            }
*/

        } catch (Exception e) {
            log.error("读取文档异常", e);
            throw new AppException(e.getMessage());
        }

        return docTables;
    }


    /**
     * 根据属性名设置属性值
     *
     * @param fieldName
     * @param object
     * @return
     */
    private void setFieldValueByFieldName(String fieldName, Object object, String value) {
        try {
            // 获取obj类的字节文件对象
            Class c = object.getClass();

            java.lang.reflect.Field f = c.getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(object, value);
        } catch (Exception e) {
            e.printStackTrace();
            //log.error(e.getMessage(), e);
        }
    }
}
