package com.yihu.hos.crawler.origin;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.common.Services;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.file.FtpFileUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.crawler.format.AdapterScheme;
import com.yihu.hos.crawler.model.adapter.AdapterDataSet;
import com.yihu.hos.crawler.model.patient.Patient;
import com.yihu.hos.crawler.model.transform.LogicValues;
import com.yihu.hos.crawler.service.EsbHttp;
import com.yihu.hos.system.model.SystemDatasource;
import com.yihu.hos.system.model.SystemOrganization;
import com.yihu.hos.system.service.OrganizationManager;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * �ݻ�
 *
 * @author Airhead
 * @version 1.0
 * @created 22-5��-2015 11:24:24
 */
public class FileSystemOrigin implements IDataOrigin {

    private static Logger logger = LoggerFactory.getLogger(FileSystemOrigin.class);

    public static String dirHear = "/home/test/patient/";        //病人数据文件根目录
    public static String fileType = "/image/";                    //采集的文件类型文件夹
    protected AdapterScheme adapterScheme;

    public FileSystemOrigin(AdapterScheme adapterScheme) {
        this.adapterScheme=adapterScheme;
    }

    /**
     * ftp采集数据
     * 非结构化档案中，key_words格式暂定为：数据集-数据元，生成文件上传时再转成：数据集.数据源（主要因为mongodb的key不支持特殊符号"."
     * @param patient         病人ID
     * @param orgAgencyOrigin 数据源
     * @param adapterDataSet  适配数据集   @return
     */
    @Override
    public String fecthData(Patient patient, SystemDatasource orgAgencyOrigin, AdapterDataSet adapterDataSet) {
        try {
            String data = null;
            String innerVersion= EsbHttp.getRemoteVersion(patient.getOrgCode());
            List<String> datas = null;
            String agencyCode = patient.getOrgCode();
            String ftpConfig = orgAgencyOrigin.getConfig();
            FtpFileUtil ftp = genFtpUtil(ftpConfig);
            String filePath = "";//远程ftp文件路径
            ObjectNode jsonObject = null;
            boolean patientId = true;
            boolean eventNo = true;
            if (patient.getPatientId() != null && !"".equals(patient.getPatientId())) {
                if (patient.getEventNo() != null && !"".equals(patient.getEventNo())) {
                    //文件路径
                    filePath = dirHear + agencyCode + "/" + patient.getPatientId() + "/" + patient.getEventNo() +  fileType;
                } else {
                    eventNo = false;
                }
            } else {
                patientId = false;
            }

            if (!patientId || !eventNo) {
                throw new Exception("采集病人数据集必须要有病人ID，事件号，数据集名:" + adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
            }

            datas = ftp.readFileData(filePath);
            if (datas != null && datas.size() > 0) {
                data = datas.get(0);
            }
            //TODO "data"内容实现，主要包括key_words和content，

            //json生成
            jsonObject.put("patient_id", patient.getPatientId());
            jsonObject.put("event_no", patient.getEventNo());
            jsonObject.put("org_code", agencyCode);
            jsonObject.put("inner_version", innerVersion);
            jsonObject.put("create_date", DateUtil.toString(new Date(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            jsonObject.put("event_time", patient.getReferenceTime());//DateUtil.toString(patient.getReferenceTime(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT)
            if (StringUtil.isEmpty(patient.getReUploadFlg())) {
                jsonObject.put("reUploadFlg", LogicValues.LOGIC_FALSE);
            } else {
                jsonObject.put("reUploadFlg", patient.getReUploadFlg());
            }
            return jsonObject.toString();
        } catch (SQLException e) {
//            e.printStackTrace();
            logger.error("", e);
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("", e);
        }
        return null;
    }

    /**
     * 获取病人列表
     *
     * @param orgAgencyOrigin 数据源
     * @param adapterDataSet  适配数据集
     * @param condition       查询条件
     * @return 病人集合
     */
    @Override
    public List<Patient> getPatientList(SystemDatasource orgAgencyOrigin, AdapterDataSet adapterDataSet, Map<String, Object> condition) {
        ArrayList<Patient> patientList = new ArrayList<>();
        try {
            String ftpConfig = orgAgencyOrigin.getConfig();
            FtpFileUtil ftp = genFtpUtil(ftpConfig);

//			StdDataSet stdDataSet = adapterDataSet.getStdDataSet();
            OrganizationManager organizationManager= SpringBeanUtil.getService(Services.Organization);
            SystemOrganization orgAgency =organizationManager.getOrgById(orgAgencyOrigin.getOrgId());
            String agencyCode =orgAgency.getCode();
            List<Map<String, String>> patientMaps = ftp.getPatientList(dirHear, agencyCode);

            if (patientMaps != null && patientMaps.size() > 0) {
                for (Map<String, String> patientMap : patientMaps) {
                    Patient patient = new Patient();
                    String patientId = patientMap.get("patient_id");
                    String eventNo = patientMap.get("event_no");
                    if (orgAgency == null) {
                        logger.error("获取病人列表错误,无法获取机构代码.");
                        continue;
                    }
                    patient.setPatientId(patientId);
                    patient.setEventNo(eventNo);
                    patient.setReferenceTime(DateUtil.toString(new Date(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT));//暂设置为当前时间
                    patient.setOrgCode(orgAgency.getCode());

                    patientList.add(patient);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("", e);
        }

        return patientList;
    }

    /**
     * 清除ftp数据
     *
     * @param patient
     * @param orgAgencyOrigin
     * @param adapterDataSet  @return
     */
    @Override
    public boolean clearData(Patient patient, SystemDatasource orgAgencyOrigin, AdapterDataSet adapterDataSet) {
        try {
            boolean clear = false;
            String agencyCode = patient.getOrgCode();
            String ftpConfig = orgAgencyOrigin.getConfig();
            FtpFileUtil ftp = genFtpUtil(ftpConfig);
            String filePath = "";//远程ftp文件路径

            boolean patientId = true;
            boolean eventNo = true;
            if (patient.getPatientId() != null && !"".equals(patient.getPatientId())) {
                if (patient.getEventNo() != null && !"".equals(patient.getEventNo())) {
                    //文件路径
                    filePath = dirHear + agencyCode + "/" + patient.getPatientId() + "/" + patient.getEventNo()  + fileType;
                } else {
                    eventNo = false;
                }
            } else {
                patientId = false;
            }

            if (!patientId || !eventNo) {
                throw new Exception("清除病人数据集必须要有病人ID，事件号，数据集名:" + adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
            }

            ftp.connect();
            clear = ftp.removeData(filePath);
            ftp.closeConnect();
            return clear;
        } catch (SQLException e) {
            e.printStackTrace();
            logger.error("", e);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("", e);
        }


        return false;
    }

    @Override
    public Date getServerDateTime(SystemDatasource orgAgencyOrigin) {
        return null;
    }

    public void finalize() throws Throwable {

    }

    public FtpFileUtil genFtpUtil(String ftpConfig) {
        ObjectMapper mapper = new ObjectMapper();
        FtpFileUtil ftpUtil = null;
        JsonNode rootNode = null;
        try {
            rootNode = mapper.readValue(ftpConfig, JsonNode.class);
            String username = rootNode.path("username").asText();
            String password = rootNode.path("password").asText();
            String host = rootNode.path("host").asText();
            int port = rootNode.path("port").asInt();
            ftpUtil = new FtpFileUtil(username, password, host, port);
        } catch (IOException e) {
            logger.error("获取Ftp服务器配置失败", e);
            e.printStackTrace();
        }
        return ftpUtil;
    }

}//end FileSystemOrigin