package com.mortals.xhx.common.utils;

import cn.hutool.core.io.FileUtil;
import com.mortals.xhx.base.system.gentable.model.GentableColumnEntity;
import com.mortals.xhx.base.system.gentable.model.GentableEntity;
import lombok.experimental.UtilityClass;
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.web.multipart.MultipartFile;

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

/**
 * @author: zxfei
 * @date: 2021/10/11 21:40
 */
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以后版本
            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<GentableColumnEntity>();
                    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.indexOf("yyyymmdd") != -1) {
                        docTable.setDividedTableType(3);
                    } else if (tableName.indexOf("yyyymm") != -1) {
                        docTable.setDividedTableType(2);
                    } else if (tableName.indexOf("yyyy") != -1) {
                        docTable.setDividedTableType(1);
                    } else {
                        docTable.setDividedTableType(0);
                    }

                    if (vals[vals.length - 1].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].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(0);
                        column.setColumnName(cell.getText().trim());
                        //备注说明
                        column.setColumnComment(cells.get(1).getText().trim() + "," + cells.get(4).getText().trim());
                        //物理类型
                        cell = cells.get(2);
                        column.setColumnType(cell.getText().trim());

                        //是否必填
                        cell = cells.get(3);
                        column.setIsRequired(cell.getText().trim() == "是" ? 1 : 0);

                        //是否列表
                        cell = cells.get(5);
                        column.setIsList(cell.getText().trim() == "是" ? 1 : 0);

                        //是否编辑
                        cell = cells.get(6);
                        column.setIsEdit(cell.getText().trim() == "是" ? 1 : 0);

                        //是否查询
                        cell = cells.get(7);
                        column.setIsQuery(cell.getText().trim() == "是" ? 1 : 0);
                        column.setIsPrimaryKey(0);
                        column.setIsIncrement(0);
                        if (column.getColumnComment().trim().indexOf("自增长") > -1) {
                            column.setIsIncrement(1);
                        }

                        if (column.getColumnComment().trim().indexOf("主键") > -1) {
                            column.setIsPrimaryKey(1);
                        }
                        columns.add(column);

                    }
                    docTable.setColumns(columns);
                    docTables.add(docTable);
                }
            } else {
                // 处理doc格式 即office2003版本
//                POIFSFileSystem pfs = new POIFSFileSystem(in);
//                HWPFDocument hwpf = new HWPFDocument(pfs);
//                Range range = hwpf.getRange();//得到文档的读取范围
//                TableIterator it = new TableIterator(range);
//                while (it.hasNext()) {
//                    List<DocTableModel> docTableModels = new ArrayList<DocTableModel>();
//
//                    Table tb =  it.next();
//
//                    DocTable docTable = new DocTable();
//
//                    TableRow firstRow = tb.getRow(0);
//
//                    TableCell firstTdCell = firstRow.getCell(0);
//
//                    Paragraph firstTdCellParagraph = firstTdCell.getParagraph(0);
//                    String firstStr = firstTdCellParagraph.text();
//                    //去除后面的特殊符号
//                    if (null != firstStr && !"".equals(firstStr)) {
//                        firstStr = firstStr.substring(0, firstStr.length() - 1);
//                    }
//                    String[] split = firstStr.split("：");
//                    docTable.setDataTableName(split[1]);
//
//                    //System.out.println("这是第" + num + "个表的数据");
//                    //迭代行，默认从0开始,可以依据需要设置i的值,改变起始行数，也可设置读取到那行，只需修改循环的判断条件即可
//                    for (int i = 1; i < tb.numRows(); i++) {
//                        DocTableModel docTableModel = new DocTableModel();
//                        TableRow tr = tb.getRow(i);
//
//                        if("".equals(tr.getCell(0).text().trim())){
//                            continue;
//                        }
//                        //迭代列，默认从0开始
//                        for (int j = 0; j < tr.numCells(); j++) {
//                            TableCell td = tr.getCell(j);//取得单元格
//                            //获取需要设置的属性名称
//                            String att = vars[j];
//
//                            //取得单元格的内容
//                            for (int k = 0; k < td.numParagraphs(); k++) {
//                                Paragraph para = td.getParagraph(k);
//                                String s = para.text();
//                                //去除后面的特殊符号
//                                if (null != s && !"".equals(s)) {
//                                    s = s.substring(0, s.length() - 1);
//                                }
//
//                                setFieldValueByFieldName(att, docTableModel, s);
//                            }
//                        }
//
//                        docTableModels.add(docTableModel);
//                    }
//                    docTable.setModelList(docTableModels);
//                    docTables.add(docTable);
//                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        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);
        }
    }
}
