package com.yihu.hos.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.gridfs.GridFSDBFile;
import com.yihu.ehr.dbhelper.mongodb.MongodbHelper;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.crawler.model.patient.Patient;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.bson.Document;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/7/22.
 */
public class CollectHelper {

    public static final String dbGridFS = "mydb";//TODO GridFS数据库名  - 提取到配置文件
    public static final String dbDocument = "document";//TODO 非结构化文挡数据库名  - 提取到配置文件

    public static final String basePath = "e:/temp";//TODO 临时文件夹  - 提取到配置文件


    /**
     * 采集档案数据
     *
     * @param index
     * @param tableName
     * @return
     */
    public Object fetchData(Object index, String tableName) {
        return null;
    }

    /**
     * 保存档案数据
     *
     * @param index
     * @param tableName
     * @return
     */
    public Object saveData(Object index, String tableName) {
        return null;
    }

    /**
     * 从Mongodb采集的档案数据生成文件
     *
     * @param patient
     * @param tableName collection名称
     * @return
     * 上传流程：
     * 1. 根据病人索引获取索引档案信息（包含结构化信息（data_sets）和非结构化信息(files) ）
     * 2. 遍历非结构信息中的cda_document_id 获取GridFS中的文件内容
     * 3. document.json文件中，根据获取的文件地址生成 files 的数据
     * 4. document.json文件中，根据结构化信息内容生成 data_sets 的数据
     * 5. 打包上传
     * "files": [
     * {
     * "cda_doc_id": "1",
     * "content": [
     * {
     * "emr_id": "b9205c72-1837-4a7f-a8f1-0c133d178141",
     * "emr_name": "血糖检验报告2",
     * "url": "group1/M00/00/1D/rBFuWldQ-eGABR4XAAAWr0mPExU106.png",
     * "url_scope": "0",
     * "mine_type": "image/png",
     * "note": "备注"
     * }
     * ]
     * }
     * ]
     */
    public static Object dataToFile(Patient patient, String tableName) {
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        //TODO 1. 根据病人索引获取索引档案信息（包含结构化信息（data_sets）
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayNode filesNode = objectMapper.createArrayNode();
        ObjectNode documentNode = null;
        ArrayNode contentNode = null;
        ObjectNode fileNode = null;
        ObjectNode resultNode = objectMapper.createObjectNode();//���ؽ����
        MongodbHelper mongodbHelper = new MongodbHelper(dbDocument);
        FindIterable<Document> documents = mongodbHelper.query(tableName, new BasicDBObject("patient_id", patient.getPatientId()).append("event_no", patient.getEventNo()), null, null);
        MongoCursor<Document> cur = documents.iterator();
        while (cur.hasNext()) {
            Document doc = cur.next();
            //TODO 4. document.json文件中，根据结构化信息内容生成 data_sets 的数据
            JsonNode dataSets = null;
            try {
                String dataStr = ((Document) doc.get("data_sets")).toJson();
                dataSets = objectMapper.readValue(dataStr, JsonNode.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            resultNode.set("data_sets", dataSets);
            List<Document> fileList = (List<Document>) doc.get("files");
            //TODO 2. 遍历非结构信息中的cda_document_id 获取GridFS中的文件内容
            //TODO 3.document.json文件中，根据获取的文件地址生成 files 的数据
            for (Document document : fileList) {
                contentNode = objectMapper.createArrayNode();
                documentNode = objectMapper.createObjectNode();
                List files = (List) document.get("files_id");
                String cdaDocumentId = (String) document.get("cda_doc_id");
                List<GridFSDBFile> fs = GridFSUtil.findFsFiles(dbGridFS, files);
                String filePath = getDocumentDir(patient);
                Map<String, StringBuffer> map = GridFSUtil.downFileList("mydb", filePath, fs);//�ļ�����
                for (Map.Entry<String, StringBuffer> entry : map.entrySet()) {
                    String type = entry.getKey();
                    String nameArr = entry.getValue().toString();
                    fileNode = objectMapper.createObjectNode();
                    fileNode.put("emr_id", UUID.randomUUID().toString());
                    fileNode.put("emr_name", "TODO");
                    fileNode.put("url", nameArr);
                    fileNode.put("url_scope", "TODO");
                    fileNode.put("mine_type", type);

                    contentNode.add(fileNode);
                }
                documentNode.put("cda_doc_id", cdaDocumentId);
                documentNode.set("content", contentNode);
                filesNode.add(documentNode);
            }

            doc.clear();

            resultNode.put("event_type", "TODO");
            resultNode.set("data_sets", dataSets);
            resultNode.set("files", filesNode);
            resultNode.put("patient_id", patient.getPatientId());
            resultNode.put("event_no", patient.getEventNo());
            resultNode.put("org_code", patient.getOrgCode());
            resultNode.put("event_time", patient.getReferenceTime());
            resultNode.put("inner_version", "TODO");
            resultNode.put("create_date", sdf.format(new Date()));
            resultNode.put("demographic_id", patient.getIdCard());

        }
        try {
            String savePath = createDocumentIndex(getDataDirectory(patient), ".json");
            boolean result = FileUtil.writeFile(savePath, objectMapper.writeValueAsString(resultNode), "UTF-8");
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        cur.close();
        return null;
    }


    public static String getDirectory(Patient patient) {
        return basePath + "/" + patient.getOrgCode() + "/" + patient.getOrgCode() + "-" + patient.getPatientId() + "-" + patient.getEventNo();
    }

    /**
     * 获取档案所在路径
     * orgCode-pateintId-eventNo/data
     *
     * @return
     */
    public static String getDataDirectory(Patient patient) {
        return getDirectory(patient) + "/" + "data";
    }

    public static String createZipPath(String basePath, String fileType) {
        UUID uuid = UUID.randomUUID();
        String index = uuid.toString();
        return basePath + "/zip/" + index + fileType;
    }

    public static String createDocumentIndex(String basePath, String fileType) {

        return basePath + "/" + "document" + fileType;
    }

    public static String getDocumentDir(Patient patient) {
        return getDirectory(patient) + "/data/document";
    }

//    public static void main(String[] args) {//
//        Patient patient = new Patient();//
//        patient.setPatientId("1001");//
//        patient.setEventNo("1001");//
//        patient.setOrgCode("41872607-9");//
//        patient.setIdCard("35068119220252141");//
////
//        dataToFile(patient, "CDA_TEST");
//        String json="[{\"HDSA00_01_009\":\"刘文轩\",\"HDSA00_01_011\":\"男\",\"HDSA00_01_012\":\"2004-05-07 13:23:44\",\"HDSA00_01_01\":\"中国\",\"HDSA00_01_014\":\"汉族\",\"HDSA00_01_015\":\"未婚\",\"HDSA00_01_017\":null,\"HDSA00_01_018\":null,\"HDSA00_01_019\":\"00\",\"HDSA00_01_036\":null,\"HDSA00_01_038\":\"其他\",\"HDSA00_01_050\":null,\"PATIENT_ID\":\"11517713\"},{\"HDSA00_01_009\":\"刘文轩\",\"HDSA00_01_011\":\"男\",\"HDSA00_01_012\":\"2004-05-07 13:23:44\",\"HDSA00_01_01\":\"中国\",\"HDSA00_01_014\":\"汉族\",\"HDSA00_01_015\":\"未婚\",\"HDSA00_01_017\":null,\"HDSA00_01_018\":null,\"HDSA00_01_019\":\"00\",\"HDSA00_01_036\":null,\"HDSA00_01_038\":\"其他\",\"HDSA00_01_050\":null,\"PATIENT_ID\":\"111\"}]";
//        ;
//    }
}
