package com.trs.web2frame.util;

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

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by 1250052380@qq.com on 2015/5/19.
 */
public class ClassCompareExport {
    private static String XMLFilePath1="C:\\Users\\esint007\\Downloads\\CLASSINFO文种.xml";
    private static String XMLFilePath2="C:\\Users\\esint007\\Downloads\\CLASSINFO文种new.xml";
    private static String EXCELFilePath="D:\\work\\ViewInfo.xls";

    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  xml1=readTxtFile(XMLFilePath1);
        JSONObject json1=xml2JSON(xml1.getBytes());
        String  xml2=readTxtFile(XMLFilePath2);
        JSONObject json2=xml2JSON(xml2.getBytes());
        System.out.println(json1.toJSONString());
        ViewToExcel(json1.toJSONString(),json2.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 jsonStr1,String jsonStr2){
        File xlsFile = new File(EXCELFilePath);//生成EXXCEl的地址
        
        try {
             // 创建一个工作簿
            WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
            WritableSheet sheet0 = workbook.createSheet("对比结果",0);

            //创建两个ListMap
            List<Map<String,Object>> listmap1=new ArrayList<>();
            List<Map<String,Object>> listmap2=new ArrayList<>();
            
            
            sheet0.addCell(new Label(0,0,"旧"));
            sheet0.addCell(new Label(1,0,"新"));
            JSONObject jsonObject1=JSONObject.parseObject(jsonStr1);
            String XWCMCLASSINFOS1=jsonObject1.get("XWCMCLASSINFOS").toString();
            String XWCMCLASSINFO1=JSONObject.parseObject(XWCMCLASSINFOS1).get("XWCMCLASSINFO").toString();
            JSONArray array_XWCMCLASSINFO1=JSONArray.parseArray(XWCMCLASSINFO1);
            listmap1=GetAllClassInfo(array_XWCMCLASSINFO1);

            JSONObject jsonObject2=JSONObject.parseObject(jsonStr2);
            String XWCMCLASSINFOS2=jsonObject2.get("XWCMCLASSINFOS").toString();
            String XWCMCLASSINFO2=JSONObject.parseObject(XWCMCLASSINFOS2).get("XWCMCLASSINFO").toString();
            JSONArray array_XWCMCLASSINFO2=JSONArray.parseArray(XWCMCLASSINFO2);
            listmap2=GetAllClassInfo(array_XWCMCLASSINFO2);
           

            for (int j=0;j<listmap1.size();j++) {
                String CNAME1=listmap1.get(j).get("CNAME").toString();
                String CLASSINFOID1=listmap1.get(j).get("CLASSINFOID").toString();
                sheet0.addCell(new Label(0,j+1,CLASSINFOID1));
                for (int i = 0; i < listmap2.size(); i++) {
                    String CNAME2=listmap2.get(i).get("CNAME").toString();
                    if(CNAME1.equals(CNAME2)){
                        String CLASSINFOID2=listmap2.get(i).get("CLASSINFOID").toString();
                        sheet0.addCell(new Label(1,j+1,CLASSINFOID2));
                    }
                }
            }
             
            workbook.write();
            workbook.close();
            //System.out.println(XWCMTABLEINFO);
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("ViewToExcel异常！："+e.getMessage());
        }
    }

    public static List<Map<String,Object>> GetAllClassInfo(JSONArray array_XWCMCLASSINFO){
        List<Map<String,Object>> listmap1=new ArrayList<>();
        try {
            
        //循环各个json下的分类信息
        for (int i = 0; i < array_XWCMCLASSINFO.size(); i++) {
            Map<String,Object> map1=new HashMap<>();
            String str_PROPERTIES =JSONObject.parseObject(array_XWCMCLASSINFO.get(i).toString()).get("PROPERTIES").toString();
            String CNAME=JSONObject.parseObject(JSONArray.parseArray(str_PROPERTIES).get(0).toString()).getString("CNAME");//
            String CLASSINFOID=JSONObject.parseObject(JSONArray.parseArray(str_PROPERTIES).get(0).toString()).getString("CLASSINFOID");//
            CNAME=CNAME.substring(2, CNAME.lastIndexOf("]")-1);
            CLASSINFOID=CLASSINFOID.substring(2, CLASSINFOID.lastIndexOf("]")-1);
            map1.put("CNAME", CNAME);
            map1.put("CLASSINFOID", CLASSINFOID);

            String XWCMCLASSINFOS =JSONObject.parseObject(array_XWCMCLASSINFO.get(i).toString()).getString("XWCMCLASSINFOS");
            if(XWCMCLASSINFOS!=null){
                JSONArray array_XWCMCLASSINFOS1=JSONArray.parseArray(XWCMCLASSINFOS);
                String XWCMCLASSINFO=JSONObject.parseObject(array_XWCMCLASSINFOS1.get(0).toString()).get("XWCMCLASSINFO").toString();
                JSONArray array_XWCMCLASSINFO1=JSONArray.parseArray(XWCMCLASSINFO);
    
                List<Map<String,Object>> listmap=GetAllClassInfo(array_XWCMCLASSINFO1);
                for (Map<String,Object> map : listmap) {
                    listmap1.add(map);
                }    
            }
            
            listmap1.add(map1);
        }
        } catch (Exception e) {
            //TODO: handle exception
            Log_Exception.Error_txt("GetAllClassInfo()异常！"+e.getMessage());
        }
        return listmap1;
    }

}