package org.springblade.manager.controller;

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springblade.common.utils.MathUtil;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.core.tool.utils.IoUtil;
import org.springblade.core.tool.utils.ResourceUtil;
import org.springblade.manager.entity.WbsFormElement;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ExpaileHtml {
/*
    public static void main(String[] args) throws IOException {
        getHtmlInfo();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //String inHtmlUrl = "/Users/hongchuangyanfa/Desktop/123654.html";
       getjiexiInfo();
    }
*/






    public static void getjiexiInfo() throws IOException {
        String inHtmlUrl = "/Users/hongchuangyanfa/Desktop/123654.html";
        File file = ResourceUtil.getFile(inHtmlUrl);
        FileInputStream inputStream = new FileInputStream(file);
        String htmlString =   IoUtil.readToString(inputStream);

        // 获取比对数据
        List<WbsFormElement> dataList = getWbsInfo();

        String dataInfox = dataList.stream().map(WbsFormElement::getEName).collect(Collectors.joining(","));

        System.out.println(dataInfox);
        Document doc = Jsoup.parse(htmlString);
        Element table = doc.select("table").first();
        Elements trs = table.select("tr");


        // 标题坐标
        List<Map<String,String>> zikey = new ArrayList<>();

        int index_id = 0;
        // 循环解析
        for(int i = 0 ;i < trs.size() ;i++) {
            Element tr = trs.get(i);
            boolean index_stat = Boolean.parseBoolean(tr.attr("index_stat"));

            if(index_stat && index_id==0){
                index_id = 1;
                zikey = new ArrayList<>();
            }

            if(!index_stat && index_id==1 && zikey.size()>=1){
                index_id = 2;
                zikey = new ArrayList<>();
            }

            Elements tds = tr.select("td");
            for (int j = 0; j < tds.size(); j++) {
                Element data = tds.get(j);
                String textInfo  = data.text();
                int x1 = Integer.parseInt( data.attr("x1"));
                int x2 = Integer.parseInt( data.attr("x2"));
                int y1 = Integer.parseInt( data.attr("y1"));
                int y2 = Integer.parseInt( data.attr("y2"));


                if(!textInfo.isEmpty() && !textInfo.equals("/")){
                    Map<String,String> dataInfo =new HashMap<String,String>();
                    dataInfo.put("name",textInfo);
                    dataInfo.put("x1",data.attr("x1"));
                    dataInfo.put("x2",data.attr("x2"));
                    dataInfo.put("y1",data.attr("y1"));
                    dataInfo.put("y2",data.attr("y2"));
                    zikey.add(dataInfo);
                }else if(data.html().indexOf("input")>=0){

                    List arrayList = new ArrayList<>();


                    for(int k=zikey.size()-1;k>=0 ;k--){
                        String name = zikey.get(k).get("name").replaceAll("[^\u4E00-\u9FA5]", "");
                        int xx1 = Integer.parseInt( zikey.get(k).get("x1"));
                        int xx2 = Integer.parseInt( zikey.get(k).get("x2"));
                        int yy1 = Integer.parseInt( zikey.get(k).get("y1"));
                        int yy2 = Integer.parseInt( zikey.get(k).get("y2"));

                        // 左匹配
                        if( yy1<=y1 && yy2>=y2 && xx2<x1 && StringUtils.isNotEmpty(name)){
                             arrayList.add(name);
                            if(!index_stat){
                                break;
                            }
                        }

                        //向 上 匹配
                        if(index_stat){
                            if( xx1<=x1 && xx2 >=x2 && yy2<y1 ){
                                arrayList.add(name);
                            }
                        }
                    }

                    Set<String> resultSet = new HashSet<>();
                    System.out.println(dataInfox+"==="+arrayList.size());
                    MathUtil.getCombination(arrayList, resultSet);
                    double maxInfo = 0;
                    if(!resultSet.isEmpty()){

                        for(WbsFormElement wbsFormElement : dataList){
                            for(String bx : resultSet){
                                double dataxx =  MathUtil.sim(bx,wbsFormElement.getEName());
                                if(maxInfo < dataxx){
                                    System.out.println("x1-x2="+x1+","+x2+"y1-y2="+y1+","+y2+bx+"="+dataxx+"_jieh="+resultSet);
                                    data.empty().text(bx);
                                    maxInfo = dataxx;
                                }
                            }
                        }
                    }
                    System.out.println(maxInfo);
                }
            }
        }


        //
       // for (Map<String,String> d:zikey){
           // System.out.println(d.get("name")+"x1"+d.get("x1"));
      //  }

        inputStream.close();

        File writefile = new File(inHtmlUrl);
        FileUtil.writeToFile(writefile, doc.html(), Boolean.parseBoolean("UTF-8"));
        System.out.println("完成");
    }


    public static List<WbsFormElement> getWbsInfo(){
        List<WbsFormElement> elementList = new ArrayList<>();
        WbsFormElement info = new WbsFormElement();
        info.setEName("承包单位");

        WbsFormElement info1 = new WbsFormElement();
        info1.setEName("工程名称");

        WbsFormElement info2 = new WbsFormElement();
        info2.setEName("年月日");

        WbsFormElement info3 = new WbsFormElement();
        info3.setEName("隧道净高实测");

        WbsFormElement info4 = new WbsFormElement();
        info3.setEName("基坑尺寸设计值");


        elementList.add(info);
        elementList.add(info1);
        elementList.add(info2);
        elementList.add(info3);

        return elementList;
    }

    public static void getHtmlInfo() throws IOException {
        String thmlUrl = "/Users/hongchuangyanfa/Desktop/1539066383856304128.html";

        File file = new File("/Users/hongchuangyanfa/Desktop/test001231.xlsx");

        FileInputStream inputStream = new FileInputStream(file);
        // 解析excel
        Workbook wb = new Workbook();
        wb.loadFromMHtml(inputStream);
        //获取工作表
        Worksheet sheet = wb.getWorksheets().get(0);
        sheet.saveToHtml(thmlUrl);

        // 测试
        File file1 = ResourceUtil.getFile(thmlUrl);
        String htmlString =  IoUtil.readToString(new FileInputStream(file1));

        // 样式集合
        Map<String ,String > styleMap = new HashMap<>();
        // 解析 style
        Document doc = Jsoup.parse(htmlString);
        Element style = doc.select("style").first();

        Matcher cssMatcher = Pattern.compile("(\\w+)\\s*[{]([^}]+)[}]").matcher(style.html());
        while (cssMatcher.find()) {
            styleMap.put(cssMatcher.group(1),cssMatcher.group(2));
        }
        // 解析 总行和总列
        Element table = doc.select("table").first();
        Elements trs = table.select("tr");

        // 获取总行列数
        int maxCol = doc.select("Col").size();
        String [] rowData = new String[trs.size()+1];

        int s_index = 0;
        boolean index_stat = false;
        // 横向计算
        for(int i = 0 ;i < trs.size() ;i++) {
            Element tr = trs.get(i);
            Elements tds = tr.select("td");

            int x_width = 0 ;
            int y_width = 0 ;
            //区域计算
            for (int j = 0; j < tds.size(); j++) {
                Element data = tds.get(j);
                String keyId = data.attr("class");

                int colspan = data.attr("COLSPAN").equals("") ? 1 : Integer.parseInt(data.attr("COLSPAN"));
                String classInfo = styleMap.get(keyId);
                data.removeAttr("class");
                data.attr("style",styleMap.get(keyId).replaceAll("break-word","inherit"));
                // 第一列
                if(j==0 && classInfo.indexOf("border-left-style")>=0 && classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")>=0 && !index_stat){
                    x_width +=colspan;
                }else if(j == tds.size()-1 && classInfo.indexOf("border-right-style")>=0 && classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")>=0 && !index_stat && j>=1){
                    x_width +=colspan;
                }else if(classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")>=0 && !index_stat && j>=1){
                    x_width +=colspan;
                }

                // 计算退出
                if(j==0 && classInfo.indexOf("border-left-style")<0 && classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")<0 && index_stat && classInfo.indexOf("border-right-style")<0){
                    y_width +=colspan;
                }else if(j == tds.size()-1 && classInfo.indexOf("border-right-style")<0 && classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")<0 && index_stat && j>=1){
                    y_width +=colspan;
                }else if(classInfo.indexOf("border-top-style")>=0 && classInfo.indexOf("border-bottom-style")<0 &&index_stat && j>=1){
                    y_width +=colspan;
                }
            }

            if(x_width == maxCol && !index_stat && s_index==0){
                s_index = i + 1;
                index_stat = true ;
            }

            if(y_width == maxCol && index_stat && s_index>0){
                s_index = i + 1;
                index_stat = false ;
            }
            tr.attr("index_stat",index_stat+"");

            int x= 0;
            for (int j = 0; j < tds.size(); j++) {
                Element data = tds.get(j);

                int colspan = data.attr("COLSPAN").equals("") ? 0 : Integer.parseInt(data.attr("COLSPAN"));
                int rowspan = data.attr("ROWSPAN").equals("") ? 0 : Integer.parseInt(data.attr("ROWSPAN"));

                Map<String, String> textObject = new HashMap<>();
                // 计算
                int x1 =0;
                int x2 =0;
                int y1 =0;
                int y2 =0;
                //x
                // X 坐标
                if(colspan==0){
                    x1 = x+1;
                    x2 = x+1;
                    x= x +1;
                }else{
                    x1 = x+1;
                    x2 = x+colspan;
                    x = x+colspan;
                }
                String textInfo = data.text().trim();

                // y 坐标
                y1=i+1;
                if(rowspan==0){
                    y2 = i+1;
                }else{
                    y2 = i+rowspan;
                    for(int k=0;k<rowspan-1;k++){
                        String dataInfo = rowData[k+2+i];
                        if(dataInfo==null){
                            dataInfo = x1+":"+x2;
                        }else{
                            String [] dataInfo2 = dataInfo.split(",");
                            String dataInfo3 = dataInfo2[dataInfo2.length-1];
                            int mx1 = Integer.parseInt(dataInfo3.split(":")[0]);
                            int mx2 = Integer.parseInt(dataInfo3.split(":")[1]);
                            if(mx2+1==x1){
                                dataInfo = dataInfo+","+mx1+":"+x2;
                            }else{
                                dataInfo = dataInfo+","+x1+":"+x2;
                            }
                        }
                        rowData[k+2+i] = dataInfo;
                    }
                }

                String getRowInfo = rowData[y1];
                if(getRowInfo!=null){
                    String [] dataInfo2 = getRowInfo.split(",");
                    if(getRowInfo.indexOf("1")>=0 && j==0){
                        for(int m =0;m<dataInfo2.length ;m++){
                            int mx1 = Integer.parseInt(dataInfo2[m].split(":")[0]);
                            int mx2 = Integer.parseInt(dataInfo2[m].split(":")[1]);
                            x = mx2;
                        }
                        x1 = x+x1;
                        x2 = x+x2;
                        x = x+1 ; //计算自己
                    }else{
                        for(int m =0;m<dataInfo2.length ;m++){
                            int mx1 = Integer.parseInt(dataInfo2[m].split(":")[0]);
                            int mx2 = Integer.parseInt(dataInfo2[m].split(":")[1]);
                            if(x2+1 == mx1){
                                x = mx2 ;
                            }
                        }
                    }
                }


               // System.out.println(StringUtil.trimAllWhitespace(textInfo)+""+StringUtil.trimAllWhitespace(textInfo).length());
                data.text(textInfo.replaceAll(" ",""));


                // 设置td 属性
                data.attr("trIndex",i+"");
                data.attr("tdIndex",j+"");
                data.attr("x1",x1+"");
                data.attr("x2",x2+"");
                data.attr("y1",y1+"");
                data.attr("y2",y2+"");



                // 设置文本信息
               /* if(textInfo.indexOf("年")>=0 && textInfo.indexOf("月")>=0&& textInfo.indexOf("日")>=0){
                    data.empty().append("<input type='time' style='width:100%;height:100%' placeholder=''> </input>");
                }*/
                if(textInfo.isEmpty() || textInfo.equals("/") || textInfo.equals("—") || textInfo.equals("—") || textInfo.equals("-")){
                    if(index_stat){
                        data.empty().append("<input type='text' style='width:100%;height:100%' placeholder=''> </input>");
                    }else{
                        if(j==0 ){
                            if(colspan ==maxCol && i>=1 && i<=2){
                                data.empty().append("<input type='text' style='width:100%;height:100%' placeholder=''> </input>");
                            }
                        }else{
                            Element bforData = tds.get(j-1);
                            if(!bforData.text().isEmpty()){
                                data.empty().append("<input type='text' style='width:100%;height:100%' placeholder=''> </input>");
                            }
                        }
                    }
                }
            }
        }

        // 写入
        inputStream.close();
        String inHtmlUrl = "/Users/hongchuangyanfa/Desktop/123654.html";
        //saveAsFileWriter(doc.html(),inHtmlUrl);
        File writefile = new File(inHtmlUrl);
        FileUtil.writeToFile(writefile, doc.html(), Boolean.parseBoolean("UTF-8"));
    }
}
