package com.trs.web2frame.util;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by 1250052380@qq.com on 2015/5/19.
 */
public class ViewExportExcelPoi {
    private static String XMLFilePath="C:\\Users\\esint007\\Downloads\\ST20200326508281317132.xml";
    private static String EXCELFilePath="D:\\work\\ViewInfo.xlsx";

    public static void main(String[] args) throws JDOMException, IOException {
        //String xml="<?xml version=\"1.0\" encoding=\"utf-8\" ?><MoBaoAccount MessageType=\"UserMobilePay\" PlatformID=\"b2ctest\"><OrderNo>M20150521084825</OrderNo><TradeAmt>5000.00</TradeAmt><Commission>0.5</Commission><UserID>zhuxiaolong</UserID><MerchID>zhuxiaolong1</MerchID><tradeType>0</tradeType><CustParam>123</CustParam> <NotifyUrl>http://mobaopay.com/callback.do</NotifyUrl><TradeSummary>订单</TradeSummary></MoBaoAccount>";
        String  xml=readTxtFile(XMLFilePath);
        JSONObject json=xml2JSON(xml.getBytes());
        //System.out.println(json.toJSONString());
        ViewToExcel(json.toJSONString());


    }

    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }

/**
 * 读取文件内容
 * @param filePath
 * @return
 */
    public static String readTxtFile(String filePath){
        StringBuilder sb = new StringBuilder();
        try {
                String encoding="UTF-8";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        //System.out.println(lineTxt);
                        sb.append(lineTxt.trim());
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return sb.toString();
      
    }



    public static void ViewToExcel(String jsonStr){
        
        try {
             // 创建一个工作簿
            // WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
            // WritableSheet sheet0 = workbook.createSheet("视图情况概览",0);
            // 创建工作薄
            XSSFWorkbook wb = new XSSFWorkbook();
                        // sheet1
            XSSFSheet sheet0 = wb.createSheet("视图情况概览");
            sheet0.createRow(0).createCell(0).setCellValue("自建视图名称");
            sheet0.createRow(0).createCell(0).setCellValue("对应标准表名");
            // sheet0.addCell(new Label(0,0,"自建视图名称"));
            // sheet0.addCell(new Label(1,0,"对应标准表名"));
            JSONObject jsonObject=JSONObject.parseObject(jsonStr);
            String XWCMTABLEINFOS=jsonObject.get("XWCMTABLEINFOS").toString();
            String XWCMTABLEINFO=JSONObject.parseObject(XWCMTABLEINFOS).get("XWCMTABLEINFO").toString();
            JSONArray array_XWCMTABLEINFO=JSONArray.parseArray(XWCMTABLEINFO);
            //循环各个元数据下的视图
            int row=0;
            for (int i = 0; i < array_XWCMTABLEINFO.size(); i++) {
                String str_XWCMVIEWINFOS =JSONObject.parseObject(array_XWCMTABLEINFO.get(i).toString()).get("XWCMVIEWINFOS").toString();
                String str_XWCMVIEWINFO=JSONObject.parseObject(JSONArray.parseArray(str_XWCMVIEWINFOS).get(0).toString()).getString("XWCMVIEWINFO");//
                JSONArray arr_XWCMVIEWINFO=JSONArray.parseArray(str_XWCMVIEWINFO);
                //循环该元数据下的视图信息
                for (int j = 0; j < arr_XWCMVIEWINFO.size(); j++) {
                    String str_ViewPROPERTIES =JSONObject.parseObject(arr_XWCMVIEWINFO.get(j).toString()).get("PROPERTIES").toString();
                    String VIEWDESC=JSONObject.parseObject(JSONArray.parseArray(str_ViewPROPERTIES).get(0).toString()).getString("VIEWDESC");//获取视图名称
                    VIEWDESC=VIEWDESC.substring(2, VIEWDESC.lastIndexOf("]")-1);
                    row++;
                    //sheet0.addCell(new Label(0,row0,VIEWDESC));
                    // 创建一个工作表
                    //WritableSheet sheet = workbook.createSheet(VIEWDESC,j+1);//根据视图名称创建sheet
                    XSSFSheet sheet = wb.createSheet(VIEWDESC);
                    XSSFRow row0= sheet.createRow(0);
                    sheet0.createRow(row).createCell(0).setCellValue(VIEWDESC);
                    // sheet.addCell(new Label(0,0,"英文名称"));
                    // sheet.addCell(new Label(1,0,"数据类型"));
                    // sheet.addCell(new Label(2,0,"字段类型"));
                    // sheet.addCell(new Label(3,0,"字段长度"));
                    // sheet.addCell(new Label(4,0,"中文名称"));

                    row0.createCell(0).setCellValue("英文名称");
                    row0.createCell(1).setCellValue("数据类型");
                    row0.createCell(2).setCellValue("字段类型");
                    row0.createCell(3).setCellValue("字段长度");
                    row0.createCell(4).setCellValue("中文名称");
                    //System.out.println(VIEWDESC);
                    String XWCMVIEWFIELDINFOS =JSONObject.parseObject(arr_XWCMVIEWINFO.get(j).toString()).get("XWCMVIEWFIELDINFOS").toString();
                    String str_XWCMVIEWFIELDINFO =JSONObject.parseObject(JSONArray.parseArray(XWCMVIEWFIELDINFOS).get(0).toString()).getString("XWCMVIEWFIELDINFO");//
                    JSONArray arr_XWCMVIEWFIELDINFO=JSONArray.parseArray(str_XWCMVIEWFIELDINFO);
                    for (int k = 0; k < arr_XWCMVIEWFIELDINFO.size(); k++) {
                        String str_FIELDPROPERTIES =JSONObject.parseObject(arr_XWCMVIEWFIELDINFO.get(k).toString()).get("PROPERTIES").toString();
                        String DBFIELDNAME =JSONObject.parseObject(JSONArray.parseArray(str_FIELDPROPERTIES).get(0).toString()).getString("DBFIELDNAME");//获取视图中字段英文名称
                        String DBTYPE =JSONObject.parseObject(JSONArray.parseArray(str_FIELDPROPERTIES).get(0).toString()).getString("DBTYPE");//数据类型
                        String FIELDTYPE  =JSONObject.parseObject(JSONArray.parseArray(str_FIELDPROPERTIES).get(0).toString()).getString("FIELDTYPE");//字段类型
                        String DBLENGTH =JSONObject.parseObject(JSONArray.parseArray(str_FIELDPROPERTIES).get(0).toString()).getString("DBLENGTH");//数据长度
                        String ANOTHERNAME=JSONObject.parseObject(JSONArray.parseArray(str_FIELDPROPERTIES).get(0).toString()).getString("ANOTHERNAME");//获取视图中字段中文名称

                        DBFIELDNAME=DBFIELDNAME.substring(2, DBFIELDNAME.lastIndexOf("]")-1);
                        DBTYPE=DBTYPE.substring(2, DBTYPE.lastIndexOf("]")-1);
                        FIELDTYPE =FIELDTYPE.substring(2, FIELDTYPE.lastIndexOf("]")-1);
                        DBLENGTH=DBLENGTH.substring(2, DBLENGTH.lastIndexOf("]")-1);
                        ANOTHERNAME=ANOTHERNAME.substring(2, ANOTHERNAME.lastIndexOf("]")-1);
                        System.out.println(DBFIELDNAME+" "+DBTYPE+" "+DBLENGTH+" "+ANOTHERNAME);
                        // sheet.addCell(new Label(0,k+1,DBFIELDNAME));
                        // sheet.addCell(new Label(1,k+1,retDBTYPEMeaning(DBTYPE)));
                        // sheet.addCell(new Label(2,k+1,retFieldMeaning(FIELDTYPE)));
                        // sheet.addCell(new Label(3,k+1,DBLENGTH));
                        // sheet.addCell(new Label(4,k+1,ANOTHERNAME));
                        XSSFRow rowk= sheet.createRow(k+1);
                        rowk.createCell(0).setCellValue(DBFIELDNAME);
                        rowk.createCell(1).setCellValue(DBTYPE);
                        rowk.createCell(2).setCellValue(FIELDTYPE);
                        rowk.createCell(3).setCellValue(DBLENGTH);
                        rowk.createCell(4).setCellValue(ANOTHERNAME);
                        
                    }
                    
                }
                
            }
           //检查当前要导出的excel文件是否存在 ，存在就删除。  
           File file = new File(EXCELFilePath);  
           if (file.exists()) {  
               file.delete();  
           }  
           // 新建一输出文件流  
           FileOutputStream fOut = new FileOutputStream(EXCELFilePath);  
           //OutputStream os = new FileOutputStream(EXCELFilePath);
           // 把相应的Excel 工作簿
           wb.write(fOut);
           //wb.close();
           fOut.flush();  
           // 操作结束，关闭文件  
           fOut.close();  
            //System.out.println(XWCMTABLEINFO);
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("ViewToExcel异常！："+e.getMessage());
        }
    }

    /**
     * 返回数据类型含义
     * @param DBTYPE
     * @return
     */
    public static String retDBTYPEMeaning(String DBTYPE){
        switch (DBTYPE) {
            case "4":{
                DBTYPE="tinyint";
                break;
            }
            case "5":{
                DBTYPE="smallint";
                break;
            }
            case "6":{
                DBTYPE="float";
                break;
            }
            case "8":{
                DBTYPE="double";
                break;
            }
            case "12":{
                DBTYPE="varchar";
                break;
            }
            case "93":{
                DBTYPE="datetime";
                break;
            }
            case "2005":{
                DBTYPE="longtext";
                break;
            }
            default:
                break;
        }
        return DBTYPE;
    }

    /**
     * 返回字段类型含义
     * @param FieldType
     * @return
     */
    public static String retFieldMeaning(String FieldType){
        switch (FieldType) {
            
            case "1":{
                FieldType="自定义类型";
                break;
            }
            case "2":{
                FieldType="密码文本";
                break;
            }
            case "3":{
                FieldType="普通文本";
                break;
            }
            case "4":{
                FieldType="多行文本";
                break;
            }
            case "5":{
                FieldType="是非框";
                break;
            }
            case "6":{
                FieldType="单选钮";
                break;
            }
            case "7":{
                FieldType="下拉列表";
                break;
            }
            case "8":{
                FieldType="附件";
                break;
            }
            
            case "9":{
                FieldType="多选";
                break;
            }
            case "10":{
                FieldType="分类法";
                break;
            }
            
            case "11":{
                FieldType="日期";
                break;
            }
            case "12":{
                FieldType="隐藏大字段内容";
                break;
            }
            case "14":{
                FieldType="相关文档";
                break;
            }
            
            case "15":{
                FieldType="可输入下拉列表";
                break;
            }
            case "17":{
                FieldType="可输入提示下拉列表";
                break;
            }
            
            case "18":{
                FieldType="链接";
                break;
            }
            case "20":{
                FieldType="视频";
                break;
            }
            case "21":{
                FieldType="视频直播";
                break;
            }
            case "22":{
                FieldType="Google地图";
                break;
            }
            case "23":{
                FieldType="栏目选择树";
                break;
            }
            
            case "24":{
                FieldType="Baidu地图";
                break;
            }
            case "29":{
                FieldType="关键词";
                break;
            }
            case "31":{
                FieldType="相关新闻";
                break;
            }
            case "32":{
                FieldType="相关图片";
                break;
            }
            case "35":{
                FieldType="标题";
                break;
            }
            case "34":{
                FieldType="摘要";
                break;
            }
            case "39":{
                FieldType="短标题";
                break;
            }
            case "40":{
                FieldType="隐藏字段";
                break;
            }
            case "42":{
                FieldType="微信、APP样式图片（隐藏）";
                break;
            }
            case "43":{
                FieldType="隐藏大字段";
                break;
            }
            
            case "44":{
                FieldType="复杂编辑器";
                break;
            }
            case "45":{
                FieldType="隐藏整数内容";
                break;
            }
            case "46":{
                FieldType="来源";
                break;
            }
            case "48":{
                FieldType="简易编辑器";
                break;
            }
            
            case "49":{
                FieldType="日期（精确到天）";
                break;
            }
            case "50":{
                FieldType="作者";
                break;
            }
            case "51":{
                FieldType="部门";
                break;
            }
            case "52":{
                FieldType="时间（不可选未来到的日期）";
                break;
            }
            
            case "53":{
                FieldType="数字序列";
                break;
            }
            case "54":{
                FieldType="身份证";
                break;
            }
            case "55":{
                FieldType="复合链接";
                break;
            }
            
            
                
        
            default:
                break;
        }
        return FieldType;
    }
}